{"focal_file": "lis.py", "focal_class": null, "focal_method": "lis", "tests": "import unittest\n\nclass Test_lis(unittest.TestCase):\n def test_lis(self):\n for l, longest_s in zip(self.lists, self.list_lis):\n self.assertEqual(longest_s, lis(l))\n", "method_code": "def lis(sequence):\n list_of_sequences = [[sequence[0]]]\n for item in sequence:\n if item > list_of_sequences[-1][-1]:\n new_s = list(list_of_sequences[-1])\n new_s.append(item)\n list_of_sequences.append(new_s)\n elif item < list_of_sequences[0][0]:\n list_of_sequences[0][0] = item\n else:\n list_of_sequences = clone_extend_remove(item, list_of_sequences)\n return list_of_sequences[-1]", "context": "def lis(sequence): ...\ndef generate_random_sequence(length=50): ...\ndef lis2(sequence): ...\ndef lis(sequence): ...\ndef clone_extend_remove(item, list_of_sequences): ...\ndef remove_lists_of_same_length(list1, list_of_lists): ...\n", "repository": "chuckha/LongestIncreasingSubsequence", "test_name": "test_lis", "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_000001.py"} {"focal_file": "lis.py", "focal_class": null, "focal_method": "lis2", "tests": "import unittest\n\nclass Test_lis2(unittest.TestCase):\n def test_lis2(self):\n for l, longest_s in zip(self.lists, self.list_lis):\n self.assertEqual(len(longest_s), lis2(l))\n", "method_code": "def lis2(sequence):\n lengths = []\n for i, s in enumerate(sequence):\n if i == 0:\n lengths.append(1)\n else:\n possibles = []\n for j, length in enumerate(lengths):\n if s > sequence[j]:\n possibles.append(length + 1)\n else:\n possibles.append(1)\n lengths.append(max(possibles))\n return max(lengths)", "context": "def lis2(sequence): ...\ndef generate_random_sequence(length=50): ...\ndef lis2(sequence): ...\ndef lis(sequence): ...\ndef clone_extend_remove(item, list_of_sequences): ...\ndef remove_lists_of_same_length(list1, list_of_lists): ...\n", "repository": "chuckha/LongestIncreasingSubsequence", "test_name": "test_lis2", "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_000002.py"} {"focal_file": "equation.py", "focal_class": null, "focal_method": "generate_numbers", "tests": "import unittest\n\nclass Test_generate_numbers(unittest.TestCase):\n def test_generate_number(self):\n self.assertEqual(generate_numbers(self.num_array, [[8, 4, 1, 2]]), [8412])\n", "method_code": "def generate_numbers(num_array, patterns):\n return [int(''.join([str(num_array[i]) for i in pattern])) for pattern in patterns]", "context": "def generate_numbers(num_array, patterns): ...\ndef patterns(words): ...\ndef generate_numbers(num_array, patterns): ...\n", "repository": "chuckha/Cryptarithm", "test_name": "test_generate_number", "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_000003.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 user = User(password='password')\n db.session.add(user)\n db.session.commit()\n token = user.generate_confirmation_token()\n self.assertTrue(user.confirm(token))\n\n def test_invalid_confirmation_token(self):\n user = User(password='password')\n user1 = User(password='passwords')\n db.session.add(user)\n db.session.add(user1)\n db.session.commit()\n token = user.generate_confirmation_token()\n self.assertFalse(user1.confirm(token))\n\n def test_expired_confirmation_token(self):\n user = User(password='password')\n db.session.add(user)\n db.session.commit()\n token = user.generate_confirmation_token(1)\n time.sleep(2)\n self.assertFalse(user.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}).decode('utf-8')\n ", "context": "class User(UserMixindb.Model):\n def generate_confirmation_token(self, expiration=3600): ...\n def to_json(self): ...\n def __init__(self, **kwargs): ...\n def add_self_follows(): ...\n def gravatar_hash(self): ...\n def ping(self): ...\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(token, new_password): ...\n def generate_email_update_token(self, new_email, expiration=3600): ...\n def update_email(self, token): ...\n def can(self, perm): ...\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_followed_by(self, user): ...\n def is_following(self, user): ...\n def follow_posts(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 username = db.Column(db.String(64), unique=True, index=True)\n email = db.Column(db.String(64), unique=True, index=True)\n password_hash = db.Column(db.String(128), nullable=False)\n confirmed = db.Column(db.Boolean, default=False)\n role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))\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": "vshalt/chirp", "test_name": "test_valid_confirmation_token", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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_000004.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 user = User(password='password')\n db.session.add(user)\n db.session.commit()\n token = user.generate_reset_token()\n self.assertTrue(user.reset_password(token, 'new_password'))\n self.assertTrue(user.verify_password('new_password'))\n\n def test_invalid_reset_token(self):\n user = User(password='password')\n db.session.add(user)\n db.session.commit()\n token = user.generate_reset_token()\n self.assertFalse(User.reset_password(token + 'a', 'new_password'))\n self.assertTrue(user.verify_password('password'))\n", "method_code": " def generate_reset_token(self, expiration=3600):\n s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration)\n return s.dumps({'reset': self.id}).decode('utf-8')\n ", "context": "class User(UserMixindb.Model):\n def generate_reset_token(self, expiration=3600): ...\n def to_json(self): ...\n def __init__(self, **kwargs): ...\n def add_self_follows(): ...\n def gravatar_hash(self): ...\n def ping(self): ...\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(token, new_password): ...\n def generate_email_update_token(self, new_email, expiration=3600): ...\n def update_email(self, token): ...\n def can(self, perm): ...\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_followed_by(self, user): ...\n def is_following(self, user): ...\n def follow_posts(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 username = db.Column(db.String(64), unique=True, index=True)\n email = db.Column(db.String(64), unique=True, index=True)\n password_hash = db.Column(db.String(128), nullable=False)\n confirmed = db.Column(db.Boolean, default=False)\n role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))\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": "vshalt/chirp", "test_name": "test_valid_reset_token", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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_000005.py"} {"focal_file": "app/models.py", "focal_class": "User", "focal_method": "generate_email_update_token", "tests": "import unittest\n\nclass Test_User_generate_email_update_token(unittest.TestCase):\n def test_valid_email_change_token(self):\n user = User(password='password')\n db.session.add(user)\n db.session.commit()\n token = user.generate_email_update_token('example@mail.com')\n self.assertTrue(user.update_email(token))\n self.assertTrue(user.email == 'example@mail.com')\n\n def test_invalid_email_change_token(self):\n user = User(email='name@mail.com', password='password')\n user1 = User(email='mail@mail.com', password='password1')\n db.session.add(user)\n db.session.add(user1)\n db.session.commit()\n token = user.generate_email_update_token('new@mail.com')\n self.assertFalse(user1.update_email(token))\n self.assertTrue(user.email == 'name@mail.com')\n", "method_code": " def generate_email_update_token(self, new_email, expiration=3600):\n s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration)\n return s.dumps({'update_email': self.id, 'new_email': new_email}).decode('utf-8')\n ", "context": "class User(UserMixindb.Model):\n def generate_email_update_token(self, new_email, expiration=3600): ...\n def to_json(self): ...\n def __init__(self, **kwargs): ...\n def add_self_follows(): ...\n def gravatar_hash(self): ...\n def ping(self): ...\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(token, new_password): ...\n def update_email(self, token): ...\n def can(self, perm): ...\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_followed_by(self, user): ...\n def is_following(self, user): ...\n def follow_posts(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 username = db.Column(db.String(64), unique=True, index=True)\n email = db.Column(db.String(64), unique=True, index=True)\n password_hash = db.Column(db.String(128), nullable=False)\n confirmed = db.Column(db.Boolean, default=False)\n role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))\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": "vshalt/chirp", "test_name": "test_valid_email_change_token", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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, 1, 0, 0], "pynose_source_file": "test_000006.py"} {"focal_file": "app/models.py", "focal_class": "User", "focal_method": "update_email", "tests": "import unittest\n\nclass Test_User_update_email(unittest.TestCase):\n def test_duplicate_email(self):\n user = User(email='sername@mail.com', password='password')\n user1 = User(email='ail@mail.com', password='password1')\n db.session.add(user)\n db.session.add(user1)\n db.session.commit()\n token = user.generate_email_update_token('ail@mail.com')\n self.assertFalse(user.update_email(token))\n self.assertTrue(user.email == 'sername@mail.com')\n", "method_code": " def update_email(self, token):\n s = Serializer(current_app.config['SECRET_KEY'])\n try:\n data = s.loads(token.encode('utf-8'))\n except:\n return False\n if data.get('update_email') != self.id:\n return False\n new_email = data.get('new_email')\n if new_email is None:\n return False\n if self.query.filter_by(email=new_email).first() is not None:\n return False\n else:\n self.email = new_email\n self.avatar_hash = self.gravatar_hash()\n db.session.add(self)\n return True\n ", "context": "class User(UserMixindb.Model):\n def update_email(self, token): ...\n def to_json(self): ...\n def __init__(self, **kwargs): ...\n def add_self_follows(): ...\n def gravatar_hash(self): ...\n def ping(self): ...\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(token, new_password): ...\n def generate_email_update_token(self, new_email, expiration=3600): ...\n def can(self, perm): ...\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_followed_by(self, user): ...\n def is_following(self, user): ...\n def follow_posts(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 username = db.Column(db.String(64), unique=True, index=True)\n email = db.Column(db.String(64), unique=True, index=True)\n password_hash = db.Column(db.String(128), nullable=False)\n confirmed = db.Column(db.Boolean, default=False)\n role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))\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": "vshalt/chirp", "test_name": "test_duplicate_email", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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, 1, 0, 0], "pynose_source_file": "test_000007.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 user = User(password='password')\n db.session.add(user)\n db.session.commit()\n last_seen_before = user.last_seen\n user.ping()\n self.assertTrue(user.last_seen > last_seen_before)\n", "method_code": " def ping(self):\n self.last_seen = datetime.utcnow()\n db.session.add(self)\n db.session.commit()\n ", "context": "class User(UserMixindb.Model):\n def ping(self): ...\n def to_json(self): ...\n def __init__(self, **kwargs): ...\n def add_self_follows(): ...\n def gravatar_hash(self): ...\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(token, new_password): ...\n def generate_email_update_token(self, new_email, expiration=3600): ...\n def update_email(self, token): ...\n def can(self, perm): ...\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_followed_by(self, user): ...\n def is_following(self, user): ...\n def follow_posts(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 username = db.Column(db.String(64), unique=True, index=True)\n email = db.Column(db.String(64), unique=True, index=True)\n password_hash = db.Column(db.String(128), nullable=False)\n confirmed = db.Column(db.Boolean, default=False)\n role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))\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": "vshalt/chirp", "test_name": "test_ping", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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, 1, 0, 0], "pynose_source_file": "test_000008.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 user = User(email='john@example.com', password='catdog')\n with self.app.test_request_context('/'):\n gravatar = user.gravatar()\n gravatar_256 = user.gravatar(size=256)\n gravatar_pg = user.gravatar(rating='pg')\n gravatar_retro = user.gravatar(default='retro')\n self.assertTrue('https://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", "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 = 'https://www.gravatar.com/avatar'\n hash = self.avatar_hash or self.gravatar_hash()\n return f'{url}/{hash}?s={size}&d={default}&r={rating}'\n ", "context": "class User(UserMixindb.Model):\n def gravatar(self, size=100, default='identicon', rating='g'): ...\n def to_json(self): ...\n def __init__(self, **kwargs): ...\n def add_self_follows(): ...\n def gravatar_hash(self): ...\n def ping(self): ...\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(token, new_password): ...\n def generate_email_update_token(self, new_email, expiration=3600): ...\n def update_email(self, token): ...\n def can(self, perm): ...\n def is_administrator(self): ...\n def follow(self, user): ...\n def unfollow(self, user): ...\n def is_followed_by(self, user): ...\n def is_following(self, user): ...\n def follow_posts(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 username = db.Column(db.String(64), unique=True, index=True)\n email = db.Column(db.String(64), unique=True, index=True)\n password_hash = db.Column(db.String(128), nullable=False)\n confirmed = db.Column(db.Boolean, default=False)\n role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))\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": "vshalt/chirp", "test_name": "test_gravatar", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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, 1, 0, 0], "pynose_source_file": "test_000009.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 user1 = User(email='john@example.com', password='cat')\n user2 = User(email='susan@example.org', password='dog')\n db.session.add(user1)\n db.session.add(user2)\n db.session.commit()\n self.assertFalse(user1.is_following(user2))\n self.assertFalse(user1.is_followed_by(user2))\n timestamp_before = datetime.utcnow()\n user1.follow(user2)\n db.session.add(user1)\n db.session.commit()\n timestamp_after = datetime.utcnow()\n self.assertTrue(user1.is_following(user2))\n self.assertFalse(user1.is_followed_by(user2))\n self.assertTrue(user2.is_followed_by(user1))\n self.assertTrue(user1.followed.count() == 2)\n self.assertTrue(user2.followers.count() == 2)\n f = user1.followed.all()[-1]\n self.assertTrue(f.followed == user2)\n self.assertTrue(timestamp_before <= f.timestamp <= timestamp_after)\n f = user2.followers.all()[-1]\n self.assertTrue(f.follower == user1)\n user1.unfollow(user2)\n db.session.add(user1)\n db.session.commit()\n self.assertTrue(user1.followed.count() == 1)\n self.assertTrue(user2.followers.count() == 1)\n self.assertTrue(Follow.query.count() == 2)\n user2.follow(user1)\n db.session.add(user1)\n db.session.add(user2)\n db.session.commit()\n db.session.delete(user2)\n db.session.commit()\n self.assertTrue(Follow.query.count() == 1)\n", "method_code": " def is_following(self, user):\n if user.id is None:\n return False\n else:\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 to_json(self): ...\n def __init__(self, **kwargs): ...\n def add_self_follows(): ...\n def gravatar_hash(self): ...\n def ping(self): ...\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(token, new_password): ...\n def generate_email_update_token(self, new_email, expiration=3600): ...\n def update_email(self, token): ...\n def can(self, perm): ...\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_followed_by(self, user): ...\n def follow_posts(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 username = db.Column(db.String(64), unique=True, index=True)\n email = db.Column(db.String(64), unique=True, index=True)\n password_hash = db.Column(db.String(128), nullable=False)\n confirmed = db.Column(db.Boolean, default=False)\n role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))\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": "vshalt/chirp", "test_name": "test_follows", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000010.py"} {"focal_file": "app/models.py", "focal_class": "User", "focal_method": "to_json", "tests": "import unittest\n\nclass Test_User_to_json(unittest.TestCase):\n def test_to_json(self):\n user = User(email='john@example.com', password='cat')\n db.session.add(user)\n db.session.commit()\n with self.app.test_request_context('/'):\n json_user = user.to_json()\n expected_keys = ['user_url', 'username', 'member_since', 'last_seen', 'posts', 'followed_posts', 'posts_count']\n self.assertEqual(sorted(json_user.keys()), sorted(expected_keys))\n self.assertEqual('/api/v1/users/' + str(user.id), json_user['user_url'])\n", "method_code": " def to_json(self):\n user_json = {'user_url': url_for('api.get_user', id=self.id), 'username': self.username, 'member_since': self.member_since, 'last_seen': self.last_seen, 'posts': url_for('api.get_user_posts', id=self.id), 'followed_posts': url_for('api.get_user_followed_posts', id=self.id), 'posts_count': self.posts.count()}\n return user_json\n ", "context": "class User(UserMixindb.Model):\n def to_json(self): ...\n def __init__(self, **kwargs): ...\n def add_self_follows(): ...\n def gravatar_hash(self): ...\n def ping(self): ...\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(token, new_password): ...\n def generate_email_update_token(self, new_email, expiration=3600): ...\n def update_email(self, token): ...\n def can(self, perm): ...\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_followed_by(self, user): ...\n def is_following(self, user): ...\n def follow_posts(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 username = db.Column(db.String(64), unique=True, index=True)\n email = db.Column(db.String(64), unique=True, index=True)\n password_hash = db.Column(db.String(128), nullable=False)\n confirmed = db.Column(db.Boolean, default=False)\n role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))\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": "vshalt/chirp", "test_name": "test_to_json", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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_000011.py"} {"focal_file": "client/stt.py", "focal_class": null, "focal_method": "transcribe", "tests": "import unittest\n\nclass Test_transcribe(unittest.TestCase):\n def testTranscribe(self):\n \"\"\"\n Does Jasper recognize 'time' (i.e., active listen)?\n \"\"\"\n with open(self.time_clip, mode='rb') as f:\n transcription = self.active_stt_engine.transcribe(f)\n self.assertIn('TIME', transcription)\n", "method_code": " def transcribe(self, fp):\n pass\n ", "context": "class AbstractSTTEngine(object):\n @abstractmethod\n def transcribe(self, fp): ...\n def get_config(cls): ...\n def get_instance(cls, vocabulary_name, phrases): ...\n def get_passive_instance(cls): ...\n def get_active_instance(cls): ...\n def is_available(cls): ...\n\n __metaclass__ = ABCMeta\n VOCABULARY_TYPE = None\n", "repository": "High-Tech-Team/Jasper", "test_name": "testTranscribe", "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_000012.py"} {"focal_file": "client/g2p.py", "focal_class": null, "focal_method": "translate", "tests": "import unittest\n\nclass Test_translate(unittest.TestCase):\n def testTranslateWord(self):\n with mock.patch('subprocess.Popen', return_value=TestPatchedG2P.DummyProc()):\n for word in WORDS:\n self.assertIn(word, self.g2pconv.translate(word).keys())\n", "method_code": " def translate(self, words):\n if type(words) is str or len(words) == 1:\n self._logger.debug('Converting single word to phonemes')\n output = self._translate_word(words if type(words) is str else words[0])\n else:\n self._logger.debug('Converting %d words to phonemes', len(words))\n output = self._translate_words(words)\n self._logger.debug('G2P conversion returned phonemes for %d words', len(output))\n return output\n ", "context": "class PhonetisaurusG2P(object):\n def translate(self, words): ...\n def execute(cls, fst_model, input, is_file=False, nbest=None): ...\n def get_config(cls): ...\n def __new__(cls, fst_model=None, *args, **kwargs): ...\n def __init__(self, fst_model=None, nbest=None): ...\n def _translate_word(self, word): ...\n def _translate_words(self, words): ...\n\n self._logger = logging.getLogger(__name__)\n self.fst_model = os.path.abspath(fst_model)\n self.nbest = nbest\n\n PATTERN = re.compile('^(?P.+)\\\\t(?P\\\\d+\\\\.\\\\d+)\\\\t ' + '(?P.*) ', re.MULTILINE)\n", "repository": "High-Tech-Team/Jasper", "test_name": "testTranslateWord", "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_000013.py"} {"focal_file": "scripts/MyXBee/frame.py", "focal_class": null, "focal_method": "remaining_bytes", "tests": "import unittest\n\nclass Test_remaining_bytes(unittest.TestCase):\n def test_remaining_bytes(self):\n \"\"\"\n remaining_bytes() should provide accurate indication\n of remaining bytes required before parsing a packet\n \"\"\"\n api_frame = APIFrame()\n frame = b'~\\x00\\x04\\x00\\x00\\x00\\x00\\xff'\n self.assertEqual(api_frame.remaining_bytes(), 3)\n api_frame.fill(frame[0])\n self.assertEqual(api_frame.remaining_bytes(), 2)\n api_frame.fill(frame[1])\n self.assertEqual(api_frame.remaining_bytes(), 1)\n api_frame.fill(frame[2])\n self.assertEqual(api_frame.remaining_bytes(), 5)\n api_frame.fill(frame[3])\n self.assertEqual(api_frame.remaining_bytes(), 4)\n", "method_code": " def remaining_bytes(self):\n remaining = 3\n if len(self.raw_data) >= 3:\n raw_len = self.raw_data[1:3]\n data_len = struct.unpack('> h', raw_len)[0]\n remaining += data_len\n remaining += 1\n return remaining - len(self.raw_data)\n ", "context": "class APIFrame():\n def remaining_bytes(self): ...\n def __init__(self, data=b'', escaped=False): ...\n def checksum(self): ...\n def verify(self, chksum): ...\n def len_bytes(self): ...\n def output(self): ...\n def escape(data): ...\n def fill(self, byte): ...\n def parse(self): ...\n\n self.data = data\n self.raw_data = b''\n self.escaped = escaped\n self._unescape_next_byte = False\n\n START_BYTE = b'~'\n ESCAPE_BYTE = b'}'\n XON_BYTE = b'\\x11'\n XOFF_BYTE = b'\\x13'\n ESCAPE_BYTES = (START_BYTE, ESCAPE_BYTE, XON_BYTE, XOFF_BYTE)\n", "repository": "dengshuan/sunist", "test_name": "test_remaining_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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000014.py"} {"focal_file": "scripts/MyXBee/base.py", "focal_class": null, "focal_method": "_write", "tests": "import unittest\n\nclass Test_write(unittest.TestCase):\n def test_write(self):\n \"\"\"\n _write method should write the expected data to the serial\n device\n \"\"\"\n device = FakeDevice()\n xbee = XBeeBase(device)\n xbee._write(b'\\x00')\n expected_frame = b'~\\x00\\x01\\x00\\xff'\n self.assertEqual(device.data, expected_frame)\n\n def test_write_again(self):\n \"\"\"\n _write method should write the expected data to the serial\n device\n \"\"\"\n device = FakeDevice()\n xbee = XBeeBase(device)\n xbee._write(b'\\x00\\x01\\x02')\n expected_frame = b'~\\x00\\x03\\x00\\x01\\x02\\xfc'\n self.assertEqual(device.data, expected_frame)\n", "method_code": " def _write(self, data):\n \"\"\"\n _write: binary data -> None\n \n Packages the given binary data in an API frame and writes the \n result to the serial port\n \"\"\"\n frame = APIFrame(data, self._escaped).output()\n self.serial.write(frame)\n ", "context": "class XBeeBase(threading.Thread):\n def _write(self, data): ...\n def __init__(self, ser, shorthand=True, callback=None, escaped=False): ...\n def halt(self): ...\n def run(self): ...\n def _wait_for_frame(self): ...\n def _build_command(self, cmd, **kwargs): ...\n def _split_response(self, data): ...\n def _parse_samples_header(self, io_bytes): ...\n def _parse_samples(self, io_bytes): ...\n def send(self, cmd, **kwargs): ...\n def wait_read_frame(self): ...\n def __getattr__(self, name): ...\n\n self.serial = ser\n self.shorthand = shorthand\n self._callback = None\n self._thread_continue = False\n self._escaped = escaped\n", "repository": "dengshuan/sunist", "test_name": "test_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_000015.py"} {"focal_file": "ITR/temperature_score.py", "focal_class": "TemperatureScore", "focal_method": "calculate", "tests": "import unittest\n\nclass Test_TemperatureScore_calculate(unittest.TestCase):\n def test_score_cap(self):\n companies, targets, pf_companies = self.create_base_companies(['A'])\n data_provider = TestDataProvider(companies=companies, targets=targets)\n temp_score = TemperatureScore(time_frames=[ETimeFrames.LONG], scopes=[EScope.S1S2], aggregation_method=PortfolioAggregationMethod.WATS)\n portfolio_data = ITR.utils.get_data([data_provider], pf_companies)\n scores = temp_score.calculate(portfolio_data)\n agg_scores = temp_score.aggregate_scores(scores)\n", "method_code": " def calculate(self, data: Optional[pd.DataFrame]=None, data_providers: Optional[List[data.DataProvider]]=None, portfolio: Optional[List[PortfolioCompany]]=None):\n \"\"\"\n Calculate the temperature for a dataframe of company data. The columns in the data frame should be a combination\n of IDataProviderTarget and IDataProviderCompany.\n \n :param data: The data set (or None if the data should be retrieved)\n :param data_providers: A list of DataProvider instances. Optional, only required if data is empty.\n :param portfolio: A list of PortfolioCompany models. Optional, only required if data is empty.\n :return: A data frame containing all relevant information for the targets and companies\n \"\"\"\n if data is None:\n if data_providers is not None and portfolio is not None:\n data = utils.get_data(data_providers, portfolio)\n else:\n raise ValueError('You need to pass and either a data set or a list of data providers and companies')\n data = self._prepare_data(data)\n if EScope.S1S2S3 in self.scopes:\n self._check_column(data, self.c.COLS.GHG_SCOPE12)\n self._check_column(data, self.c.COLS.GHG_SCOPE3)\n data = self._calculate_company_score(data)\n data = data[data[self.c.COLS.SCOPE].isin(self.scopes)]\n data[self.c.COLS.TEMPERATURE_SCORE] = data[self.c.COLS.TEMPERATURE_SCORE].round(2)\n return data\n ", "context": "class TemperatureScore(PortfolioAggregation):\n def calculate(self, data: Optional[pd.DataFrame]=None, data_providers: Optional[List[data.DataProvider]]=None, portfolio: Optional[List[PortfolioCompany]]=None): ...\n def __init__(self, time_frames: List[ETimeFrames], scopes: List[EScope], fallback_score: float=3.2, model: int=4, aggregation_method: PortfolioAggregationMethod=PortfolioAggregationMethod.WATS, grouping: Optional[List]=None, config: Type[TemperatureScoreConfig]=TemperatureScoreConfig): ...\n def get_annual_reduction_rate(self, target: pd.Series) -> Optional[float]: ...\n def get_score(self, target: pd.Series) -> Tuple[float, float]: ...\n def get_ghc_temperature_score(self, row: pd.Series, company_data: pd.DataFrame) -> Tuple[float, float]: ...\n def get_default_score(self, target: pd.Series) -> float: ...\n def _prepare_data(self, data: pd.DataFrame): ...\n def _calculate_company_score(self, data): ...\n def _get_aggregations(self, data: pd.DataFrame, total_companies: int) -> Tuple[Aggregation, pd.Series, pd.Series]: ...\n def _get_score_aggregation(self, data: pd.DataFrame, time_frame: ETimeFrames, scope: EScope) -> Optional[ScoreAggregation]: ...\n def aggregate_scores(self, data: pd.DataFrame) -> ScoreAggregations: ...\n def cap_scores(self, scores: pd.DataFrame) -> pd.DataFrame: ...\n def anonymize_data_dump(self, scores: pd.DataFrame) -> pd.DataFrame: ...\n\n self.model = model\n self.fallback_score = fallback_score\n self.time_frames = time_frames\n self.scopes = scopes\n", "repository": "os-c/ITR", "test_name": "test_score_cap", "smells": [1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 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_000016.py"} {"focal_file": "ITR/interfaces.py", "focal_class": null, "focal_method": "validate_e", "tests": "import unittest\n\nclass Test_validate_e(unittest.TestCase):\n def test_IDataProviderTarget(self):\n self.assertEqual(IDataProviderTarget.validate_e('test'), 'test')\n self.assertIsNone(IDataProviderTarget.validate_e(''))\n self.assertIsNone(IDataProviderTarget.validate_e('nan'))\n", "method_code": " def validate_e(cls, val):\n if val == '' or val == 'nan' or pd.isnull(val):\n return None\n return val\n ", "context": "class IDataProviderTarget(BaseModel):\n @validator('start_year', pre=True, always=False)\n def validate_e(cls, val): ...", "repository": "os-c/ITR", "test_name": "test_IDataProviderTarget", "smells": [1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 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_000017.py"} {"focal_file": "ITR/portfolio_aggregation.py", "focal_class": null, "focal_method": "is_emissions_based", "tests": "import unittest\n\nclass Test_is_emissions_based(unittest.TestCase):\n def test_is_emissions_based(self):\n self.assertTrue(PortfolioAggregationMethod.is_emissions_based(PortfolioAggregationMethod.MOTS))\n self.assertTrue(PortfolioAggregationMethod.is_emissions_based(PortfolioAggregationMethod.EOTS))\n self.assertTrue(PortfolioAggregationMethod.is_emissions_based(PortfolioAggregationMethod.ECOTS))\n self.assertTrue(PortfolioAggregationMethod.is_emissions_based(PortfolioAggregationMethod.AOTS))\n self.assertTrue(PortfolioAggregationMethod.is_emissions_based(PortfolioAggregationMethod.ROTS))\n self.assertFalse(PortfolioAggregationMethod.is_emissions_based(PortfolioAggregationMethod.WATS))\n self.assertFalse(PortfolioAggregationMethod.is_emissions_based(PortfolioAggregationMethod.TETS))\n", "method_code": " def is_emissions_based(method: 'PortfolioAggregationMethod') -> bool:\n \"\"\"\n Check whether a given method is emissions-based (i.e. it uses the emissions to calculate the aggregation).\n \n :param method: The method to check\n :return:\n \"\"\"\n return method == PortfolioAggregationMethod.MOTS or method == PortfolioAggregationMethod.EOTS or method == PortfolioAggregationMethod.ECOTS or (method == PortfolioAggregationMethod.AOTS) or (method == PortfolioAggregationMethod.ROTS)\n ", "context": "class PortfolioAggregationMethod(Enum):\n @staticmethod\n def is_emissions_based(method: 'PortfolioAggregationMethod') -> bool: ...\n def get_value_column(method: 'PortfolioAggregationMethod', column_config: Type[ColumnsConfig]) -> str: ...\n\n WATS = 'WATS'\n TETS = 'TETS'\n MOTS = 'MOTS'\n EOTS = 'EOTS'\n ECOTS = 'ECOTS'\n AOTS = 'AOTS'\n ROTS = 'ROTS'\n", "repository": "os-c/ITR", "test_name": "test_is_emissions_based", "smells": [1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 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_000018.py"} {"focal_file": "ITR/portfolio_aggregation.py", "focal_class": null, "focal_method": "get_value_column", "tests": "import unittest\n\nclass Test_get_value_column(unittest.TestCase):\n def test_get_value_column(self):\n self.assertEqual(PortfolioAggregationMethod.get_value_column(PortfolioAggregationMethod.MOTS, ColumnsConfig), ColumnsConfig.MARKET_CAP)\n self.assertEqual(PortfolioAggregationMethod.get_value_column(PortfolioAggregationMethod.EOTS, ColumnsConfig), ColumnsConfig.COMPANY_ENTERPRISE_VALUE)\n self.assertEqual(PortfolioAggregationMethod.get_value_column(PortfolioAggregationMethod.ECOTS, ColumnsConfig), ColumnsConfig.COMPANY_EV_PLUS_CASH)\n self.assertEqual(PortfolioAggregationMethod.get_value_column(PortfolioAggregationMethod.AOTS, ColumnsConfig), ColumnsConfig.COMPANY_TOTAL_ASSETS)\n self.assertEqual(PortfolioAggregationMethod.get_value_column(PortfolioAggregationMethod.ROTS, ColumnsConfig), ColumnsConfig.COMPANY_REVENUE)\n self.assertEqual(PortfolioAggregationMethod.get_value_column(PortfolioAggregationMethod.WATS, ColumnsConfig), ColumnsConfig.MARKET_CAP)\n self.assertEqual(PortfolioAggregationMethod.get_value_column(PortfolioAggregationMethod.TETS, ColumnsConfig), ColumnsConfig.MARKET_CAP)\n", "method_code": " def get_value_column(method: 'PortfolioAggregationMethod', column_config: Type[ColumnsConfig]) -> str:\n map_value_column = {PortfolioAggregationMethod.MOTS: column_config.MARKET_CAP, PortfolioAggregationMethod.EOTS: column_config.COMPANY_ENTERPRISE_VALUE, PortfolioAggregationMethod.ECOTS: column_config.COMPANY_EV_PLUS_CASH, PortfolioAggregationMethod.AOTS: column_config.COMPANY_TOTAL_ASSETS, PortfolioAggregationMethod.ROTS: column_config.COMPANY_REVENUE}\n return map_value_column.get(method, column_config.MARKET_CAP)\n ", "context": "class PortfolioAggregationMethod(Enum):\n @staticmethod\n def get_value_column(method: 'PortfolioAggregationMethod', column_config: Type[ColumnsConfig]) -> str: ...\n def is_emissions_based(method: 'PortfolioAggregationMethod') -> bool: ...\n\n WATS = 'WATS'\n TETS = 'TETS'\n MOTS = 'MOTS'\n EOTS = 'EOTS'\n ECOTS = 'ECOTS'\n AOTS = 'AOTS'\n ROTS = 'ROTS'\n", "repository": "os-c/ITR", "test_name": "test_get_value_column", "smells": [1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 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_000019.py"} {"focal_file": "ITR/portfolio_aggregation.py", "focal_class": "PortfolioAggregation", "focal_method": "_check_column", "tests": "import unittest\n\nclass Test_PortfolioAggregation_check_column(unittest.TestCase):\n def test_check_column(self):\n PortfolioAggregation()._check_column(data=self.data, column=ColumnsConfig.COMPANY_REVENUE)\n self.data.loc[0, ColumnsConfig.MARKET_CAP] = pd.NA\n with self.assertRaises(ValueError):\n PortfolioAggregation()._check_column(data=self.data, column=ColumnsConfig.MARKET_CAP)\n", "method_code": " def _check_column(self, data: pd.DataFrame, column: str):\n \"\"\"\n Check if a certain column is filled for all companies. If not throw an error.\n \n :param data: The data to check\n :param column: The column to check\n :return:\n \"\"\"\n missing_data = data[pd.isnull(data[column])][self.c.COLS.COMPANY_NAME].unique()\n if len(missing_data):\n raise ValueError('The value for {} is missing for the following companies: {}'.format(column, ', '.join(missing_data)))\n ", "context": "class PortfolioAggregation(ABC):\n def _check_column(self, data: pd.DataFrame, column: str): ...\n def __init__(self, config: Type[PortfolioAggregationConfig]=PortfolioAggregationConfig): ...\n def _calculate_aggregate_score(self, data: pd.DataFrame, input_column: str, portfolio_aggregation_method: PortfolioAggregationMethod) -> pd.Series: ...\n\n self.c = config\n", "repository": "os-c/ITR", "test_name": "test_check_column", "smells": [1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 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_000020.py"} {"focal_file": "ITR/portfolio_aggregation.py", "focal_class": "PortfolioAggregation", "focal_method": "_calculate_aggregate_score", "tests": "import unittest\n\nclass Test_PortfolioAggregation_calculate_aggregate_score(unittest.TestCase):\n def test_calculate_aggregate_score_WATS(self):\n pd.testing.assert_series_equal(PortfolioAggregation()._calculate_aggregate_score(data=self.data, input_column=ColumnsConfig.MARKET_CAP, portfolio_aggregation_method=PortfolioAggregationMethod.WATS), pd.Series([0.166667, 0.666667, 1.5]))\n\n def test_calculate_aggregate_score_TETS(self):\n pd.testing.assert_series_equal(PortfolioAggregation()._calculate_aggregate_score(data=self.data, input_column=ColumnsConfig.MARKET_CAP, portfolio_aggregation_method=PortfolioAggregationMethod.TETS), pd.Series([0.111111, 0.444444, 2.0]))\n\n def test_calculate_aggregate_score_ECOTS(self):\n pd.testing.assert_series_equal(PortfolioAggregation()._calculate_aggregate_score(data=self.data, input_column=ColumnsConfig.MARKET_CAP, portfolio_aggregation_method=PortfolioAggregationMethod.ECOTS), pd.Series([0.111111, 0.444444, 2.0]))\n\n def test_calculate_aggregate_score_MOTS(self):\n pd.testing.assert_series_equal(PortfolioAggregation()._calculate_aggregate_score(data=self.data, input_column=ColumnsConfig.MARKET_CAP, portfolio_aggregation_method=PortfolioAggregationMethod.MOTS), pd.Series([0.111111, 0.444444, 2.0]))\n\n def test_calculate_aggregate_score_EOTS(self):\n pd.testing.assert_series_equal(PortfolioAggregation()._calculate_aggregate_score(data=self.data, input_column=ColumnsConfig.MARKET_CAP, portfolio_aggregation_method=PortfolioAggregationMethod.EOTS), pd.Series([0.111111, 0.444444, 2.0]))\n\n def test_calculate_aggregate_score_AOTS(self):\n pd.testing.assert_series_equal(PortfolioAggregation()._calculate_aggregate_score(data=self.data, input_column=ColumnsConfig.MARKET_CAP, portfolio_aggregation_method=PortfolioAggregationMethod.AOTS), pd.Series([0.111111, 0.444444, 2.0]))\n\n def test_calculate_aggregate_score_ROTS(self):\n pd.testing.assert_series_equal(PortfolioAggregation()._calculate_aggregate_score(data=self.data, input_column=ColumnsConfig.MARKET_CAP, portfolio_aggregation_method=PortfolioAggregationMethod.ROTS), pd.Series([0.111111, 0.444444, 2.0]))\n", "method_code": " def _calculate_aggregate_score(self, data: pd.DataFrame, input_column: str, portfolio_aggregation_method: PortfolioAggregationMethod) -> pd.Series:\n \"\"\"\n Aggregate the scores in a given column based on a certain portfolio aggregation method.\n \n :param data: The data to run the calculations on\n :param input_column: The input column (containing the scores)\n :param portfolio_aggregation_method: The method to use\n :return: The aggregates score\n \"\"\"\n if portfolio_aggregation_method == PortfolioAggregationMethod.WATS:\n total_investment_weight = data[self.c.COLS.INVESTMENT_VALUE].sum()\n try:\n return data.apply(lambda row: row[self.c.COLS.INVESTMENT_VALUE] * row[input_column] / total_investment_weight, axis=1)\n except ZeroDivisionError:\n raise ValueError('The portfolio weight is not allowed to be zero')\n elif portfolio_aggregation_method == PortfolioAggregationMethod.TETS:\n use_S1S2 = (data[self.c.COLS.SCOPE] == EScope.S1S2) | (data[self.c.COLS.SCOPE] == EScope.S1S2S3)\n use_S3 = (data[self.c.COLS.SCOPE] == EScope.S3) | (data[self.c.COLS.SCOPE] == EScope.S1S2S3)\n if use_S3.any():\n self._check_column(data, self.c.COLS.GHG_SCOPE3)\n if use_S1S2.any():\n self._check_column(data, self.c.COLS.GHG_SCOPE12)\n emissions = (use_S1S2 * data[self.c.COLS.GHG_SCOPE12]).sum() + (use_S3 * data[self.c.COLS.GHG_SCOPE3]).sum()\n try:\n return (use_S1S2 * data[self.c.COLS.GHG_SCOPE12] + use_S3 * data[self.c.COLS.GHG_SCOPE3]) / emissions * data[input_column]\n except ZeroDivisionError:\n raise ValueError('The total emissions should be higher than zero')\n elif PortfolioAggregationMethod.is_emissions_based(portfolio_aggregation_method):\n if portfolio_aggregation_method == PortfolioAggregationMethod.ECOTS:\n self._check_column(data, self.c.COLS.COMPANY_ENTERPRISE_VALUE)\n self._check_column(data, self.c.COLS.CASH_EQUIVALENTS)\n data[self.c.COLS.COMPANY_EV_PLUS_CASH] = data[self.c.COLS.COMPANY_ENTERPRISE_VALUE] + data[self.c.COLS.CASH_EQUIVALENTS]\n value_column = PortfolioAggregationMethod.get_value_column(portfolio_aggregation_method, self.c.COLS)\n try:\n self._check_column(data, self.c.COLS.INVESTMENT_VALUE)\n self._check_column(data, value_column)\n use_S1S2 = (data[self.c.COLS.SCOPE] == EScope.S1S2) | (data[self.c.COLS.SCOPE] == EScope.S1S2S3)\n use_S3 = (data[self.c.COLS.SCOPE] == EScope.S3) | (data[self.c.COLS.SCOPE] == EScope.S1S2S3)\n if use_S1S2.any():\n self._check_column(data, self.c.COLS.GHG_SCOPE12)\n if use_S3.any():\n self._check_column(data, self.c.COLS.GHG_SCOPE3)\n data[self.c.COLS.OWNED_EMISSIONS] = data[self.c.COLS.INVESTMENT_VALUE] / data[value_column] * (use_S1S2 * data[self.c.COLS.GHG_SCOPE12] + use_S3 * data[self.c.COLS.GHG_SCOPE3])\n except ZeroDivisionError:\n raise ValueError('To calculate the aggregation, the {} column may not be zero'.format(value_column))\n owned_emissions = data[self.c.COLS.OWNED_EMISSIONS].sum()\n try:\n return data.apply(lambda row: row[self.c.COLS.OWNED_EMISSIONS] / owned_emissions * row[input_column], axis=1)\n except ZeroDivisionError:\n raise ValueError('The total owned emissions can not be zero')\n else:\n raise ValueError('The specified portfolio aggregation method is invalid')\n ", "context": "class PortfolioAggregation(ABC):\n def _calculate_aggregate_score(self, data: pd.DataFrame, input_column: str, portfolio_aggregation_method: PortfolioAggregationMethod) -> pd.Series: ...\n def __init__(self, config: Type[PortfolioAggregationConfig]=PortfolioAggregationConfig): ...\n def _check_column(self, data: pd.DataFrame, column: str): ...\n\n self.c = config\n", "repository": "os-c/ITR", "test_name": "test_calculate_aggregate_score_WATS", "smells": [1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 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_000021.py"} {"focal_file": "_abathur/extract.py", "focal_class": "Extractor", "focal_method": "perform_extraction", "tests": "import unittest\n\nclass Test_Extractor_perform_extraction(unittest.TestCase):\n def test_extractor_query_param(self):\n \"\"\"\n Testing the Extractor with query_param = True\n \"\"\"\n tmp_dir = self.__class__.TMP_DIR\n db_name = self.__class__.DB_NAME\n db_conn_str = 'sqlite:///{tmp_dir}/{db_name}'.format(tmp_dir=tmp_dir, db_name=db_name)\n test_dir_name = os.path.dirname(__file__)\n test_param_query_filename = os.path.join(test_dir_name, 'data/test_param_query_file.sql')\n test_query_filename = os.path.join(test_dir_name, 'data/test_query_file.json')\n output_filename = os.path.join(tmp_dir, 'test_output.csv')\n extractor = Extractor(db_conn_str, test_param_query_filename, test_query_filename, output_filename, True)\n extractor.perform_extraction()\n sample_output_filename = os.path.join(test_dir_name, 'data/sample_test_output.csv')\n self.assertTrue(filecmp.cmp(output_filename, sample_output_filename))\n", "method_code": " def perform_extraction(self):\n \"\"\"\n query_param: whether we should query the params or just use the file as\n params\n \"\"\"\n engine = create_engine(self._db_connection_string)\n conn = engine.connect()\n param_keys = []\n param_list = []\n if self._query_param:\n with open(self._param_file, 'rb') as param_query_file:\n the_query = param_query_file.read()\n result = conn.execute(the_query)\n param_keys = result.keys()\n for row in result:\n param_list.append(IndexedDict(param_keys, row))\n else:\n with open(self._param_file, 'rb') as param_query_file:\n csvreader = csv.reader(param_query_file)\n param_keys = csvreader.next()\n for row in csvreader:\n param_list.append(IndexedDict(param_keys, row))\n with open(self._query_file, 'r') as the_query_file:\n query_file_dict = json.load(the_query_file)\n with open(self._output_file, 'wb') as the_output_file:\n csvwriter = csv.writer(the_output_file, lineterminator='\\n')\n csvwriter.writerow(param_keys + query_file_dict.keys())\n for indexed_dict in param_list:\n row = list(indexed_dict.values())\n for feat_name, feat_query in query_file_dict.iteritems():\n result = conn.execute(feat_query.format(**indexed_dict.to_dict()))\n feat_value = result.fetchone()[0]\n row.append(feat_value)\n result.close()\n csvwriter.writerow(row)\n ", "context": "class Extractor(object):\n def perform_extraction(self): ...\n def __init__(self, db_connection_string, param_file, query_file, output_file, query_param): ...\n\n self._db_connection_string = db_connection_string\n self._param_file = param_file\n self._query_file = query_file\n self._output_file = output_file\n self._query_param = query_param\n", "repository": "realstraw/abathur", "test_name": "test_extractor_query_param", "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_000022.py"} {"focal_file": "ratr0/util/png_util.py", "focal_class": null, "focal_method": "chunks", "tests": "import unittest\n\nclass Test_chunks(unittest.TestCase):\n def test_chunks(self):\n \"\"\"test the chunks() function\"\"\"\n self.assertEquals([[1], [2], [3]], list(png_util.chunks([1, 2, 3], 1)))\n self.assertEquals([[1, 2], [3, 4]], list(png_util.chunks([1, 2, 3, 4], 2)))\n", "method_code": "def chunks(l, n):\n for i in range(0, len(list(l)), n):\n yield l[i:i + n]", "context": "def chunks(l, n): ...\ndef chunks(l, n): ...\ndef color_to_plane_bits(color, depth): ...\ndef extract_planes(im, depth, verbose): ...\ndef interleave_planes(planes, map_words_per_row): ...\ndef make_colors(im, final_depth, verbose): ...\n", "repository": "weiju/ratr0-utils", "test_name": "test_chunks", "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_000023.py"} {"focal_file": "ratr0/util/png_util.py", "focal_class": null, "focal_method": "color_to_plane_bits", "tests": "import unittest\n\nclass Test_color_to_plane_bits(unittest.TestCase):\n def test_color_to_plane_bits_depth_0(self):\n \"\"\"call color_to_plane_bits() with depth 0\"\"\"\n self.assertEquals([], png_util.color_to_plane_bits(0, 0))\n\n def test_color_to_plane_bits_depth_1(self):\n \"\"\"call color_to_plane_bits() with depth 1\"\"\"\n self.assertEquals([0], png_util.color_to_plane_bits(0, 1))\n self.assertEquals([1], png_util.color_to_plane_bits(1, 1))\n\n def test_color_to_plane_bits_depth_2(self):\n \"\"\"call color_to_plane_bits() with depth 2\"\"\"\n self.assertEquals([0, 0], png_util.color_to_plane_bits(0, 2))\n self.assertEquals([1, 0], png_util.color_to_plane_bits(1, 2))\n self.assertEquals([0, 1], png_util.color_to_plane_bits(2, 2))\n self.assertEquals([1, 1], png_util.color_to_plane_bits(3, 2))\n", "method_code": "def color_to_plane_bits(color, depth):\n \"\"\"returns the bits for a given pixel in a list, lowest to highest plane\"\"\"\n result = [0] * depth\n for bit in range(depth):\n if color & 1 << bit != 0:\n result[bit] = 1\n return result", "context": "def color_to_plane_bits(color, depth): ...\ndef chunks(l, n): ...\ndef color_to_plane_bits(color, depth): ...\ndef extract_planes(im, depth, verbose): ...\ndef interleave_planes(planes, map_words_per_row): ...\ndef make_colors(im, final_depth, verbose): ...\n", "repository": "weiju/ratr0-utils", "test_name": "test_color_to_plane_bits_depth_0", "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_000024.py"} {"focal_file": "ratr0/util/png_util.py", "focal_class": null, "focal_method": "extract_planes", "tests": "import unittest\n\nclass Test_extract_planes(unittest.TestCase):\n def test_extract_planes_0(self):\n \"\"\"attempting to extract from an image with depth 0\"\"\"\n im = MockImage((2, 2), [1, 0, 0, 1])\n planes, map_words_per_row = png_util.extract_planes(im, 0, False)\n self.assertEquals([], planes)\n self.assertEquals(1, map_words_per_row)\n\n def test_extract_planes_1_2by2_all_0(self):\n \"\"\"an image that has 2x2 pixels all set to 0\"\"\"\n im = MockImage((2, 2), [0, 0, 0, 0])\n planes, map_words_per_row = png_util.extract_planes(im, 1, False)\n self.assertEquals(1, map_words_per_row)\n self.assertEquals([[0, 0]], planes)\n\n def test_extract_planes_1_2by2_all_1(self):\n \"\"\"an image that has 2x2 pixels all set to color 1\"\"\"\n im = MockImage((2, 2), [1, 1, 1, 1])\n planes, map_words_per_row = png_util.extract_planes(im, 1, False)\n self.assertEquals(1, map_words_per_row)\n row = 3 << 16 - 2\n self.assertEquals([[row, row]], planes)\n\n def test_extract_planes_1_2by16_all_1(self):\n \"\"\"an image that has 16x2 pixels all set to color 1\"\"\"\n im = MockImage((16, 2), [1] * 32)\n planes, map_words_per_row = png_util.extract_planes(im, 1, False)\n self.assertEquals(1, map_words_per_row)\n self.assertEquals([[65535, 65535]], planes)\n\n def test_extract_planes_1_2by32_all_1(self):\n \"\"\"an image that has 16x2 pixels with each rows 16 pixels color 1 and\n 16 pixels color 0\"\"\"\n im = MockImage((32, 2), [1] * 16 + [0] * 16 + [1] * 16 + [0] * 16)\n planes, map_words_per_row = png_util.extract_planes(im, 1, False)\n self.assertEquals(2, map_words_per_row)\n self.assertEquals([[65535, 0, 65535, 0]], planes)\n", "method_code": "def extract_planes(im, depth, verbose):\n \"\"\"check extract_planes(), seems to be wrong and lose data !!!\"\"\"\n imdata = im.getdata()\n width, height = im.size\n map_words_per_row = int(width / 16)\n if width % 16 > 0:\n map_words_per_row += 1\n if verbose:\n print('source image width: %d height: %d' % (width, height))\n print('bitmap words/row: %d' % map_words_per_row)\n planes = [[0] * (map_words_per_row * height) for _ in range(depth)]\n for y in range(height):\n x = 0\n while x < width:\n for i in range(min(16, width - x)):\n color = imdata[y * width + x + i]\n planebits = color_to_plane_bits(color, depth)\n wordidx = (x + i) / 16\n pos = int(y * map_words_per_row + wordidx)\n for planeidx in range(depth):\n if planebits[planeidx]:\n planes[planeidx][pos] |= 1 << 15 - (x + i) % 16\n x += 16\n if verbose:\n for i, plane in enumerate(planes):\n print('Plane %d: ' % i)\n words = ['%04x' % w for w in plane]\n print(' '.join(words))\n return (planes, map_words_per_row)", "context": "def extract_planes(im, depth, verbose): ...\ndef chunks(l, n): ...\ndef color_to_plane_bits(color, depth): ...\ndef extract_planes(im, depth, verbose): ...\ndef interleave_planes(planes, map_words_per_row): ...\ndef make_colors(im, final_depth, verbose): ...\n", "repository": "weiju/ratr0-utils", "test_name": "test_extract_planes_0", "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_000025.py"} {"focal_file": "data_structures/radix_sort.py", "focal_class": null, "focal_method": "radix_sort", "tests": "import unittest\n\nclass Test_radix_sort(unittest.TestCase):\n def test_sort(self):\n input_li = [65, 43, 21, 10, 32, 54]\n expected = [10, 21, 32, 43, 54, 65]\n self.assertEquals(radix_sort(input_li, 10), expected)\n", "method_code": "def radix_sort(unsorted, base):\n result = unsorted\n if not result:\n return []\n length = int(floor(log(abs(max(unsorted)), base))) + 1\n mini = int(floor(log(abs(min(unsorted)), base))) + 1\n if mini > length:\n length = mini\n for i in xrange(1, length + 1):\n buckets = [[] for x in range(base)]\n for j in result:\n digit = j % base ** i // base ** (i - 1)\n buckets[digit].append(j)\n result = [item for bucket in buckets for item in bucket]\n if min(result) < 0:\n buckets = [[], []]\n for j in result:\n if j <= 0:\n buckets[0].append(j)\n else:\n buckets[1].append(j)\n result = [item for bucket in buckets for item in bucket]\n return result", "context": "def radix_sort(unsorted, base): ...\ndef radix_sort(unsorted, base): ...\n", "repository": "sbabineau/data-structures", "test_name": "test_sort", "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_000026.py"} {"focal_file": "data_structures/quick_sort.py", "focal_class": null, "focal_method": "quick_sort", "tests": "import unittest\n\nclass Test_quick_sort(unittest.TestCase):\n def test_sort(self):\n input_li = [6, 4, 2, 1, 3, 5]\n expected = [1, 2, 3, 4, 5, 6]\n self.assertEquals(quick_sort(input_li), expected)\n", "method_code": "def quick_sort(unsorted, method='median'):\n if len(unsorted) < 2:\n return unsorted\n piv = pivot(unsorted, method=method)\n lesser = [i for i in unsorted if i < piv]\n greater = [i for i in unsorted if i > piv]\n piv_list = [i for i in unsorted if i == piv]\n lesser = quick_sort(lesser, method=method)\n greater = quick_sort(greater, method=method)\n lesser.extend(piv_list)\n lesser.extend(greater)\n return lesser", "context": "def quick_sort(unsorted, method='median'): ...\ndef quick_sort(unsorted, method='median'): ...\ndef pivot(list_inp, method='median'): ...\n", "repository": "sbabineau/data-structures", "test_name": "test_sort", "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_000027.py"} {"focal_file": "data_structures/quick_sort.py", "focal_class": null, "focal_method": "pivot", "tests": "import unittest\n\nclass Test_pivot(unittest.TestCase):\n def test_front_pivot(self):\n self.assertEquals(pivot(self.inp, method='first'), 6)\n\n def test_last_pivot(self):\n self.assertEquals(pivot(self.inp, method='last'), 5)\n\n def test_median_pivot(self):\n self.assertEquals(pivot(self.inp, method='median'), 5)\n", "method_code": "def pivot(list_inp, method='median'):\n \"\"\"Defines a pivot point for quicksort, method can be ['first', 'last',\n 'median']\"\"\"\n if method.lower() == 'median':\n med_list = [list_inp[0], list_inp[-1], list_inp[len(list_inp) // 2]]\n med_list.remove(max(med_list))\n med_list.remove(min(med_list))\n return med_list[0]\n if method.lower() == 'first':\n return list_inp[0]\n if method.lower() == 'last':\n return list_inp[-1]", "context": "def pivot(list_inp, method='median'): ...\ndef quick_sort(unsorted, method='median'): ...\ndef pivot(list_inp, method='median'): ...\n", "repository": "sbabineau/data-structures", "test_name": "test_front_pivot", "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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000028.py"} {"focal_file": "data_structures/queue.py", "focal_class": null, "focal_method": "dequeue", "tests": "import unittest\n\nclass Test_dequeue(unittest.TestCase):\n def test_dequeue(self):\n self.assertEqual(self.qtest.dequeue(), True)\n\n def test_dequeue_head(self):\n self.qtest.dequeue()\n self.assertEqual(self.qtest.head.value, 6)\n\n def test_dequeue_empty(self):\n self.qtest.dequeue()\n self.qtest.dequeue()\n self.qtest.dequeue()\n self.assertRaises(self.qtest.dequeue)\n\n def test_dequeue_value(self):\n self.qtest.dequeue()\n self.qtest.dequeue()\n self.qtest.dequeue()\n self.assertEqual(self.qtest.tail, None)\n", "method_code": " def dequeue(self):\n if self.head is self.tail:\n self.tail = None\n if self.head:\n response, self.head = (self.head.value, self.head.next)\n self.length -= 1\n return response\n else:\n raise IndexError\n ", "context": "class Queue(object):\n def dequeue(self): ...\n def __init__(self): ...\n def enqueue(self, value): ...\n def length(self): ...\n\n self.head = None\n self.tail = None\n self.length = 0\n", "repository": "sbabineau/data-structures", "test_name": "test_dequeue", "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, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000029.py"} {"focal_file": "data_structures/binarytree.py", "focal_class": null, "focal_method": "insert", "tests": "import unittest\n\nclass Test_insert(unittest.TestCase):\n def test_insert(self):\n self.tree.insert(9)\n self.assertTrue(self.tree.contains(9))\n\n def test_reinsert(self):\n self.tree.insert(7)\n self.assertEqual(self.tree.size(), 1)\n", "method_code": " def insert(self, value):\n \"\"\"Insert an integer into a binary tree\"\"\"\n if value == self.value:\n return\n elif value > self.value:\n if self.greater is None:\n self.greater = BinaryTree(value)\n return\n self.greater.insert(value)\n elif value < self.value:\n if self.lesser is None:\n self.lesser = BinaryTree(value)\n return\n self.lesser.insert(value)\n ", "context": "class BinaryTree(object):\n def insert(self, value): ...\n def __init__(self, value=None): ...\n def contains(self, value): ...\n def size(self, total=0): ...\n def depth(self): ...\n def balance(self): ...\n def in_order(self): ...\n def pre_order(self): ...\n def post_order(self): ...\n def breadth_first(self): ...\n def get_dot(self): ...\n def _get_dot(self): ...\n\n self.value = value\n self.greater = None\n self.lesser = None\n", "repository": "sbabineau/data-structures", "test_name": "test_insert", "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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000030.py"} {"focal_file": "data_structures/binarytree.py", "focal_class": null, "focal_method": "contains", "tests": "import unittest\n\nclass Test_contains(unittest.TestCase):\n def test_contains_false(self):\n self.assertFalse(self.tree.contains(6))\n", "method_code": " def contains(self, value):\n \"\"\"Determine whether value is contained in binary tree\"\"\"\n try:\n if value == self.value:\n return True\n elif value > self.value:\n return self.greater.contains(value)\n elif value < self.value:\n return self.lesser.contains(value)\n except AttributeError:\n return False\n ", "context": "class BinaryTree(object):\n def contains(self, value): ...\n def __init__(self, value=None): ...\n def insert(self, value): ...\n def size(self, total=0): ...\n def depth(self): ...\n def balance(self): ...\n def in_order(self): ...\n def pre_order(self): ...\n def post_order(self): ...\n def breadth_first(self): ...\n def get_dot(self): ...\n def _get_dot(self): ...\n\n self.value = value\n self.greater = None\n self.lesser = None\n", "repository": "sbabineau/data-structures", "test_name": "test_contains_false", "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_000031.py"} {"focal_file": "data_structures/binarytree.py", "focal_class": null, "focal_method": "size", "tests": "import unittest\n\nclass Test_size(unittest.TestCase):\n def test_size(self):\n self.assertEqual(self.tree.size(), 1)\n self.tree.insert(6)\n self.assertEqual(self.tree.size(), 2)\n\n def test_empty_size(self):\n self.assertEqual(self.tree.size(), 0)\n", "method_code": " def size(self, total=0):\n \"\"\"Returns total of all values within binary tree\"\"\"\n if self.value:\n total += 1\n else:\n return 0\n if self.lesser:\n total += self.lesser.size()\n if self.greater:\n total += self.lesser.size()\n return total\n ", "context": "class BinaryTree(object):\n def size(self, total=0): ...\n def __init__(self, value=None): ...\n def insert(self, value): ...\n def contains(self, value): ...\n def depth(self): ...\n def balance(self): ...\n def in_order(self): ...\n def pre_order(self): ...\n def post_order(self): ...\n def breadth_first(self): ...\n def get_dot(self): ...\n def _get_dot(self): ...\n\n self.value = value\n self.greater = None\n self.lesser = None\n", "repository": "sbabineau/data-structures", "test_name": "test_size", "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_000032.py"} {"focal_file": "data_structures/binarytree.py", "focal_class": null, "focal_method": "depth", "tests": "import unittest\n\nclass Test_depth(unittest.TestCase):\n def test_depth(self):\n self.tree.insert(8)\n self.tree.insert(9)\n self.tree.insert(10)\n self.tree.insert(5)\n self.assertEqual(self.tree.depth(), 4)\n", "method_code": " def depth(self):\n if self.value is None:\n return 0\n a = self.greater.depth() if self.greater else 0\n b = self.lesser.depth() if self.lesser else 0\n return max(a, b) + 1\n ", "context": "class BinaryTree(object):\n def depth(self): ...\n def __init__(self, value=None): ...\n def insert(self, value): ...\n def contains(self, value): ...\n def size(self, total=0): ...\n def balance(self): ...\n def in_order(self): ...\n def pre_order(self): ...\n def post_order(self): ...\n def breadth_first(self): ...\n def get_dot(self): ...\n def _get_dot(self): ...\n\n self.value = value\n self.greater = None\n self.lesser = None\n", "repository": "sbabineau/data-structures", "test_name": "test_depth", "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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000033.py"} {"focal_file": "data_structures/binarytree.py", "focal_class": null, "focal_method": "balance", "tests": "import unittest\n\nclass Test_balance(unittest.TestCase):\n def test_balance_pos(self):\n self.tree.insert(10)\n self.tree.insert(8)\n self.tree.insert(9)\n self.assertEqual(self.tree.balance(), 3)\n\n def test_balance_neg(self):\n self.tree.insert(1)\n self.tree.insert(2)\n self.tree.insert(9)\n self.assertEqual(self.tree.balance(), -1)\n\n def test_balance_even(self):\n self.tree.insert(10)\n self.tree.insert(4)\n self.assertEqual(self.tree.balance(), 0)\n\n def test_empty_balance(self):\n self.assertEqual(self.tree.balance(), 0)\n", "method_code": " def balance(self):\n a = self.greater.depth() if self.greater else 0\n b = self.lesser.depth() if self.lesser else 0\n return a - b\n ", "context": "class BinaryTree(object):\n def balance(self): ...\n def __init__(self, value=None): ...\n def insert(self, value): ...\n def contains(self, value): ...\n def size(self, total=0): ...\n def depth(self): ...\n def in_order(self): ...\n def pre_order(self): ...\n def post_order(self): ...\n def breadth_first(self): ...\n def get_dot(self): ...\n def _get_dot(self): ...\n\n self.value = value\n self.greater = None\n self.lesser = None\n", "repository": "sbabineau/data-structures", "test_name": "test_balance_pos", "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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000034.py"} {"focal_file": "data_structures/binarytree.py", "focal_class": null, "focal_method": "in_order", "tests": "import unittest\n\nclass Test_in_order(unittest.TestCase):\n def test_in_order(self):\n outp = []\n for i in self.tree.in_order():\n outp.append(i)\n self.assertEqual(outp, [4, 5, 6, 10, 14, 15, 16])\n", "method_code": " def in_order(self):\n if self.lesser is not None:\n for i in self.lesser.in_order():\n yield i\n if self.value is not None:\n yield self.value\n if self.greater is not None:\n for i in self.greater.in_order():\n yield i\n ", "context": "class BinaryTree(object):\n def in_order(self): ...\n def __init__(self, value=None): ...\n def insert(self, value): ...\n def contains(self, value): ...\n def size(self, total=0): ...\n def depth(self): ...\n def balance(self): ...\n def pre_order(self): ...\n def post_order(self): ...\n def breadth_first(self): ...\n def get_dot(self): ...\n def _get_dot(self): ...\n\n self.value = value\n self.greater = None\n self.lesser = None\n", "repository": "sbabineau/data-structures", "test_name": "test_in_order", "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, 0, 0, 0], "pynose_source_file": "test_000035.py"} {"focal_file": "data_structures/binarytree.py", "focal_class": null, "focal_method": "post_order", "tests": "import unittest\n\nclass Test_post_order(unittest.TestCase):\n def test_post_order(self):\n outp = []\n for i in self.tree.post_order():\n outp.append(i)\n self.assertEqual(outp, [4, 6, 5, 14, 16, 15, 10])\n", "method_code": " def post_order(self):\n if self.lesser is not None:\n for i in self.lesser.pre_order():\n yield i\n if self.greater is not None:\n for i in self.greater.pre_order():\n yield i\n if self.value is not None:\n yield self.value\n ", "context": "class BinaryTree(object):\n def post_order(self): ...\n def __init__(self, value=None): ...\n def insert(self, value): ...\n def contains(self, value): ...\n def size(self, total=0): ...\n def depth(self): ...\n def balance(self): ...\n def in_order(self): ...\n def pre_order(self): ...\n def breadth_first(self): ...\n def get_dot(self): ...\n def _get_dot(self): ...\n\n self.value = value\n self.greater = None\n self.lesser = None\n", "repository": "sbabineau/data-structures", "test_name": "test_post_order", "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, 0, 0, 0], "pynose_source_file": "test_000036.py"} {"focal_file": "data_structures/binarytree.py", "focal_class": null, "focal_method": "pre_order", "tests": "import unittest\n\nclass Test_pre_order(unittest.TestCase):\n def test_pre_order(self):\n outp = []\n for i in self.tree.pre_order():\n outp.append(i)\n self.assertEqual(outp, [10, 5, 4, 6, 15, 14, 16])\n", "method_code": " def pre_order(self):\n if self.value is not None:\n yield self.value\n if self.lesser is not None:\n for i in self.lesser.post_order():\n yield i\n if self.greater is not None:\n for i in self.greater.post_order():\n yield i\n ", "context": "class BinaryTree(object):\n def pre_order(self): ...\n def __init__(self, value=None): ...\n def insert(self, value): ...\n def contains(self, value): ...\n def size(self, total=0): ...\n def depth(self): ...\n def balance(self): ...\n def in_order(self): ...\n def post_order(self): ...\n def breadth_first(self): ...\n def get_dot(self): ...\n def _get_dot(self): ...\n\n self.value = value\n self.greater = None\n self.lesser = None\n", "repository": "sbabineau/data-structures", "test_name": "test_pre_order", "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, 0, 0, 0], "pynose_source_file": "test_000037.py"} {"focal_file": "data_structures/binarytree.py", "focal_class": null, "focal_method": "breadth_first", "tests": "import unittest\n\nclass Test_breadth_first(unittest.TestCase):\n def test_breadth_first(self):\n outp = []\n for i in self.tree.breadth_first():\n outp.append(i)\n self.assertEqual(outp, [10, 5, 15, 4, 6, 14, 16])\n", "method_code": " def breadth_first(self):\n inp = deque()\n inp.append(self)\n while len(inp) > 0:\n outp = inp.popleft()\n yield outp.value\n if outp.lesser is not None:\n inp.append(outp.lesser)\n if outp.greater is not None:\n inp.append(outp.greater)\n ", "context": "class BinaryTree(object):\n def breadth_first(self): ...\n def __init__(self, value=None): ...\n def insert(self, value): ...\n def contains(self, value): ...\n def size(self, total=0): ...\n def depth(self): ...\n def balance(self): ...\n def in_order(self): ...\n def pre_order(self): ...\n def post_order(self): ...\n def get_dot(self): ...\n def _get_dot(self): ...\n\n self.value = value\n self.greater = None\n self.lesser = None\n", "repository": "sbabineau/data-structures", "test_name": "test_breadth_first", "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, 0, 0, 0], "pynose_source_file": "test_000038.py"} {"focal_file": "docker_dns_test.py", "focal_class": null, "focal_method": "check_record", "tests": "import unittest\n\nclass Test_check_record(unittest.TestCase):\n def test__a_records_id(self):\n rec = self.resolver._a_records('cidpandas.docker')\n self.assertEqual(len(rec), 1)\n rec = rec[0]\n self.assertTrue(check_record(rec, name='cidpandas.docker', type=dns.A))\n self.assertEqual(rec.payload.dottedQuad(), '127.0.0.1')\n", "method_code": "def check_record(record, **kwargs):\n for k in kwargs:\n real_value = getattr(record, k)\n if k is 'name':\n real_value = real_value.name\n if real_value != kwargs[k]:\n return False\n return True", "context": "def check_record(record, **kwargs): ...\ndef in_generator(gen, val): ...\ndef check_record(record, **kwargs): ...\ndef check_deferred(deferred, success): ...\ndef main(): ...\n", "repository": "infoxchange/docker_dns", "test_name": "test__a_records_id", "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_000039.py"} {"focal_file": "forklift/arguments.py", "focal_class": null, "focal_method": "convert_to_args", "tests": "import unittest\n\nclass Test_convert_to_args(unittest.TestCase):\n def test_convert_to_args(self):\n \"\"\"\n Test convert_to_args.\n \"\"\"\n conf = OrderedDict([('simple', 'value'), ('number', 10), ('array', ['one', 'two']), ('empty_array', []), ('nested', OrderedDict([('first', 'deep'), ('second', 'deeper')]))])\n self.assertEqual(convert_to_args(conf), ['--simple', 'value', '--number', '10', '--array', 'one', 'two', '--nested.first', 'deep', '--nested.second', 'deeper'])\n self.assertEqual(convert_to_args(None), [])\n", "method_code": "def convert_to_args(conf, prefix=None):\n \"\"\"\n Convert hierarchical configuration dictionary to argparse arguments.\n\n 'environment' at root level is a special case: if it is a hash,\n it is converted into an array of VAR=VALUE pairs.\n \"\"\"\n args = []\n conf = conf or {}\n prefix = prefix or ()\n if not prefix and 'environment' in conf:\n environment = conf['environment']\n if isinstance(environment, dict):\n conf['environment'] = ['{0}={1}'.format(k, v) for k, v in environment.items()]\n for key, value in conf.items():\n arg_prefix = prefix + (key,)\n if isinstance(value, dict):\n args.extend(convert_to_args(value, arg_prefix))\n else:\n if not isinstance(value, (list, tuple)):\n value = (value,)\n if len(value) > 0:\n args.append('--' + '.'.join(arg_prefix))\n for val in value:\n args.append(str(val))\n return args", "context": "def convert_to_args(conf, prefix=None): ...\ndef argument_factory(add_argument, name): ...\ndef convert_to_args(conf, prefix=None): ...\ndef project_args(args, prefix): ...\n", "repository": "infoxchange/docker-forklift", "test_name": "test_convert_to_args", "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_000040.py"} {"focal_file": "forklift/arguments.py", "focal_class": null, "focal_method": "project_args", "tests": "import unittest\n\nclass Test_project_args(unittest.TestCase):\n def test_project_args(self):\n \"\"\"\n Test project_args.\n \"\"\"\n args = Namespace(**{'one.a': '1a', 'one.b': '1b', 'two.c': '2c'})\n self.assertEqual(vars(project_args(args, 'one')), {'a': '1a', 'b': '1b'})\n", "method_code": "def project_args(args, prefix):\n \"\"\"\n Return only keys in the object having the specified prefix, stripping\n the prefix.\n \"\"\"\n pairs = vars(args).items()\n strip_len = len(prefix) + 1\n return Namespace(**dict(((key[strip_len:], value) for key, value in pairs if key.startswith(prefix + '.'))))", "context": "def project_args(args, prefix): ...\ndef argument_factory(add_argument, name): ...\ndef convert_to_args(conf, prefix=None): ...\ndef project_args(args, prefix): ...\n", "repository": "infoxchange/docker-forklift", "test_name": "test_project_args", "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_000041.py"} {"focal_file": "editparser/__init__.py", "focal_class": "TimeCode", "focal_method": "attributes", "tests": "import unittest\n\nclass Test_TimeCode_attributes(unittest.TestCase):\n def test_creation_with_attributes(self):\n mi = TimeCode('00:00:00:01')\n mo = TimeCode('00:00:00:03')\n gi = TimeCode('00:00:01:01')\n go = TimeCode('00:00:02:01')\n e = Edit(mi, mo, gi, go, name='stuff', number=1, blerg='wek')\n self.assertEquals(e.attributes(), {'name': 'stuff', 'number': 1, 'blerg': 'wek'})\n", "method_code": " def attributes(self):\n return self._attributes\n ", "context": "class Edit():\n def attributes(self): ...\n def __init__(self, mediaIn, mediaOut, globalIn, globalOut, **kwargs): ...\n def parse_input_tc(self, tc): ...\n def mediaIn(self): ...\n def mediaOut(self): ...\n def globalIn(self, refTC=None): ...\n def globalOut(self, refTC=None): ...\n def mediaInOut(self): ...\n def globalInOut(self, refTC=None): ...\n def setMediaIn(self, mediaIn): ...\n def setMediaOut(self, mediaOut): ...\n def setGlobalIn(self, globalIn): ...\n def setGlobalOut(self, globalOut): ...\n def get(self, attribute, default=None): ...\n def set(self, attribute, value): ...\n def __repr__(self): ...\n\n self._mediaIn = self.parse_input_tc(mediaIn)\n self._mediaOut = self.parse_input_tc(mediaOut)\n self._globalIn = self.parse_input_tc(globalIn)\n self._globalOut = self.parse_input_tc(globalOut)\n self._attributes = kwargs\n", "repository": "svenni/editparser", "test_name": "test_creation_with_attributes", "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_000042.py"} {"focal_file": "editparser/__init__.py", "focal_class": null, "focal_method": "mediaIn", "tests": "import unittest\n\nclass Test_mediaIn(unittest.TestCase):\n def test_get_media_in(self):\n self.assertEquals(self.e.mediaIn(), self.mi)\n", "method_code": " def mediaIn(self):\n return self._mediaIn\n ", "context": "class Edit():\n def mediaIn(self): ...\n def __init__(self, mediaIn, mediaOut, globalIn, globalOut, **kwargs): ...\n def parse_input_tc(self, tc): ...\n def mediaOut(self): ...\n def globalIn(self, refTC=None): ...\n def globalOut(self, refTC=None): ...\n def mediaInOut(self): ...\n def globalInOut(self, refTC=None): ...\n def setMediaIn(self, mediaIn): ...\n def setMediaOut(self, mediaOut): ...\n def setGlobalIn(self, globalIn): ...\n def setGlobalOut(self, globalOut): ...\n def get(self, attribute, default=None): ...\n def set(self, attribute, value): ...\n def attributes(self): ...\n def __repr__(self): ...\n\n self._mediaIn = self.parse_input_tc(mediaIn)\n self._mediaOut = self.parse_input_tc(mediaOut)\n self._globalIn = self.parse_input_tc(globalIn)\n self._globalOut = self.parse_input_tc(globalOut)\n self._attributes = kwargs\n", "repository": "svenni/editparser", "test_name": "test_get_media_in", "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_000043.py"} {"focal_file": "editparser/__init__.py", "focal_class": null, "focal_method": "mediaOut", "tests": "import unittest\n\nclass Test_mediaOut(unittest.TestCase):\n def test_get_media_out(self):\n self.assertEquals(self.e.mediaOut(), self.mo)\n", "method_code": " def mediaOut(self):\n return self._mediaOut\n ", "context": "class Edit():\n def mediaOut(self): ...\n def __init__(self, mediaIn, mediaOut, globalIn, globalOut, **kwargs): ...\n def parse_input_tc(self, tc): ...\n def mediaIn(self): ...\n def globalIn(self, refTC=None): ...\n def globalOut(self, refTC=None): ...\n def mediaInOut(self): ...\n def globalInOut(self, refTC=None): ...\n def setMediaIn(self, mediaIn): ...\n def setMediaOut(self, mediaOut): ...\n def setGlobalIn(self, globalIn): ...\n def setGlobalOut(self, globalOut): ...\n def get(self, attribute, default=None): ...\n def set(self, attribute, value): ...\n def attributes(self): ...\n def __repr__(self): ...\n\n self._mediaIn = self.parse_input_tc(mediaIn)\n self._mediaOut = self.parse_input_tc(mediaOut)\n self._globalIn = self.parse_input_tc(globalIn)\n self._globalOut = self.parse_input_tc(globalOut)\n self._attributes = kwargs\n", "repository": "svenni/editparser", "test_name": "test_get_media_out", "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_000044.py"} {"focal_file": "editparser/__init__.py", "focal_class": null, "focal_method": "globalIn", "tests": "import unittest\n\nclass Test_globalIn(unittest.TestCase):\n def test_get_global_in(self):\n self.assertEquals(self.e.globalIn(), self.gi)\n", "method_code": " def globalIn(self, refTC=None):\n if refTC is None:\n refTC = TimeCode(frames=0, base=self._globalIn.base())\n return self._globalIn - refTC\n ", "context": "class Edit():\n def globalIn(self, refTC=None): ...\n def __init__(self, mediaIn, mediaOut, globalIn, globalOut, **kwargs): ...\n def parse_input_tc(self, tc): ...\n def mediaIn(self): ...\n def mediaOut(self): ...\n def globalOut(self, refTC=None): ...\n def mediaInOut(self): ...\n def globalInOut(self, refTC=None): ...\n def setMediaIn(self, mediaIn): ...\n def setMediaOut(self, mediaOut): ...\n def setGlobalIn(self, globalIn): ...\n def setGlobalOut(self, globalOut): ...\n def get(self, attribute, default=None): ...\n def set(self, attribute, value): ...\n def attributes(self): ...\n def __repr__(self): ...\n\n self._mediaIn = self.parse_input_tc(mediaIn)\n self._mediaOut = self.parse_input_tc(mediaOut)\n self._globalIn = self.parse_input_tc(globalIn)\n self._globalOut = self.parse_input_tc(globalOut)\n self._attributes = kwargs\n", "repository": "svenni/editparser", "test_name": "test_get_global_in", "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_000045.py"} {"focal_file": "editparser/__init__.py", "focal_class": null, "focal_method": "globalOut", "tests": "import unittest\n\nclass Test_globalOut(unittest.TestCase):\n def test_get_global_out(self):\n self.assertEquals(self.e.globalOut(), self.go)\n", "method_code": " def globalOut(self, refTC=None):\n if refTC is None:\n refTC = TimeCode(frames=0, base=self._globalOut.base())\n return self._globalOut - refTC\n ", "context": "class Edit():\n def globalOut(self, refTC=None): ...\n def __init__(self, mediaIn, mediaOut, globalIn, globalOut, **kwargs): ...\n def parse_input_tc(self, tc): ...\n def mediaIn(self): ...\n def mediaOut(self): ...\n def globalIn(self, refTC=None): ...\n def mediaInOut(self): ...\n def globalInOut(self, refTC=None): ...\n def setMediaIn(self, mediaIn): ...\n def setMediaOut(self, mediaOut): ...\n def setGlobalIn(self, globalIn): ...\n def setGlobalOut(self, globalOut): ...\n def get(self, attribute, default=None): ...\n def set(self, attribute, value): ...\n def attributes(self): ...\n def __repr__(self): ...\n\n self._mediaIn = self.parse_input_tc(mediaIn)\n self._mediaOut = self.parse_input_tc(mediaOut)\n self._globalIn = self.parse_input_tc(globalIn)\n self._globalOut = self.parse_input_tc(globalOut)\n self._attributes = kwargs\n", "repository": "svenni/editparser", "test_name": "test_get_global_out", "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_000046.py"} {"focal_file": "editparser/__init__.py", "focal_class": "TimeCode", "focal_method": "frames", "tests": "import unittest\n\nclass Test_TimeCode_frames(unittest.TestCase):\n def test_get_global_out_with_ref_tc(self):\n ref_tc = TimeCode('00:00:02:00')\n self.assertEquals(self.e.globalOut(ref_tc).frames(), 1)\n", "method_code": " def frames(self):\n return self._frames\n ", "context": "class TimeCode():\n def frames(self): ...\n def __init__(self, tc='00:00:00:00', frames=0, base=24): ...\n def from_msec(self, msec, base=24): ...\n def base(self): ...\n def tc(self): ...\n def toFrames(self, tc): ...\n def __str__(self): ...\n def __repr__(self): ...\n def __add__(self, other): ...\n def __sub__(self, other): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n\n self._base = base\n", "repository": "svenni/editparser", "test_name": "test_get_global_out_with_ref_tc", "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_000047.py"} {"focal_file": "editparser/__init__.py", "focal_class": null, "focal_method": "mediaInOut", "tests": "import unittest\n\nclass Test_mediaInOut(unittest.TestCase):\n def test_get_mediaInOut(self):\n self.assertEquals(self.e.mediaInOut(), (self.mi, self.mo))\n", "method_code": " def mediaInOut(self):\n return (self._mediaIn, self._mediaOut)\n ", "context": "class Edit():\n def mediaInOut(self): ...\n def __init__(self, mediaIn, mediaOut, globalIn, globalOut, **kwargs): ...\n def parse_input_tc(self, tc): ...\n def mediaIn(self): ...\n def mediaOut(self): ...\n def globalIn(self, refTC=None): ...\n def globalOut(self, refTC=None): ...\n def globalInOut(self, refTC=None): ...\n def setMediaIn(self, mediaIn): ...\n def setMediaOut(self, mediaOut): ...\n def setGlobalIn(self, globalIn): ...\n def setGlobalOut(self, globalOut): ...\n def get(self, attribute, default=None): ...\n def set(self, attribute, value): ...\n def attributes(self): ...\n def __repr__(self): ...\n\n self._mediaIn = self.parse_input_tc(mediaIn)\n self._mediaOut = self.parse_input_tc(mediaOut)\n self._globalIn = self.parse_input_tc(globalIn)\n self._globalOut = self.parse_input_tc(globalOut)\n self._attributes = kwargs\n", "repository": "svenni/editparser", "test_name": "test_get_mediaInOut", "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_000048.py"} {"focal_file": "editparser/__init__.py", "focal_class": null, "focal_method": "globalInOut", "tests": "import unittest\n\nclass Test_globalInOut(unittest.TestCase):\n def test_get_globalInOut(self):\n self.assertEquals(self.e.globalInOut(), (self.gi, self.go))\n", "method_code": " def globalInOut(self, refTC=None):\n if refTC is None:\n refTC = TimeCode(frames=0, base=self._globalIn.base())\n return (self.globalIn(refTC), self.globalOut(refTC))\n ", "context": "class Edit():\n def globalInOut(self, refTC=None): ...\n def __init__(self, mediaIn, mediaOut, globalIn, globalOut, **kwargs): ...\n def parse_input_tc(self, tc): ...\n def mediaIn(self): ...\n def mediaOut(self): ...\n def globalIn(self, refTC=None): ...\n def globalOut(self, refTC=None): ...\n def mediaInOut(self): ...\n def setMediaIn(self, mediaIn): ...\n def setMediaOut(self, mediaOut): ...\n def setGlobalIn(self, globalIn): ...\n def setGlobalOut(self, globalOut): ...\n def get(self, attribute, default=None): ...\n def set(self, attribute, value): ...\n def attributes(self): ...\n def __repr__(self): ...\n\n self._mediaIn = self.parse_input_tc(mediaIn)\n self._mediaOut = self.parse_input_tc(mediaOut)\n self._globalIn = self.parse_input_tc(globalIn)\n self._globalOut = self.parse_input_tc(globalOut)\n self._attributes = kwargs\n", "repository": "svenni/editparser", "test_name": "test_get_globalInOut", "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_000049.py"} {"focal_file": "editparser/__init__.py", "focal_class": "TimeCode", "focal_method": "globalInOut", "tests": "import unittest\n\nclass Test_TimeCode_globalInOut(unittest.TestCase):\n def test_get_globalInOut_with_ref_tc(self):\n ref_tc = TimeCode('00:00:02:00')\n g_in, g_out = self.e.globalInOut(ref_tc)\n self.assertEquals(g_in.frames(), -23)\n self.assertEquals(g_out.frames(), 1)\n", "method_code": " def globalInOut(self, refTC=None):\n if refTC is None:\n refTC = TimeCode(frames=0, base=self._globalIn.base())\n return (self.globalIn(refTC), self.globalOut(refTC))\n ", "context": "class Edit():\n def globalInOut(self, refTC=None): ...\n def __init__(self, mediaIn, mediaOut, globalIn, globalOut, **kwargs): ...\n def parse_input_tc(self, tc): ...\n def mediaIn(self): ...\n def mediaOut(self): ...\n def globalIn(self, refTC=None): ...\n def globalOut(self, refTC=None): ...\n def mediaInOut(self): ...\n def setMediaIn(self, mediaIn): ...\n def setMediaOut(self, mediaOut): ...\n def setGlobalIn(self, globalIn): ...\n def setGlobalOut(self, globalOut): ...\n def get(self, attribute, default=None): ...\n def set(self, attribute, value): ...\n def attributes(self): ...\n def __repr__(self): ...\n\n self._mediaIn = self.parse_input_tc(mediaIn)\n self._mediaOut = self.parse_input_tc(mediaOut)\n self._globalIn = self.parse_input_tc(globalIn)\n self._globalOut = self.parse_input_tc(globalOut)\n self._attributes = kwargs\n", "repository": "svenni/editparser", "test_name": "test_get_globalInOut_with_ref_tc", "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_000050.py"} {"focal_file": "editparser/__init__.py", "focal_class": "TimeCode", "focal_method": "mediaIn", "tests": "import unittest\n\nclass Test_TimeCode_mediaIn(unittest.TestCase):\n def test_set_mediaIn(self):\n new_TC = TimeCode('00:00:00:05', base=24)\n self.e.setMediaIn(new_TC)\n self.assertEquals(self.e.mediaIn(), new_TC)\n", "method_code": " def mediaIn(self):\n return self._mediaIn\n ", "context": "class Edit():\n def mediaIn(self): ...\n def __init__(self, mediaIn, mediaOut, globalIn, globalOut, **kwargs): ...\n def parse_input_tc(self, tc): ...\n def mediaOut(self): ...\n def globalIn(self, refTC=None): ...\n def globalOut(self, refTC=None): ...\n def mediaInOut(self): ...\n def globalInOut(self, refTC=None): ...\n def setMediaIn(self, mediaIn): ...\n def setMediaOut(self, mediaOut): ...\n def setGlobalIn(self, globalIn): ...\n def setGlobalOut(self, globalOut): ...\n def get(self, attribute, default=None): ...\n def set(self, attribute, value): ...\n def attributes(self): ...\n def __repr__(self): ...\n\n self._mediaIn = self.parse_input_tc(mediaIn)\n self._mediaOut = self.parse_input_tc(mediaOut)\n self._globalIn = self.parse_input_tc(globalIn)\n self._globalOut = self.parse_input_tc(globalOut)\n self._attributes = kwargs\n", "repository": "svenni/editparser", "test_name": "test_set_mediaIn", "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_000051.py"} {"focal_file": "editparser/__init__.py", "focal_class": "TimeCode", "focal_method": "mediaOut", "tests": "import unittest\n\nclass Test_TimeCode_mediaOut(unittest.TestCase):\n def test_set_mediaOut(self):\n new_TC = TimeCode('00:00:00:15', base=24)\n self.e.setMediaOut(new_TC)\n self.assertEquals(self.e.mediaOut(), new_TC)\n", "method_code": " def mediaOut(self):\n return self._mediaOut\n ", "context": "class Edit():\n def mediaOut(self): ...\n def __init__(self, mediaIn, mediaOut, globalIn, globalOut, **kwargs): ...\n def parse_input_tc(self, tc): ...\n def mediaIn(self): ...\n def globalIn(self, refTC=None): ...\n def globalOut(self, refTC=None): ...\n def mediaInOut(self): ...\n def globalInOut(self, refTC=None): ...\n def setMediaIn(self, mediaIn): ...\n def setMediaOut(self, mediaOut): ...\n def setGlobalIn(self, globalIn): ...\n def setGlobalOut(self, globalOut): ...\n def get(self, attribute, default=None): ...\n def set(self, attribute, value): ...\n def attributes(self): ...\n def __repr__(self): ...\n\n self._mediaIn = self.parse_input_tc(mediaIn)\n self._mediaOut = self.parse_input_tc(mediaOut)\n self._globalIn = self.parse_input_tc(globalIn)\n self._globalOut = self.parse_input_tc(globalOut)\n self._attributes = kwargs\n", "repository": "svenni/editparser", "test_name": "test_set_mediaOut", "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_000052.py"} {"focal_file": "editparser/__init__.py", "focal_class": "TimeCode", "focal_method": "globalIn", "tests": "import unittest\n\nclass Test_TimeCode_globalIn(unittest.TestCase):\n def test_set_globalIn(self):\n new_TC = TimeCode('00:00:00:04', base=24)\n self.e.setGlobalIn(new_TC)\n self.assertEquals(self.e.globalIn(), new_TC)\n", "method_code": " def globalIn(self, refTC=None):\n if refTC is None:\n refTC = TimeCode(frames=0, base=self._globalIn.base())\n return self._globalIn - refTC\n ", "context": "class Edit():\n def globalIn(self, refTC=None): ...\n def __init__(self, mediaIn, mediaOut, globalIn, globalOut, **kwargs): ...\n def parse_input_tc(self, tc): ...\n def mediaIn(self): ...\n def mediaOut(self): ...\n def globalOut(self, refTC=None): ...\n def mediaInOut(self): ...\n def globalInOut(self, refTC=None): ...\n def setMediaIn(self, mediaIn): ...\n def setMediaOut(self, mediaOut): ...\n def setGlobalIn(self, globalIn): ...\n def setGlobalOut(self, globalOut): ...\n def get(self, attribute, default=None): ...\n def set(self, attribute, value): ...\n def attributes(self): ...\n def __repr__(self): ...\n\n self._mediaIn = self.parse_input_tc(mediaIn)\n self._mediaOut = self.parse_input_tc(mediaOut)\n self._globalIn = self.parse_input_tc(globalIn)\n self._globalOut = self.parse_input_tc(globalOut)\n self._attributes = kwargs\n", "repository": "svenni/editparser", "test_name": "test_set_globalIn", "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_000053.py"} {"focal_file": "editparser/__init__.py", "focal_class": "TimeCode", "focal_method": "globalOut", "tests": "import unittest\n\nclass Test_TimeCode_globalOut(unittest.TestCase):\n def test_set_globalOut(self):\n new_TC = TimeCode('00:00:00:04', base=24)\n self.e.setGlobalOut(new_TC)\n self.assertEquals(self.e.globalOut(), new_TC)\n", "method_code": " def globalOut(self, refTC=None):\n if refTC is None:\n refTC = TimeCode(frames=0, base=self._globalOut.base())\n return self._globalOut - refTC\n ", "context": "class Edit():\n def globalOut(self, refTC=None): ...\n def __init__(self, mediaIn, mediaOut, globalIn, globalOut, **kwargs): ...\n def parse_input_tc(self, tc): ...\n def mediaIn(self): ...\n def mediaOut(self): ...\n def globalIn(self, refTC=None): ...\n def mediaInOut(self): ...\n def globalInOut(self, refTC=None): ...\n def setMediaIn(self, mediaIn): ...\n def setMediaOut(self, mediaOut): ...\n def setGlobalIn(self, globalIn): ...\n def setGlobalOut(self, globalOut): ...\n def get(self, attribute, default=None): ...\n def set(self, attribute, value): ...\n def attributes(self): ...\n def __repr__(self): ...\n\n self._mediaIn = self.parse_input_tc(mediaIn)\n self._mediaOut = self.parse_input_tc(mediaOut)\n self._globalIn = self.parse_input_tc(globalIn)\n self._globalOut = self.parse_input_tc(globalOut)\n self._attributes = kwargs\n", "repository": "svenni/editparser", "test_name": "test_set_globalOut", "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_000054.py"} {"focal_file": "editparser/__init__.py", "focal_class": "TimeCode", "focal_method": "setGlobalOut", "tests": "import unittest\n\nclass Test_TimeCode_setGlobalOut(unittest.TestCase):\n def test_set_globalOut_wrongBase(self):\n new_TC = TimeCode('00:00:00:04', base=10)\n with self.assertRaises(EditError):\n self.e.setGlobalOut(new_TC)\n", "method_code": " def setGlobalOut(self, globalOut):\n if globalOut.base() != self._globalOut.base():\n raise EditError('Wrong input base! Expected %s, got %s.' % (self._globalOut.base(), globalOut.base()))\n self._globalOut = globalOut\n ", "context": "class Edit():\n def setGlobalOut(self, globalOut): ...\n def __init__(self, mediaIn, mediaOut, globalIn, globalOut, **kwargs): ...\n def parse_input_tc(self, tc): ...\n def mediaIn(self): ...\n def mediaOut(self): ...\n def globalIn(self, refTC=None): ...\n def globalOut(self, refTC=None): ...\n def mediaInOut(self): ...\n def globalInOut(self, refTC=None): ...\n def setMediaIn(self, mediaIn): ...\n def setMediaOut(self, mediaOut): ...\n def setGlobalIn(self, globalIn): ...\n def get(self, attribute, default=None): ...\n def set(self, attribute, value): ...\n def attributes(self): ...\n def __repr__(self): ...\n\n self._mediaIn = self.parse_input_tc(mediaIn)\n self._mediaOut = self.parse_input_tc(mediaOut)\n self._globalIn = self.parse_input_tc(globalIn)\n self._globalOut = self.parse_input_tc(globalOut)\n self._attributes = kwargs\n", "repository": "svenni/editparser", "test_name": "test_set_globalOut_wrongBase", "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_000055.py"} {"focal_file": "editparser/__init__.py", "focal_class": null, "focal_method": "get", "tests": "import unittest\n\nclass Test_get(unittest.TestCase):\n def test_attribute_set_get(self):\n self.e.set('integer', 15)\n self.e.set('float', 1.0)\n self.e.set('string', 'this is')\n self.e.set('bool', False)\n self.assertEquals(self.e.get('integer'), 15)\n self.assertEquals(self.e.get('float'), 1.0)\n self.assertEquals(self.e.get('string'), 'this is')\n self.assertEquals(self.e.get('bool'), False)\n", "method_code": " def get(self, attribute, default=None):\n return self._attributes.get(attribute, default)\n ", "context": "class Edit():\n def get(self, attribute, default=None): ...\n def __init__(self, mediaIn, mediaOut, globalIn, globalOut, **kwargs): ...\n def parse_input_tc(self, tc): ...\n def mediaIn(self): ...\n def mediaOut(self): ...\n def globalIn(self, refTC=None): ...\n def globalOut(self, refTC=None): ...\n def mediaInOut(self): ...\n def globalInOut(self, refTC=None): ...\n def setMediaIn(self, mediaIn): ...\n def setMediaOut(self, mediaOut): ...\n def setGlobalIn(self, globalIn): ...\n def setGlobalOut(self, globalOut): ...\n def set(self, attribute, value): ...\n def attributes(self): ...\n def __repr__(self): ...\n\n self._mediaIn = self.parse_input_tc(mediaIn)\n self._mediaOut = self.parse_input_tc(mediaOut)\n self._globalIn = self.parse_input_tc(globalIn)\n self._globalOut = self.parse_input_tc(globalOut)\n self._attributes = kwargs\n", "repository": "svenni/editparser", "test_name": "test_attribute_set_get", "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_000056.py"} {"focal_file": "editparser/__init__.py", "focal_class": null, "focal_method": "insertEdit", "tests": "import unittest\n\nclass Test_insertEdit(unittest.TestCase):\n def test_insert_edits(self):\n self.edl.appendEdit(self.edit_a)\n self.assertEquals(self.edl.getAllEdits(), [self.edit_a])\n self.edl.insertEdit(0, self.edit_b)\n self.assertEquals(self.edl.getAllEdits(), [self.edit_b, self.edit_a])\n", "method_code": " def insertEdit(self, index, edit):\n self._edits.insert(index, edit)\n ", "context": "class EDL():\n def insertEdit(self, index, edit): ...\n def __init__(self, title, path, startTimeCode='01:00:00:00', base=25): ...\n def appendEdit(self, edit): ...\n def getAllEdits(self): ...\n def getEdit(self, index): ...\n def title(self): ...\n def path(self): ...\n def start_tc(self): ...\n\n self._title = title\n self._edits = []\n self._edlPath = path\n self.startTC = TimeCode(startTimeCode, base=base)\n", "repository": "svenni/editparser", "test_name": "test_insert_edits", "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_000057.py"} {"focal_file": "editparser/__init__.py", "focal_class": "TimeCode", "focal_method": "base", "tests": "import unittest\n\nclass Test_TimeCode_base(unittest.TestCase):\n def test_base(self):\n tc = TimeCode(base=30)\n self.assertEquals(tc.base(), 30)\n self.assertEquals(tc._frames, 0)\n\n def test_addition_non_default_base(self):\n tc1 = TimeCode(frames=25, base=30)\n tc2 = TimeCode(frames=24, base=30)\n new_tc = tc1 + tc2\n self.assertEquals(new_tc.base(), tc1.base())\n self.assertEquals(new_tc.frames(), 49)\n\n def test_subtraction_non_default_base(self):\n tc1 = TimeCode(frames=10, base=10)\n tc2 = TimeCode(frames=5, base=10)\n new_tc = tc1 - tc2\n self.assertEquals(new_tc.base(), tc1.base())\n self.assertEquals(new_tc.frames(), 5)\n", "method_code": " def base(self):\n return self._base\n ", "context": "class TimeCode():\n def base(self): ...\n def __init__(self, tc='00:00:00:00', frames=0, base=24): ...\n def from_msec(self, msec, base=24): ...\n def tc(self): ...\n def frames(self): ...\n def toFrames(self, tc): ...\n def __str__(self): ...\n def __repr__(self): ...\n def __add__(self, other): ...\n def __sub__(self, other): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n\n self._base = base\n", "repository": "svenni/editparser", "test_name": "test_base", "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_000058.py"} {"focal_file": "editparser/__init__.py", "focal_class": null, "focal_method": "frames", "tests": "import unittest\n\nclass Test_frames(unittest.TestCase):\n def test_get_frames(self):\n self.assertEquals(self.tc1.frames(), 4)\n", "method_code": " def frames(self):\n return self._frames\n ", "context": "class TimeCode():\n def frames(self): ...\n def __init__(self, tc='00:00:00:00', frames=0, base=24): ...\n def from_msec(self, msec, base=24): ...\n def base(self): ...\n def tc(self): ...\n def toFrames(self, tc): ...\n def __str__(self): ...\n def __repr__(self): ...\n def __add__(self, other): ...\n def __sub__(self, other): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n\n self._base = base\n", "repository": "svenni/editparser", "test_name": "test_get_frames", "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_000059.py"} {"focal_file": "editparser/__init__.py", "focal_class": null, "focal_method": "toFrames", "tests": "import unittest\n\nclass Test_toFrames(unittest.TestCase):\n def test_frames(self):\n self.assertEquals(self.tc.toFrames('00:00:00:01'), 1)\n", "method_code": " def toFrames(self, tc):\n try:\n if tc[0] == '-':\n tc = tc[1:]\n multiplier = -1\n else:\n multiplier = 1\n h, m, s, f = tc.split(':')\n except (ValueError, IndexError):\n raise RuntimeError('Timecode of invalid format, expecting xx:xx:xx:xx, got %s' % tc)\n h = int(h)\n m = int(m)\n s = int(s)\n f = int(f)\n return multiplier * (f + self._base * s + self._base * 60 * m + self._base * 60 * 60 * h)\n ", "context": "class TimeCode():\n def toFrames(self, tc): ...\n def __init__(self, tc='00:00:00:00', frames=0, base=24): ...\n def from_msec(self, msec, base=24): ...\n def base(self): ...\n def tc(self): ...\n def frames(self): ...\n def __str__(self): ...\n def __repr__(self): ...\n def __add__(self, other): ...\n def __sub__(self, other): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n\n self._base = base\n", "repository": "svenni/editparser", "test_name": "test_frames", "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_000060.py"} {"focal_file": "editparser/__init__.py", "focal_class": null, "focal_method": "from_msec", "tests": "import unittest\n\nclass Test_from_msec(unittest.TestCase):\n def test_create_from_msec(self):\n tc = TimeCode.from_msec(2520.0, base=25)\n self.assertEquals(tc.tc(), '00:00:02:13')\n", "method_code": " def from_msec(self, msec, base=24):\n millisec = msec % 1000\n seconds = int(msec / 1000)\n frames = seconds * base + int(base * millisec / 1000)\n return TimeCode(frames=frames, base=base)\n ", "context": "class TimeCode():\n @classmethod\n def from_msec(self, msec, base=24): ...\n def __init__(self, tc='00:00:00:00', frames=0, base=24): ...\n def base(self): ...\n def tc(self): ...\n def frames(self): ...\n def toFrames(self, tc): ...\n def __str__(self): ...\n def __repr__(self): ...\n def __add__(self, other): ...\n def __sub__(self, other): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n\n self._base = base\n", "repository": "svenni/editparser", "test_name": "test_create_from_msec", "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_000061.py"} {"focal_file": "functionalpy/__init__.py", "focal_class": "Seq", "focal_method": "fold", "tests": "import unittest\n\nclass Test_Seq_fold(unittest.TestCase):\n def test_fold(self):\n seq = Seq(1, 2, 3, 4, 5)\n expect = 15\n actual = seq.fold(lambda x, y: x + y, 0)\n self.assertEqual(expect, actual)\n", "method_code": " def fold(self, f, x):\n return reduce(f, self, x)\n ", "context": "class Seq(listMonadFoldableMonoidGeneric[A]):\n def fold(self, f, x): ...\n def __init__(self, *values) -> None: ...\n def to_seq(iterable): ...\n def to_list(self): ...\n def map(self, f): ...\n def ap(self, fs): ...\n def flat_map(self, f): ...\n def flatten(self): ...\n def fold1(self, f): ...\n def mempty(): ...\n def append(self, seq): ...\n def __add__(self, other): ...\n def filter(self, f): ...\n def zip(self, xs): ...\n def zip_with(self, f, xs): ...\n def zip_with_index(self): ...\n def unzip(self): ...\n def sort(self): ...\n def sort_by_key(self, key_func): ...\n def group(self): ...\n def group_by(self, key_func): ...\n def reverse(self): ...\n def unique(self): ...\n def for_each(self, f): ...\n def head(self): ...\n def tail(self): ...\n def last(self): ...\n def init(self): ...\n def take(self, n): ...\n def drop(self, n): ...\n def length(self): ...\n def cons(self, a): ...\n def get(self, f): ...\n", "repository": "aruneko/FunctionalPy", "test_name": "test_fold", "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_000062.py"} {"focal_file": "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 def test_sorted_dict(self): ...\n", "repository": "lotooo/vlc-scrobbler", "test_name": "test_py_encode_basestring_ascii", "smells": [1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 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_000063.py"} {"focal_file": "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)]:\n d = v._asdict()\n l = list(v)\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 self.assertEqual(l, json.loads(json.dumps(v, namedtuple_as_object=False)))\n self.assertRaises(TypeError, json.dumps, v, tuple_as_array=False, namedtuple_as_object=False)\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, **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 ``separators`` is an ``(item_separator, dict_separator)`` tuple\n then it will be used instead of the default ``(', ', ': ')`` separators.\n ``(',', ':')`` is the most compact JSON representation.\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 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.\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 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, **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, **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, **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, **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): ...\n", "repository": "lotooo/vlc-scrobbler", "test_name": "test_namedtuple_dumps", "smells": [1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 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_000064.py"} {"focal_file": "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)]:\n d = v._asdict()\n l = list(v)\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 sio = StringIO()\n json.dump(v, sio, namedtuple_as_object=False)\n self.assertEqual(l, json.loads(sio.getvalue()))\n self.assertRaises(TypeError, json.dump, v, StringIO(), tuple_as_array=False, namedtuple_as_object=False)\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, **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 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 ``separators`` is an ``(item_separator, dict_separator)`` tuple\n then it will be used instead of the default ``(', ', ': ')`` separators.\n ``(',', ':')`` is the most compact JSON representation.\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 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.\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 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, **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, **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, **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, **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): ...\n", "repository": "lotooo/vlc-scrobbler", "test_name": "test_namedtuple_dump", "smells": [1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 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_000065.py"} {"focal_file": "pycscope/__init__.py", "focal_class": null, "focal_method": "genFiles", "tests": "import unittest\n\nclass Test_genFiles(unittest.TestCase):\n def testgenfiles(self):\n tmpd = tempfile.mkdtemp()\n try:\n with open(os.path.join(tmpd, 'a.py'), 'w') as a:\n a.write('a = 1\\n')\n with open(os.path.join(tmpd, 'b'), 'w') as b:\n b.write('b = 1\\n')\n sd = os.path.join(tmpd, 's')\n os.mkdir(sd)\n with open(os.path.join(sd, 'c.py'), 'w') as c:\n c.write('c = 1\\n')\n with open(os.path.join(sd, 'd.py'), 'w') as d:\n d.write('d = 1\\n')\n std = os.path.join(sd, 't')\n os.mkdir(std)\n with open(os.path.join(std, 'e.py'), 'w') as e:\n e.write('e = 1\\n')\n with open(os.path.join(std, 'f.py'), 'w') as f:\n f.write('f = 1\\n')\n fs = list(pycscope.genFiles(tmpd, ['a.py', 'b', 's'], True, []))\n self.assertEquals(fs, ['a.py', 's/c.py', 's/d.py', 's/t/e.py', 's/t/f.py'])\n finally:\n shutil.rmtree(tmpd)\n", "method_code": "def genFiles(basepath, args, recurse, exclude):\n \"\"\" A generator for returning all the files that need to be parsed.\n Caller is required to provide synchronization.\n \"\"\"\n for name in sorted(args):\n name_n = os.path.normpath(name)\n if name_n in exclude:\n continue\n if os.path.isdir(os.path.join(basepath, name_n)):\n for fname in parseDir(basepath, name_n, recurse, exclude):\n yield fname\n elif isPython(name_n):\n yield name_n", "context": "def genFiles(basepath, args, recurse, exclude): ...\ndef main(argv=None): ...\ndef writeIndex(basepath, fout, indexbuff, fnamesbuff): ...\ndef work(basepath, gen, debug): ...\ndef isPython(name): ...\ndef genFiles(basepath, args, recurse, exclude): ...\ndef parseDir(basepath, relpath, recurse, exclude): ...\ndef parseFile(basepath, relpath, indexbuff, indexbuff_len, fnamesbuff, dump=False): ...\ndef replaceNodeType(treeList): ...\ndef dumpCst(cst, stream=None): ...\ndef isNamedFuncCall(cst, cst_len): ...\ndef isTrailerFuncCall(cst, idx, cst_len): ...\ndef markTestlist(ctx, cst): ...\ndef processNonTerminal(ctx, cst): ...\ndef processTerminal(ctx, cst): ...\ndef walkCst(ctx, cst): ...\ndef parseSource(sourcecode, indexbuff, indexbuff_len, dump=False): ...\n", "repository": "portante/pycscope", "test_name": "testgenfiles", "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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000066.py"} {"focal_file": "pycscope/__init__.py", "focal_class": "Symbol", "focal_method": "format", "tests": "import unittest\n\nclass Test_Symbol_format(unittest.TestCase):\n def testFormat(self):\n s = Symbol('hi')\n self.assertEqual('hi', s.format())\n s = Symbol('bye', '~')\n self.assertEqual('\\t~bye', s.format())\n", "method_code": " def format(self):\n \"\"\" Marks are represented as a string with a tab character\n followed by the mark character itself, if it has\n one. Otherwise it is an empty string.\n \"\"\"\n if self.__mark:\n return '\\t%s' % self.__mark\n else:\n return self.__mark\n ", "context": "class Mark(object):\n def format(self): ...\n def __init__(self, mark=''): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n def __repr__(self): ...\n def __getattr__(self, name): ...\n\n self.__mark = mark or ''\n\n FILE = '@'\n FUNC_DEF = '$'\n FUNC_CALL = '`'\n FUNC_END = '}'\n INCLUDE = '~'\n ASSIGN = '='\n CLASS = 'c'\n GLOBAL = 'g'\n LOCAL = 'l'\n __valid = (FILE, FUNC_DEF, FUNC_CALL, FUNC_END, INCLUDE, ASSIGN, CLASS, GLOBAL, LOCAL)\n __str__ = format\n", "repository": "portante/pycscope", "test_name": "testFormat", "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_000067.py"} {"focal_file": "pycscope/__init__.py", "focal_class": null, "focal_method": "work", "tests": "import unittest\n\nclass Test_work(unittest.TestCase):\n def testwork(self):\n tmpd = tempfile.mkdtemp()\n try:\n with open(os.path.join(tmpd, 'a'), 'w') as a:\n a.write('a = 1\\n')\n with open(os.path.join(tmpd, 'b'), 'w') as b:\n b.write('b = 1\\n')\n with open(os.path.join(tmpd, 's'), 'w') as s:\n s.write('a a (b)\\n')\n ibuf, fbuf = pycscope.work(tmpd, ['a', 's', 'b'], False)\n self.assertEquals(ibuf, ['\\n\\t@a\\n\\n', '1 \\n\\t=a\\n = 1\\n\\n', '\\n\\t@s\\n\\n', '\\n\\t@b\\n\\n', '1 \\n\\t=b\\n = 1\\n\\n'])\n self.assertEquals(fbuf, ['a', 's', 'b'])\n finally:\n shutil.rmtree(tmpd)\n", "method_code": "def work(basepath, gen, debug):\n \"\"\" The actual work of parsing the files.\n \"\"\"\n indexbuff = []\n indexbuff_len = 0\n fnamesbuff = []\n for fname in gen:\n try:\n indexbuff_len = parseFile(basepath, fname, indexbuff, indexbuff_len, fnamesbuff, dump=debug)\n except (SyntaxError, AssertionError) as e:\n print('pycscope.py: %s: Line %s: %s' % (e.filename, e.lineno, e))\n pass\n except UnicodeDecodeError as e:\n print('pycscope.py: %s: %s' % (e.filename, e))\n pass\n return (indexbuff, fnamesbuff)", "context": "def work(basepath, gen, debug): ...\ndef main(argv=None): ...\ndef writeIndex(basepath, fout, indexbuff, fnamesbuff): ...\ndef work(basepath, gen, debug): ...\ndef isPython(name): ...\ndef genFiles(basepath, args, recurse, exclude): ...\ndef parseDir(basepath, relpath, recurse, exclude): ...\ndef parseFile(basepath, relpath, indexbuff, indexbuff_len, fnamesbuff, dump=False): ...\ndef replaceNodeType(treeList): ...\ndef dumpCst(cst, stream=None): ...\ndef isNamedFuncCall(cst, cst_len): ...\ndef isTrailerFuncCall(cst, idx, cst_len): ...\ndef markTestlist(ctx, cst): ...\ndef processNonTerminal(ctx, cst): ...\ndef processTerminal(ctx, cst): ...\ndef walkCst(ctx, cst): ...\ndef parseSource(sourcecode, indexbuff, indexbuff_len, dump=False): ...\n", "repository": "portante/pycscope", "test_name": "testwork", "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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000068.py"} {"focal_file": "gluster/swift/common/middleware/gswauth/swauth/authtypes.py", "focal_class": null, "focal_method": "encode", "tests": "import unittest\n\nclass Test_encode(unittest.TestCase):\n def test_plaintext_encode(self):\n enc_key = self.auth_encoder.encode('keystring')\n self.assertEquals('plaintext:keystring', enc_key)\n\n def test_sha1_encode(self):\n enc_key = self.auth_encoder.encode('keystring')\n self.assertEquals('sha1:salt$d50dc700c296e23ce5b41f7431a0e01f69010f06', enc_key)\n\n def test_plaintext_encode(self):\n enc_key = self.auth_encoder.encode('keystring')\n self.assertEquals('plaintext:keystring', enc_key)\n\n def test_sha1_encode(self):\n enc_key = self.auth_encoder.encode('keystring')\n self.assertEquals('sha1:salt$d50dc700c296e23ce5b41f7431a0e01f69010f06', enc_key)\n", "method_code": " def encode(self, key):\n \"\"\"\n Encodes a user key into a particular format. The result of this method\n will be used by swauth for storing user credentials.\n \n :param key: User's secret key\n :returns: A string representing user credentials\n \"\"\"\n return 'plaintext:%s' % key\n ", "context": "class Plaintext(object):\n def encode(self, key): ...\n def match(self, key, creds): ...\n", "repository": "portante/gluster-swift", "test_name": "test_plaintext_encode", "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_000069.py"} {"focal_file": "gluster/swift/common/middleware/gswauth/swauth/authtypes.py", "focal_class": null, "focal_method": "match", "tests": "import unittest\n\nclass Test_match(unittest.TestCase):\n def test_plaintext_valid_match(self):\n creds = 'plaintext:keystring'\n match = self.auth_encoder.match('keystring', creds)\n self.assertEquals(match, True)\n\n def test_plaintext_invalid_match(self):\n creds = 'plaintext:other-keystring'\n match = self.auth_encoder.match('keystring', creds)\n self.assertEquals(match, False)\n\n def test_sha1_valid_match(self):\n creds = 'sha1:salt$d50dc700c296e23ce5b41f7431a0e01f69010f06'\n match = self.auth_encoder.match('keystring', creds)\n self.assertEquals(match, True)\n\n def test_sha1_invalid_match(self):\n creds = 'sha1:salt$deadbabedeadbabedeadbabec0ffeebadc0ffeee'\n match = self.auth_encoder.match('keystring', creds)\n self.assertEquals(match, False)\n\n def test_plaintext_valid_match(self):\n creds = 'plaintext:keystring'\n match = self.auth_encoder.match('keystring', creds)\n self.assertEquals(match, True)\n\n def test_plaintext_invalid_match(self):\n creds = 'plaintext:other-keystring'\n match = self.auth_encoder.match('keystring', creds)\n self.assertEquals(match, False)\n\n def test_sha1_valid_match(self):\n creds = 'sha1:salt$d50dc700c296e23ce5b41f7431a0e01f69010f06'\n match = self.auth_encoder.match('keystring', creds)\n self.assertEquals(match, True)\n\n def test_sha1_invalid_match(self):\n creds = 'sha1:salt$deadbabedeadbabedeadbabec0ffeebadc0ffeee'\n match = self.auth_encoder.match('keystring', creds)\n self.assertEquals(match, False)\n", "method_code": " def match(self, key, creds):\n \"\"\"\n Checks whether the user-provided key matches the user's credentials\n \n :param key: User-supplied key\n :param creds: User's stored credentials\n :returns: True if the supplied key is valid, False otherwise\n \"\"\"\n return self.encode(key) == creds\n ", "context": "class Plaintext(object):\n def match(self, key, creds): ...\n def encode(self, key): ...\n", "repository": "portante/gluster-swift", "test_name": "test_plaintext_valid_match", "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_000070.py"} {"focal_file": "test/unit/common/middleware/gswauth/swauth/test_middleware.py", "focal_class": null, "focal_method": "_make_request", "tests": "import unittest\n\nclass Test_make_request(unittest.TestCase):\n def test_detect_reseller_request(self):\n req = self._make_request('/v1/AUTH_admin', headers={'X-Auth-Token': 'AUTH_t'})\n cache_key = 'AUTH_/auth/AUTH_t'\n cache_entry = (time() + 3600, '.reseller_admin')\n req.environ['swift.cache'].set(cache_key, cache_entry)\n self.assertTrue(req.environ.get('reseller_request'))\n", "method_code": " def _make_request(self, path, **kwargs):\n req = Request.blank(path, **kwargs)\n req.environ['swift.cache'] = FakeMemcache()\n return req\n ", "context": "class TestAuth(unittest.TestCase):\n def _make_request(self, path, **kwargs): ...\n def setUp(self): ...\n def test_super_admin_key_not_required(self): ...\n def test_reseller_prefix_init(self): ...\n def test_auth_prefix_init(self): ...\n def test_no_auth_type_init(self): ...\n def test_valid_auth_type_init(self): ...\n def test_invalid_auth_type_init(self): ...\n def test_default_metadata_volume_init(self): ...\n def test_conf_metadata_volume_init(self): ...\n def test_default_swift_cluster_init(self): ...\n def test_top_level_denied(self): ...\n def test_anon(self): ...\n def test_auth_deny_non_reseller_prefix(self): ...\n def test_auth_deny_non_reseller_prefix_no_override(self): ...\n def test_auth_no_reseller_prefix_deny(self): ...\n def test_auth_no_reseller_prefix_allow(self): ...\n def test_auth_no_reseller_prefix_no_token(self): ...\n def test_auth_fail(self): ...\n def test_auth_success(self): ...\n def test_auth_memcache(self): ...\n def test_auth_just_expired(self): ...\n def test_middleware_storage_token(self): ...\n def test_authorize_bad_path(self): ...\n def test_authorize_account_access(self): ...\n def test_authorize_acl_group_access(self): ...\n def test_deny_cross_reseller(self): ...\n def test_authorize_acl_referrer_access(self): ...\n def test_detect_reseller_request(self): ...\n def test_account_put_permissions(self): ...\n def test_account_delete_permissions(self): ...\n def test_get_token_fail(self): ...\n def test_get_token_fail_invalid_key(self): ...\n def test_get_token_fail_invalid_x_auth_user_format(self): ...\n def test_get_token_fail_non_matching_account_in_request(self): ...\n def test_get_token_fail_bad_path(self): ...\n def test_get_token_fail_missing_key(self): ...\n def test_get_token_fail_get_user_details(self): ...\n def test_get_token_fail_get_account(self): ...\n def test_get_token_fail_put_new_token(self): ...\n def test_get_token_fail_post_to_user(self): ...\n def test_get_token_fail_get_services(self): ...\n def test_get_token_fail_get_existing_token(self): ...\n def test_get_token_success_v1_0(self): ...\n def test_get_token_success_v1_0_with_user_token_life(self): ...\n def test_get_token_success_v1_0_with_user_token_life_past_max(self): ...\n def test_get_token_success_v1_act_auth(self): ...\n def test_get_token_success_storage_instead_of_auth(self): ...\n def test_get_token_success_v1_act_auth_auth_instead_of_storage(self): ...\n def test_get_token_success_existing_token(self): ...\n def test_get_token_success_existing_token_but_request_new_one(self): ...\n def test_get_token_success_existing_token_expired(self): ...\n def test_get_token_success_existing_token_expired_fail_deleting_old(self): ...\n def test_prep_success(self): ...\n def test_prep_bad_method(self): ...\n def test_prep_bad_creds(self): ...\n def test_prep_fail_account_create(self): ...\n def test_prep_fail_token_container_create(self): ...\n def test_prep_fail_account_id_container_create(self): ...\n def test_get_reseller_success(self): ...\n def test_get_reseller_fail_bad_creds(self): ...\n def test_get_reseller_fail_listing(self): ...\n def test_get_account_success(self): ...\n def test_get_account_fail_bad_account_name(self): ...\n def test_get_account_fail_creds(self): ...\n def test_get_account_fail_get_services(self): ...\n def test_get_account_fail_listing(self): ...\n def test_set_services_new_service(self): ...\n def test_set_services_new_endpoint(self): ...\n def test_set_services_update_endpoint(self): ...\n def test_set_services_fail_bad_creds(self): ...\n def test_set_services_fail_bad_account_name(self): ...\n def test_set_services_fail_bad_json(self): ...\n def test_set_services_fail_get_services(self): ...\n def test_set_services_fail_put_services(self): ...\n def test_put_account_success(self): ...\n def test_put_account_success_preexist_but_not_completed(self): ...\n def test_put_account_success_preexist_and_completed(self): ...\n def test_put_account_success_with_given_suffix(self): ...\n def test_put_account_fail_bad_creds(self): ...\n def test_put_account_fail_invalid_account_name(self): ...\n def test_put_account_fail_on_initial_account_head(self): ...\n def test_put_account_fail_on_account_marker_put(self): ...\n def test_put_account_fail_on_storage_account_put(self): ...\n def test_put_account_fail_on_account_id_mapping(self): ...\n def test_put_account_fail_on_services_object(self): ...\n def test_put_account_fail_on_post_mapping(self): ...\n def test_delete_account_success(self): ...\n def test_delete_account_success_missing_services(self): ...\n def test_delete_account_success_missing_storage_account(self): ...\n def test_delete_account_success_missing_account_id_mapping(self): ...\n def test_delete_account_success_missing_account_container_at_end(self): ...\n def test_delete_account_fail_bad_creds(self): ...\n def test_delete_account_fail_invalid_account_name(self): ...\n def test_delete_account_fail_not_found(self): ...\n def test_delete_account_fail_not_found_concurrency(self): ...\n def test_delete_account_fail_list_account(self): ...\n def test_delete_account_fail_list_account_concurrency(self): ...\n def test_delete_account_fail_has_users(self): ...\n def test_delete_account_fail_has_users2(self): ...\n def test_delete_account_fail_get_services(self): ...\n def test_delete_account_fail_delete_storage_account(self): ...\n def test_delete_account_fail_delete_storage_account2(self): ...\n def test_delete_account_fail_delete_storage_account3(self): ...\n def test_delete_account_fail_delete_storage_account4(self): ...\n def test_delete_account_fail_delete_services(self): ...\n def test_delete_account_fail_delete_account_id_mapping(self): ...\n def test_delete_account_fail_delete_account_container(self): ...\n def test_get_user_success(self): ...\n def test_get_user_fail_no_super_admin_key(self): ...\n def test_get_user_groups_success(self): ...\n def test_get_user_groups_success2(self): ...\n def test_get_user_fail_invalid_account(self): ...\n def test_get_user_fail_invalid_user(self): ...\n def test_get_user_fail_bad_creds(self): ...\n def test_get_user_account_admin_success(self): ...\n def test_get_user_account_admin_fail_getting_account_admin(self): ...\n def test_get_user_account_admin_fail_getting_reseller_admin(self): ...\n def test_get_user_reseller_admin_fail_getting_reseller_admin(self): ...\n def test_get_user_super_admin_succeed_getting_reseller_admin(self): ...\n def test_get_user_groups_not_found(self): ...\n def test_get_user_groups_fail_listing(self): ...\n def test_get_user_groups_fail_get_user(self): ...\n def test_get_user_not_found(self): ...\n def test_get_user_fail(self): ...\n def test_put_user_fail_invalid_account(self): ...\n def test_put_user_fail_invalid_user(self): ...\n def test_put_user_fail_no_user_key(self): ...\n def test_put_user_reseller_admin_fail_bad_creds(self): ...\n def test_put_user_account_admin_fail_bad_creds(self): ...\n def test_put_user_regular_fail_bad_creds(self): ...\n def test_put_user_regular_success(self): ...\n def test_put_user_special_chars_success(self): ...\n def test_put_user_account_admin_success(self): ...\n def test_put_user_reseller_admin_success(self): ...\n def test_put_user_fail_not_found(self): ...\n def test_put_user_fail(self): ...\n def test_delete_user_bad_creds(self): ...\n def test_delete_user_invalid_account(self): ...\n def test_delete_user_invalid_user(self): ...\n def test_delete_user_not_found(self): ...\n def test_delete_user_fail_head_user(self): ...\n def test_delete_user_fail_delete_token(self): ...\n def test_delete_user_fail_delete_user(self): ...\n def test_delete_user_success(self): ...\n def test_delete_user_success_missing_user_at_end(self): ...\n def test_delete_user_success_missing_token(self): ...\n def test_delete_user_success_no_token(self): ...\n def test_validate_token_bad_prefix(self): ...\n def test_validate_token_tmi(self): ...\n def test_validate_token_bad_memcache(self): ...\n def test_validate_token_from_memcache(self): ...\n def test_validate_token_from_memcache_expired(self): ...\n def test_validate_token_from_object(self): ...\n def test_validate_token_from_object_expired(self): ...\n def test_validate_token_from_object_with_admin(self): ...\n def test_get_conn_default(self): ...\n def test_get_conn_default_https(self): ...\n def test_get_conn_overridden(self): ...\n def test_get_conn_overridden_https(self): ...\n def test_get_itoken_fail_no_memcache(self): ...\n def test_get_itoken_success(self): ...\n def test_get_admin_detail_fail_no_colon(self): ...\n def test_get_admin_detail_fail_user_not_found(self): ...\n def test_get_admin_detail_fail_get_user_error(self): ...\n def test_get_admin_detail_success(self): ...\n def test_credentials_match_success(self): ...\n def test_credentials_match_fail_no_details(self): ...\n def test_credentials_match_fail_plaintext(self): ...\n def test_is_super_admin_success(self): ...\n def test_is_super_admin_fail_bad_key(self): ...\n def test_is_super_admin_fail_bad_user(self): ...\n def test_is_reseller_admin_success_is_super_admin(self): ...\n def test_is_reseller_admin_success_called_get_admin_detail(self): ...\n def test_is_reseller_admin_fail_only_account_admin(self): ...\n def test_is_reseller_admin_fail_regular_user(self): ...\n def test_is_reseller_admin_fail_bad_key(self): ...\n def test_is_account_admin_success_is_super_admin(self): ...\n def test_is_account_admin_success_is_reseller_admin(self): ...\n def test_is_account_admin_success(self): ...\n def test_is_account_admin_fail_account_admin_different_account(self): ...\n def test_is_account_admin_fail_regular_user(self): ...\n def test_is_account_admin_fail_bad_key(self): ...\n def test_reseller_admin_but_account_is_internal_use_only(self): ...\n def test_reseller_admin_but_account_is_exactly_reseller_prefix(self): ...\n def _get_token_success_v1_0_encoded(self, saved_user, saved_key, sent_user, sent_key): ...\n def test_get_token_success_v1_0_encoded1(self): ...\n def test_get_token_success_v1_0_encoded2(self): ...\n def test_get_token_success_v1_0_encoded3(self): ...\n def test_allowed_sync_hosts(self): ...\n def test_reseller_admin_is_owner(self): ...\n def test_admin_is_owner(self): ...\n def test_regular_is_not_owner(self): ...\n def test_sync_request_success(self): ...\n def test_sync_request_fail_key(self): ...\n def test_sync_request_fail_no_timestamp(self): ...\n def test_sync_request_fail_sync_host(self): ...\n def test_sync_request_success_lb_sync_host(self): ...\n def test_override_asked_for_but_not_allowed(self): ...\n def test_override_asked_for_and_allowed(self): ...\n def test_override_default_allowed(self): ...\n def test_token_too_long(self): ...\n def test_crazy_authorization(self): ...\n", "repository": "portante/gluster-swift", "test_name": "test_detect_reseller_request", "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_000071.py"} {"focal_file": "test/unit/common/middleware/gswauth/swauth/test_middleware.py", "focal_class": null, "focal_method": "_get_token_success_v1_0_encoded", "tests": "import unittest\n\nclass Test_get_token_success_v1_0_encoded(unittest.TestCase):\n def test_get_token_success_v1_0_encoded1(self):\n self._get_token_success_v1_0_encoded('act:usr', 'key', 'act%3ausr', 'key')\n\n def test_get_token_success_v1_0_encoded2(self):\n self._get_token_success_v1_0_encoded('act:u s r', 'key', 'act%3au%20s%20r', 'key')\n\n def test_get_token_success_v1_0_encoded3(self):\n self._get_token_success_v1_0_encoded('act:u s r', 'k:e:y', 'act%3au%20s%20r', 'k%3Ae%3ay')\n", "method_code": " def _get_token_success_v1_0_encoded(self, saved_user, saved_key, sent_user, sent_key):\n self.test_auth.app = FakeApp(iter([('200 Ok', {}, json.dumps({'auth': 'plaintext:%s' % saved_key, 'groups': [{'name': saved_user}, {'name': 'act'}, {'name': '.admin'}]})), ('204 Ok', {'X-Container-Meta-Account-Id': 'AUTH_cfa'}, ''), ('201 Created', {}, ''), ('204 No Content', {}, ''), ('200 Ok', {}, json.dumps({'storage': {'default': 'local', 'local': 'http://127.0.0.1:8080/v1/AUTH_cfa'}}))]))\n resp = Request.blank('/auth/v1.0', headers={'X-Auth-User': sent_user, 'X-Auth-Key': sent_key}).get_response(self.test_auth)\n self.assertEquals(resp.status_int, 200)\n self.assert_(resp.headers.get('x-auth-token', '').startswith('AUTH_tk'), resp.headers.get('x-auth-token'))\n self.assertEquals(resp.headers.get('x-auth-token'), resp.headers.get('x-storage-token'))\n self.assertEquals(resp.headers.get('x-storage-url'), 'http://127.0.0.1:8080/v1/AUTH_cfa')\n self.assertEquals(json.loads(resp.body), {'storage': {'default': 'local', 'local': 'http://127.0.0.1:8080/v1/AUTH_cfa'}})\n self.assertEquals(self.test_auth.app.calls, 5)\n ", "context": "class TestAuth(unittest.TestCase):\n def _get_token_success_v1_0_encoded(self, saved_user, saved_key, sent_user, sent_key): ...\n def setUp(self): ...\n def test_super_admin_key_not_required(self): ...\n def test_reseller_prefix_init(self): ...\n def test_auth_prefix_init(self): ...\n def test_no_auth_type_init(self): ...\n def test_valid_auth_type_init(self): ...\n def test_invalid_auth_type_init(self): ...\n def test_default_metadata_volume_init(self): ...\n def test_conf_metadata_volume_init(self): ...\n def test_default_swift_cluster_init(self): ...\n def test_top_level_denied(self): ...\n def test_anon(self): ...\n def test_auth_deny_non_reseller_prefix(self): ...\n def test_auth_deny_non_reseller_prefix_no_override(self): ...\n def test_auth_no_reseller_prefix_deny(self): ...\n def test_auth_no_reseller_prefix_allow(self): ...\n def test_auth_no_reseller_prefix_no_token(self): ...\n def test_auth_fail(self): ...\n def test_auth_success(self): ...\n def test_auth_memcache(self): ...\n def test_auth_just_expired(self): ...\n def test_middleware_storage_token(self): ...\n def test_authorize_bad_path(self): ...\n def test_authorize_account_access(self): ...\n def test_authorize_acl_group_access(self): ...\n def test_deny_cross_reseller(self): ...\n def test_authorize_acl_referrer_access(self): ...\n def test_detect_reseller_request(self): ...\n def test_account_put_permissions(self): ...\n def test_account_delete_permissions(self): ...\n def test_get_token_fail(self): ...\n def test_get_token_fail_invalid_key(self): ...\n def test_get_token_fail_invalid_x_auth_user_format(self): ...\n def test_get_token_fail_non_matching_account_in_request(self): ...\n def test_get_token_fail_bad_path(self): ...\n def test_get_token_fail_missing_key(self): ...\n def test_get_token_fail_get_user_details(self): ...\n def test_get_token_fail_get_account(self): ...\n def test_get_token_fail_put_new_token(self): ...\n def test_get_token_fail_post_to_user(self): ...\n def test_get_token_fail_get_services(self): ...\n def test_get_token_fail_get_existing_token(self): ...\n def test_get_token_success_v1_0(self): ...\n def test_get_token_success_v1_0_with_user_token_life(self): ...\n def test_get_token_success_v1_0_with_user_token_life_past_max(self): ...\n def test_get_token_success_v1_act_auth(self): ...\n def test_get_token_success_storage_instead_of_auth(self): ...\n def test_get_token_success_v1_act_auth_auth_instead_of_storage(self): ...\n def test_get_token_success_existing_token(self): ...\n def test_get_token_success_existing_token_but_request_new_one(self): ...\n def test_get_token_success_existing_token_expired(self): ...\n def test_get_token_success_existing_token_expired_fail_deleting_old(self): ...\n def test_prep_success(self): ...\n def test_prep_bad_method(self): ...\n def test_prep_bad_creds(self): ...\n def test_prep_fail_account_create(self): ...\n def test_prep_fail_token_container_create(self): ...\n def test_prep_fail_account_id_container_create(self): ...\n def test_get_reseller_success(self): ...\n def test_get_reseller_fail_bad_creds(self): ...\n def test_get_reseller_fail_listing(self): ...\n def test_get_account_success(self): ...\n def test_get_account_fail_bad_account_name(self): ...\n def test_get_account_fail_creds(self): ...\n def test_get_account_fail_get_services(self): ...\n def test_get_account_fail_listing(self): ...\n def test_set_services_new_service(self): ...\n def test_set_services_new_endpoint(self): ...\n def test_set_services_update_endpoint(self): ...\n def test_set_services_fail_bad_creds(self): ...\n def test_set_services_fail_bad_account_name(self): ...\n def test_set_services_fail_bad_json(self): ...\n def test_set_services_fail_get_services(self): ...\n def test_set_services_fail_put_services(self): ...\n def test_put_account_success(self): ...\n def test_put_account_success_preexist_but_not_completed(self): ...\n def test_put_account_success_preexist_and_completed(self): ...\n def test_put_account_success_with_given_suffix(self): ...\n def test_put_account_fail_bad_creds(self): ...\n def test_put_account_fail_invalid_account_name(self): ...\n def test_put_account_fail_on_initial_account_head(self): ...\n def test_put_account_fail_on_account_marker_put(self): ...\n def test_put_account_fail_on_storage_account_put(self): ...\n def test_put_account_fail_on_account_id_mapping(self): ...\n def test_put_account_fail_on_services_object(self): ...\n def test_put_account_fail_on_post_mapping(self): ...\n def test_delete_account_success(self): ...\n def test_delete_account_success_missing_services(self): ...\n def test_delete_account_success_missing_storage_account(self): ...\n def test_delete_account_success_missing_account_id_mapping(self): ...\n def test_delete_account_success_missing_account_container_at_end(self): ...\n def test_delete_account_fail_bad_creds(self): ...\n def test_delete_account_fail_invalid_account_name(self): ...\n def test_delete_account_fail_not_found(self): ...\n def test_delete_account_fail_not_found_concurrency(self): ...\n def test_delete_account_fail_list_account(self): ...\n def test_delete_account_fail_list_account_concurrency(self): ...\n def test_delete_account_fail_has_users(self): ...\n def test_delete_account_fail_has_users2(self): ...\n def test_delete_account_fail_get_services(self): ...\n def test_delete_account_fail_delete_storage_account(self): ...\n def test_delete_account_fail_delete_storage_account2(self): ...\n def test_delete_account_fail_delete_storage_account3(self): ...\n def test_delete_account_fail_delete_storage_account4(self): ...\n def test_delete_account_fail_delete_services(self): ...\n def test_delete_account_fail_delete_account_id_mapping(self): ...\n def test_delete_account_fail_delete_account_container(self): ...\n def test_get_user_success(self): ...\n def test_get_user_fail_no_super_admin_key(self): ...\n def test_get_user_groups_success(self): ...\n def test_get_user_groups_success2(self): ...\n def test_get_user_fail_invalid_account(self): ...\n def test_get_user_fail_invalid_user(self): ...\n def test_get_user_fail_bad_creds(self): ...\n def test_get_user_account_admin_success(self): ...\n def test_get_user_account_admin_fail_getting_account_admin(self): ...\n def test_get_user_account_admin_fail_getting_reseller_admin(self): ...\n def test_get_user_reseller_admin_fail_getting_reseller_admin(self): ...\n def test_get_user_super_admin_succeed_getting_reseller_admin(self): ...\n def test_get_user_groups_not_found(self): ...\n def test_get_user_groups_fail_listing(self): ...\n def test_get_user_groups_fail_get_user(self): ...\n def test_get_user_not_found(self): ...\n def test_get_user_fail(self): ...\n def test_put_user_fail_invalid_account(self): ...\n def test_put_user_fail_invalid_user(self): ...\n def test_put_user_fail_no_user_key(self): ...\n def test_put_user_reseller_admin_fail_bad_creds(self): ...\n def test_put_user_account_admin_fail_bad_creds(self): ...\n def test_put_user_regular_fail_bad_creds(self): ...\n def test_put_user_regular_success(self): ...\n def test_put_user_special_chars_success(self): ...\n def test_put_user_account_admin_success(self): ...\n def test_put_user_reseller_admin_success(self): ...\n def test_put_user_fail_not_found(self): ...\n def test_put_user_fail(self): ...\n def test_delete_user_bad_creds(self): ...\n def test_delete_user_invalid_account(self): ...\n def test_delete_user_invalid_user(self): ...\n def test_delete_user_not_found(self): ...\n def test_delete_user_fail_head_user(self): ...\n def test_delete_user_fail_delete_token(self): ...\n def test_delete_user_fail_delete_user(self): ...\n def test_delete_user_success(self): ...\n def test_delete_user_success_missing_user_at_end(self): ...\n def test_delete_user_success_missing_token(self): ...\n def test_delete_user_success_no_token(self): ...\n def test_validate_token_bad_prefix(self): ...\n def test_validate_token_tmi(self): ...\n def test_validate_token_bad_memcache(self): ...\n def test_validate_token_from_memcache(self): ...\n def test_validate_token_from_memcache_expired(self): ...\n def test_validate_token_from_object(self): ...\n def test_validate_token_from_object_expired(self): ...\n def test_validate_token_from_object_with_admin(self): ...\n def test_get_conn_default(self): ...\n def test_get_conn_default_https(self): ...\n def test_get_conn_overridden(self): ...\n def test_get_conn_overridden_https(self): ...\n def test_get_itoken_fail_no_memcache(self): ...\n def test_get_itoken_success(self): ...\n def test_get_admin_detail_fail_no_colon(self): ...\n def test_get_admin_detail_fail_user_not_found(self): ...\n def test_get_admin_detail_fail_get_user_error(self): ...\n def test_get_admin_detail_success(self): ...\n def test_credentials_match_success(self): ...\n def test_credentials_match_fail_no_details(self): ...\n def test_credentials_match_fail_plaintext(self): ...\n def test_is_super_admin_success(self): ...\n def test_is_super_admin_fail_bad_key(self): ...\n def test_is_super_admin_fail_bad_user(self): ...\n def test_is_reseller_admin_success_is_super_admin(self): ...\n def test_is_reseller_admin_success_called_get_admin_detail(self): ...\n def test_is_reseller_admin_fail_only_account_admin(self): ...\n def test_is_reseller_admin_fail_regular_user(self): ...\n def test_is_reseller_admin_fail_bad_key(self): ...\n def test_is_account_admin_success_is_super_admin(self): ...\n def test_is_account_admin_success_is_reseller_admin(self): ...\n def test_is_account_admin_success(self): ...\n def test_is_account_admin_fail_account_admin_different_account(self): ...\n def test_is_account_admin_fail_regular_user(self): ...\n def test_is_account_admin_fail_bad_key(self): ...\n def test_reseller_admin_but_account_is_internal_use_only(self): ...\n def test_reseller_admin_but_account_is_exactly_reseller_prefix(self): ...\n def test_get_token_success_v1_0_encoded1(self): ...\n def test_get_token_success_v1_0_encoded2(self): ...\n def test_get_token_success_v1_0_encoded3(self): ...\n def test_allowed_sync_hosts(self): ...\n def test_reseller_admin_is_owner(self): ...\n def test_admin_is_owner(self): ...\n def test_regular_is_not_owner(self): ...\n def test_sync_request_success(self): ...\n def test_sync_request_fail_key(self): ...\n def test_sync_request_fail_no_timestamp(self): ...\n def test_sync_request_fail_sync_host(self): ...\n def test_sync_request_success_lb_sync_host(self): ...\n def _make_request(self, path, **kwargs): ...\n def test_override_asked_for_but_not_allowed(self): ...\n def test_override_asked_for_and_allowed(self): ...\n def test_override_default_allowed(self): ...\n def test_token_too_long(self): ...\n def test_crazy_authorization(self): ...\n", "repository": "portante/gluster-swift", "test_name": "test_get_token_success_v1_0_encoded1", "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_000072.py"} {"focal_file": "gluster/swift/common/Glusterfs.py", "focal_class": null, "focal_method": "_busy_wait", "tests": "import unittest\n\nclass Test_busy_wait(unittest.TestCase):\n def test_busy_wait_timeout(self):\n os.path.ismount = mock_os_path_ismount_false\n real_time_sleep = time.sleep\n time.sleep = mock_time_sleep\n try:\n self.assertFalse(gfs._busy_wait('/'))\n finally:\n time.sleep = real_time_sleep\n\n def test_busy_wait(self):\n self.assertTrue(gfs._busy_wait('/'))\n", "method_code": "def _busy_wait(full_mount_path):\n for i in range(0, 5):\n if os.path.ismount(full_mount_path):\n return True\n time.sleep(2)\n logging.error('Busy wait for mount timed out for mount %s', full_mount_path)\n return False", "context": "def _busy_wait(full_mount_path): ...\ndef _busy_wait(full_mount_path): ...\ndef _get_unique_id(): ...\ndef _get_drive_mount_point_name(drive): ...\ndef mount(root, drive): ...\ndef unmount(full_mount_path): ...\ndef _get_export_list(): ...\n", "repository": "portante/gluster-swift", "test_name": "test_busy_wait_timeout", "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, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000073.py"} {"focal_file": "gluster/swift/common/Glusterfs.py", "focal_class": null, "focal_method": "mount", "tests": "import unittest\n\nclass Test_mount(unittest.TestCase):\n def test_mount(self):\n try:\n tmpdir = mkdtemp()\n root = os.path.join(tmpdir, 'mnt/gluster-object')\n drive = 'test'\n _init_mock_variables(tmpdir)\n assert gfs.mount(root, drive)\n finally:\n _reset_mock_variables()\n shutil.rmtree(tmpdir)\n", "method_code": "def mount(root, drive):\n \"\"\"\n Verify that the path to the device is a mount point and mounted. This\n allows us to fast fail on drives that have been unmounted because of\n issues, and also prevents us for accidentally filling up the root\n partition.\n\n This method effectively replaces the swift.common.constraints.check_mount\n method in behavior, adding the ability to auto-mount the volume, which is\n dubious (FIXME).\n\n :param root: base path where the devices are mounted\n :param drive: drive name to be checked\n :returns: True if it is a valid mounted device, False otherwise\n \"\"\"\n if not urllib.quote_plus(drive) == drive:\n return False\n mount_point = _get_drive_mount_point_name(drive)\n full_mount_path = os.path.join(root, mount_point)\n if do_ismount(full_mount_path):\n return True\n el = _get_export_list()\n for export in el:\n if drive == export:\n break\n else:\n logging.error('No export found in %r matching drive, %s', el, drive)\n return False\n try:\n os.makedirs(full_mount_path)\n except OSError as err:\n if err.errno == errno.EEXIST:\n pass\n else:\n logging.exception('Could not create mount path hierarchy: %s' % full_mount_path)\n return False\n mnt_cmd = 'mount -t glusterfs %s:%s %s' % (MOUNT_IP, export, full_mount_path)\n if _allow_mount_per_server:\n if os.system(mnt_cmd):\n logging.exception('Mount failed %s' % mnt_cmd)\n return True\n lck_file = os.path.join(RUN_DIR, '%s.lock' % mount_point)\n try:\n os.mkdir(RUN_DIR)\n except OSError as err:\n if err.errno == errno.EEXIST:\n pass\n else:\n logging.exception('Could not create RUN_DIR: %s' % full_mount_path)\n return False\n fd = os.open(lck_file, os.O_CREAT | os.O_RDWR)\n with os.fdopen(fd, 'r+b') as f:\n try:\n fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)\n except IOError as ex:\n if ex.errno in (errno.EACCES, errno.EAGAIN):\n return _busy_wait(full_mount_path)\n if os.system(mnt_cmd) or not _busy_wait(full_mount_path):\n logging.error('Mount failed %s', mnt_cmd)\n return False\n return True", "context": "def mount(root, drive): ...\ndef _busy_wait(full_mount_path): ...\ndef _get_unique_id(): ...\ndef _get_drive_mount_point_name(drive): ...\ndef mount(root, drive): ...\ndef unmount(full_mount_path): ...\ndef _get_export_list(): ...\n", "repository": "portante/gluster-swift", "test_name": "test_mount", "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, 0], "pynose_source_file": "test_000074.py"} {"focal_file": "gluster/swift/common/constraints.py", "focal_class": null, "focal_method": "set_object_name_component_length", "tests": "import unittest\n\nclass Test_set_object_name_component_length(unittest.TestCase):\n def test_set_object_name_component_length(self):\n len = cnt.get_object_name_component_length()\n cnt.set_object_name_component_length(len + 1)\n self.assertEqual(len, cnt.get_object_name_component_length() - 1)\n if hasattr(swift.common.constraints, 'constraints_conf_int'):\n len = swift.common.constraints.constraints_conf_int('max_object_name_component_length', 255)\n cnt.set_object_name_component_length()\n self.assertEqual(len, cnt.get_object_name_component_length())\n with patch('swift.common.constraints.constraints_conf_int', mock_constraints_conf_int):\n cnt.set_object_name_component_length()\n self.assertEqual(cnt.get_object_name_component_length(), 1000)\n", "method_code": "def set_object_name_component_length(len=None):\n global MAX_OBJECT_NAME_COMPONENT_LENGTH\n if len:\n MAX_OBJECT_NAME_COMPONENT_LENGTH = len\n elif hasattr(swift.common.constraints, 'constraints_conf_int'):\n MAX_OBJECT_NAME_COMPONENT_LENGTH = swift.common.constraints.constraints_conf_int('max_object_name_component_length', 255)\n else:\n MAX_OBJECT_NAME_COMPONENT_LENGTH = 255\n return", "context": "def set_object_name_component_length(len=None): ...\ndef set_object_name_component_length(len=None): ...\ndef get_object_name_component_length(): ...\ndef validate_obj_name_component(obj): ...\ndef gluster_check_object_creation(req, object_name): ...\n", "repository": "portante/gluster-swift", "test_name": "test_set_object_name_component_length", "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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000075.py"} {"focal_file": "gluster/swift/common/constraints.py", "focal_class": null, "focal_method": "validate_obj_name_component", "tests": "import unittest\n\nclass Test_validate_obj_name_component(unittest.TestCase):\n def test_validate_obj_name_component(self):\n max_obj_len = cnt.get_object_name_component_length()\n self.assertFalse(cnt.validate_obj_name_component('tests' * (max_obj_len / 5)))\n cnt.set_object_name_component_length(300)\n self.assertFalse(cnt.validate_obj_name_component('tests' * 60))\n\n def test_validate_obj_name_component_err(self):\n max_obj_len = cnt.get_object_name_component_length()\n self.assertTrue(cnt.validate_obj_name_component('tests' * (max_obj_len / 5 + 1)))\n self.assertTrue(cnt.validate_obj_name_component('.'))\n self.assertTrue(cnt.validate_obj_name_component('..'))\n self.assertTrue(cnt.validate_obj_name_component(''))\n", "method_code": "def validate_obj_name_component(obj):\n if not obj:\n return \"cannot begin, end, or have contiguous %s's\" % os.path.sep\n if len(obj) > MAX_OBJECT_NAME_COMPONENT_LENGTH:\n return 'too long (%d)' % len(obj)\n if obj == '.' or obj == '..':\n return 'cannot be . or ..'\n return ''", "context": "def validate_obj_name_component(obj): ...\ndef set_object_name_component_length(len=None): ...\ndef get_object_name_component_length(): ...\ndef validate_obj_name_component(obj): ...\ndef gluster_check_object_creation(req, object_name): ...\n", "repository": "portante/gluster-swift", "test_name": "test_validate_obj_name_component", "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_000076.py"} {"focal_file": "gluster/swift/common/constraints.py", "focal_class": null, "focal_method": "gluster_check_object_creation", "tests": "import unittest\n\nclass Test_gluster_check_object_creation(unittest.TestCase):\n def test_gluster_check_object_creation(self):\n with patch('gluster.swift.common.constraints.__check_object_creation', mock_check_object_creation):\n self.assertFalse(cnt.gluster_check_object_creation(None, 'dir/z'))\n\n def test_gluster_check_object_creation_err(self):\n with patch('gluster.swift.common.constraints.__check_object_creation', mock_check_object_creation):\n self.assertTrue(cnt.gluster_check_object_creation(None, 'dir/.'))\n", "method_code": "def gluster_check_object_creation(req, object_name):\n \"\"\"\n Check to ensure that everything is alright about an object to be created.\n Monkey patches swift.common.constraints.check_object_creation, invoking\n the original, and then adding an additional check for individual object\n name components.\n\n :param req: HTTP request object\n :param object_name: name of object to be created\n :raises HTTPRequestEntityTooLarge: the object is too large\n :raises HTTPLengthRequered: missing content-length header and not\n a chunked request\n :raises HTTPBadRequest: missing or bad content-type header, or\n bad metadata\n \"\"\"\n ret = __check_object_creation(req, object_name)\n if ret is None:\n for obj in object_name.split(os.path.sep):\n reason = validate_obj_name_component(obj)\n if reason:\n bdy = 'Invalid object name \"%s\", component \"%s\" %s' % (object_name, obj, reason)\n ret = HTTPBadRequest(body=bdy, request=req, content_type='text/plain')\n return ret", "context": "def gluster_check_object_creation(req, object_name): ...\ndef set_object_name_component_length(len=None): ...\ndef get_object_name_component_length(): ...\ndef validate_obj_name_component(obj): ...\ndef gluster_check_object_creation(req, object_name): ...\n", "repository": "portante/gluster-swift", "test_name": "test_gluster_check_object_creation", "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_000077.py"} {"focal_file": "gluster/swift/common/DiskDir.py", "focal_class": null, "focal_method": "_read_metadata", "tests": "import unittest\n\nclass Test_read_metadata(unittest.TestCase):\n def test__read_metadata(self):\n\n def fake_read_metadata(p):\n return {'a': 1, 'b': ('c', 5)}\n orig_rm = dd.read_metadata\n dd.read_metadata = fake_read_metadata\n try:\n md = dd._read_metadata('/tmp/foo')\n finally:\n dd.read_metadata = orig_rm\n assert md['a'] == (1, 0)\n assert md['b'] == ('c', 5)\n", "method_code": "def _read_metadata(dd):\n \"\"\" Filter read metadata so that it always returns a tuple that includes\n some kind of timestamp. With 1.4.8 of the Swift integration the\n timestamps were not stored. Here we fabricate timestamps for volumes\n where the existing data has no timestamp (that is, stored data is not\n a tuple), allowing us a measure of backward compatibility.\n\n FIXME: At this time it does not appear that the timestamps on each\n metadata are used for much, so this should not hurt anything.\n \"\"\"\n metadata_i = read_metadata(dd)\n metadata = {}\n timestamp = 0\n for key, value in metadata_i.iteritems():\n if not isinstance(value, tuple):\n value = (value, timestamp)\n metadata[key] = value\n return metadata", "context": "def _read_metadata(dd): ...\ndef _read_metadata(dd): ...\ndef filter_prefix(objects, prefix): ...\ndef filter_delimiter(objects, delimiter, prefix, marker, path=None): ...\ndef filter_marker(objects, marker): ...\ndef filter_prefix_as_marker(objects, prefix): ...\ndef filter_end_marker(objects, end_marker): ...\n", "repository": "portante/gluster-swift", "test_name": "test__read_metadata", "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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000078.py"} {"focal_file": "gluster/swift/common/DiskDir.py", "focal_class": null, "focal_method": "filter_end_marker", "tests": "import unittest\n\nclass Test_filter_end_marker(unittest.TestCase):\n def test_filter_end_marker(self):\n in_objs, end_marker = ([], '')\n out_objs = dd.filter_end_marker(in_objs, end_marker)\n assert list(out_objs) == []\n in_objs, end_marker = ([], 'abc')\n out_objs = dd.filter_end_marker(in_objs, end_marker)\n assert list(out_objs) == []\n in_objs, end_marker = (['abc_123', 'abc_456', 'abc_789', 'def_101'], '')\n out_objs = dd.filter_end_marker(in_objs, end_marker)\n assert list(out_objs) == []\n in_objs, end_marker = (['abc_123', 'abc_456', 'abc_789', 'def_101'], 'ABC')\n out_objs = dd.filter_end_marker(in_objs, end_marker)\n assert list(out_objs) == []\n in_objs, end_marker = (['abc_123', 'abc_456', 'abc_789', 'def_101'], 'efg')\n out_objs = dd.filter_end_marker(in_objs, end_marker)\n assert list(out_objs) == ['abc_123', 'abc_456', 'abc_789', 'def_101']\n in_objs, end_marker = (['abc_123', 'def_101', 'abc_456', 'abc_789'], 'abc_789')\n out_objs = dd.filter_end_marker(in_objs, end_marker)\n assert list(out_objs) == ['abc_123']\n in_objs, end_marker = (['abc_123', 'abc_456', 'abc_789', 'def_101'], 'abc_789')\n out_objs = dd.filter_end_marker(in_objs, end_marker)\n assert list(out_objs) == ['abc_123', 'abc_456']\n in_objs, end_marker = (['abc_123', 'abc_456', 'abc_789', 'def_101'], 'abc_5')\n out_objs = dd.filter_end_marker(in_objs, end_marker)\n assert list(out_objs) == ['abc_123', 'abc_456']\n in_objs, end_marker = (['abc_123', 'abc_456', 'abc_789', 'def_101'], 'abc_123')\n out_objs = dd.filter_end_marker(in_objs, end_marker)\n assert list(out_objs) == []\n in_objs, end_marker = (['abc_123', 'abc_456', 'abc_789', 'def_101'], 'def_101')\n out_objs = dd.filter_end_marker(in_objs, end_marker)\n assert list(out_objs) == ['abc_123', 'abc_456', 'abc_789']\n", "method_code": "def filter_end_marker(objects, end_marker):\n \"\"\"\n Accept a list of strings, sorted, and return all the strings that are\n strictly less than the given end_marker string. We perform this as a\n generator to avoid creating potentially large intermediate object lists.\n \"\"\"\n for object_name in objects:\n if object_name < end_marker:\n yield object_name\n else:\n break", "context": "def filter_end_marker(objects, end_marker): ...\ndef _read_metadata(dd): ...\ndef filter_prefix(objects, prefix): ...\ndef filter_delimiter(objects, delimiter, prefix, marker, path=None): ...\ndef filter_marker(objects, marker): ...\ndef filter_prefix_as_marker(objects, prefix): ...\ndef filter_end_marker(objects, end_marker): ...\n", "repository": "portante/gluster-swift", "test_name": "test_filter_end_marker", "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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000079.py"} {"focal_file": "gluster/swift/common/DiskDir.py", "focal_class": null, "focal_method": "filter_marker", "tests": "import unittest\n\nclass Test_filter_marker(unittest.TestCase):\n def test_filter_marker(self):\n in_objs, marker = ([], '')\n out_objs = dd.filter_marker(in_objs, marker)\n assert list(out_objs) == []\n in_objs, marker = ([], 'abc')\n out_objs = dd.filter_marker(in_objs, marker)\n assert list(out_objs) == []\n in_objs, marker = (['abc_123', 'abc_456', 'abc_789', 'def_101'], '')\n out_objs = dd.filter_marker(in_objs, marker)\n assert list(out_objs) == in_objs\n in_objs, marker = (['abc_123', 'abc_456', 'abc_789', 'def_101'], 'ABC')\n out_objs = dd.filter_marker(in_objs, marker)\n assert list(out_objs) == in_objs\n in_objs, marker = (['abc_123', 'abc_456', 'abc_789', 'def_101'], 'efg')\n out_objs = dd.filter_marker(in_objs, marker)\n assert list(out_objs) == []\n in_objs, marker = (['abc_123', 'def_101', 'abc_456', 'abc_789'], 'abc_456')\n out_objs = dd.filter_marker(in_objs, marker)\n assert list(out_objs) == ['def_101', 'abc_789']\n in_objs, marker = (['abc_123', 'abc_456', 'abc_789', 'def_101'], 'abc_456')\n out_objs = dd.filter_marker(in_objs, marker)\n assert list(out_objs) == ['abc_789', 'def_101']\n in_objs, marker = (['abc_123', 'abc_456', 'abc_789', 'def_101'], 'abc_5')\n out_objs = dd.filter_marker(in_objs, marker)\n assert list(out_objs) == ['abc_789', 'def_101']\n in_objs, marker = (['abc_123', 'abc_456', 'abc_789', 'def_101'], 'abc_123')\n out_objs = dd.filter_marker(in_objs, marker)\n assert list(out_objs) == ['abc_456', 'abc_789', 'def_101']\n in_objs, marker = (['abc_123', 'abc_456', 'abc_789', 'def_101'], 'def_101')\n out_objs = dd.filter_marker(in_objs, marker)\n assert list(out_objs) == []\n", "method_code": "def filter_marker(objects, marker):\n \"\"\"\n Accept sorted list of strings, return all strings whose value is strictly\n greater than the given marker value.\n \"\"\"\n for object_name in objects:\n if object_name > marker:\n yield object_name", "context": "def filter_marker(objects, marker): ...\ndef _read_metadata(dd): ...\ndef filter_prefix(objects, prefix): ...\ndef filter_delimiter(objects, delimiter, prefix, marker, path=None): ...\ndef filter_marker(objects, marker): ...\ndef filter_prefix_as_marker(objects, prefix): ...\ndef filter_end_marker(objects, end_marker): ...\n", "repository": "portante/gluster-swift", "test_name": "test_filter_marker", "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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000080.py"} {"focal_file": "gluster/swift/common/DiskDir.py", "focal_class": null, "focal_method": "filter_prefix", "tests": "import unittest\n\nclass Test_filter_prefix(unittest.TestCase):\n def test_filter_prefix(self):\n in_objs, prefix = ([], '')\n out_objs = dd.filter_prefix(in_objs, prefix)\n assert list(out_objs) == []\n in_objs, prefix = ([], 'abc')\n out_objs = dd.filter_prefix(in_objs, prefix)\n assert list(out_objs) == []\n in_objs, prefix = (['abc_123', 'abc_456', 'abc_789', 'def_101'], '')\n out_objs = dd.filter_prefix(in_objs, prefix)\n assert list(out_objs) == in_objs\n in_objs, prefix = (['abc_123', 'abc_456', 'abc_789', 'def_101'], 'abc')\n out_objs = dd.filter_prefix(in_objs, prefix)\n assert list(out_objs) == ['abc_123', 'abc_456', 'abc_789']\n in_objs, prefix = (['ABC_123', 'ABC_456', 'abc_123', 'abc_456', 'abc_789', 'def_101'], 'abc')\n out_objs = dd.filter_prefix(in_objs, prefix)\n assert list(out_objs) == ['abc_123', 'abc_456', 'abc_789']\n in_objs, prefix = (['abc_123', 'def_101', 'abc_456', 'abc_789'], 'abc')\n out_objs = dd.filter_prefix(in_objs, prefix)\n assert list(out_objs) == ['abc_123']\n", "method_code": "def filter_prefix(objects, prefix):\n \"\"\"\n Accept a sorted list of strings, returning all strings starting with the\n given prefix.\n \"\"\"\n found = False\n for object_name in objects:\n if object_name.startswith(prefix):\n yield object_name\n found = True\n elif found:\n break", "context": "def filter_prefix(objects, prefix): ...\ndef _read_metadata(dd): ...\ndef filter_prefix(objects, prefix): ...\ndef filter_delimiter(objects, delimiter, prefix, marker, path=None): ...\ndef filter_marker(objects, marker): ...\ndef filter_prefix_as_marker(objects, prefix): ...\ndef filter_end_marker(objects, end_marker): ...\n", "repository": "portante/gluster-swift", "test_name": "test_filter_prefix", "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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000081.py"} {"focal_file": "gluster/swift/common/DiskDir.py", "focal_class": null, "focal_method": "filter_delimiter", "tests": "import unittest\n\nclass Test_filter_delimiter(unittest.TestCase):\n def test_filter_delimiter(self):\n in_objs, delimiter, prefix, marker = ([], None, '', '')\n try:\n out_objs = dd.filter_delimiter(in_objs, delimiter, prefix, marker)\n except AssertionError:\n pass\n except Exception:\n self.fail('Failed to raise assertion')\n in_objs, delimiter, prefix, marker = ([], '', '', '')\n try:\n out_objs = dd.filter_delimiter(in_objs, delimiter, prefix, marker)\n except AssertionError:\n pass\n except Exception:\n self.fail('Failed to raise assertion')\n in_objs, delimiter, prefix, marker = ([], str(255), '', '')\n try:\n out_objs = dd.filter_delimiter(in_objs, delimiter, prefix, marker)\n except AssertionError:\n pass\n except Exception:\n self.fail('Failed to raise assertion')\n in_objs, delimiter, prefix, marker = ([], '_', '', '')\n out_objs = dd.filter_delimiter(in_objs, delimiter, prefix, marker)\n assert list(out_objs) == []\n in_objs, delimiter, prefix, marker = (['abc_'], '_', '', '')\n out_objs = dd.filter_delimiter(in_objs, delimiter, prefix, marker)\n assert list(out_objs) == in_objs\n in_objs, delimiter, prefix, marker = (['abc_123', 'abc_456'], '_', '', '')\n out_objs = dd.filter_delimiter(in_objs, delimiter, prefix, marker)\n assert list(out_objs) == ['abc_']\n in_objs, delimiter, prefix, marker = (['abc_123', 'abc_456', 'def_123', 'def_456'], '_', '', '')\n out_objs = dd.filter_delimiter(in_objs, delimiter, prefix, marker)\n assert list(out_objs) == ['abc_', 'def_']\n in_objs, delimiter, prefix, marker = (['abc_123', 'abc_456', 'abc_789', 'def_101'], '_', 'abc_', '')\n out_objs = dd.filter_delimiter(in_objs, delimiter, prefix, marker)\n l = list(out_objs)\n assert l == ['abc_123', 'abc_456', 'abc_789'], repr(l)\n in_objs, delimiter, prefix, marker = (['abc_123_a', 'abc_456', 'abc_789_', 'def_101'], '_', 'abc_', '')\n out_objs = dd.filter_delimiter(in_objs, delimiter, prefix, marker)\n l = list(out_objs)\n assert l == ['abc_123_', 'abc_456', 'abc_789_'], repr(l)\n in_objs, delimiter, prefix, marker, path = (['abc_123_a', 'abc_456', 'abc_789_', 'def_101'], '_', 'abc_', '', '')\n out_objs = dd.filter_delimiter(in_objs, delimiter, prefix, marker, path)\n l = list(out_objs)\n assert l == ['abc_456', 'abc_789_'], repr(l)\n in_objs, delimiter, prefix, marker, path = (['abc/123', 'abc/456', 'def/123', 'def/456'], '/', 'abc/', '', '')\n out_objs = dd.filter_delimiter(in_objs, delimiter, prefix, marker, path)\n l = list(out_objs)\n assert l == ['abc/123', 'abc/456'], repr(l)\n", "method_code": "def filter_delimiter(objects, delimiter, prefix, marker, path=None):\n \"\"\"\n Accept a sorted list of strings, returning strings that:\n 1. begin with \"prefix\" (empty string matches all)\n 2. does not match the \"path\" argument\n 3. does not contain the delimiter in the given prefix length\n \"\"\"\n assert delimiter\n assert prefix is not None\n skip_name = None\n for object_name in objects:\n if prefix and (not object_name.startswith(prefix)):\n break\n if path is not None:\n if object_name == path:\n continue\n if skip_name:\n if object_name < skip_name:\n continue\n else:\n skip_name = None\n end = object_name.find(delimiter, len(prefix))\n if end >= 0 and len(object_name) > end + 1:\n skip_name = object_name[:end] + chr(ord(delimiter) + 1)\n continue\n else:\n if skip_name:\n if object_name < skip_name:\n continue\n else:\n skip_name = None\n end = object_name.find(delimiter, len(prefix))\n if end > 0:\n dir_name = object_name[:end + 1]\n if dir_name != marker:\n yield dir_name\n skip_name = object_name[:end] + chr(ord(delimiter) + 1)\n continue\n yield object_name", "context": "def filter_delimiter(objects, delimiter, prefix, marker, path=None): ...\ndef _read_metadata(dd): ...\ndef filter_prefix(objects, prefix): ...\ndef filter_delimiter(objects, delimiter, prefix, marker, path=None): ...\ndef filter_marker(objects, marker): ...\ndef filter_prefix_as_marker(objects, prefix): ...\ndef filter_end_marker(objects, end_marker): ...\n", "repository": "portante/gluster-swift", "test_name": "test_filter_delimiter", "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, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000082.py"} {"focal_file": "gluster/swift/common/DiskDir.py", "focal_class": null, "focal_method": "_dir_exists_read_metadata", "tests": "import unittest\n\nclass Test_dir_exists_read_metadata(unittest.TestCase):\n def test__dir_exists_read_metadata_exists(self):\n datadir = os.path.join(self.td, self.fake_drives[0])\n fake_md = {'fake': (True, 0)}\n fake_md_p = pickle.dumps(fake_md, utils.PICKLE_PROTOCOL)\n _setxattr(datadir, utils.METADATA_KEY, fake_md_p)\n dc = dd.DiskCommon(self.td, self.fake_drives[0], self.fake_accounts[0], self.fake_logger)\n dc._dir_exists_read_metadata()\n assert dc.metadata == fake_md, repr(dc.metadata)\n assert dc.db_file == dd._db_file\n assert dc.pending_timeout == 10\n assert dc.stale_reads_ok is False\n assert dc.root == self.td\n assert dc.logger == self.fake_logger\n assert dc.account == self.fake_accounts[0]\n assert dc.datadir == datadir\n assert dc._dir_exists is True\n\n def test__dir_exists_read_metadata_does_not_exist(self):\n dc = dd.DiskCommon(self.td, 'dne0', 'dne0', self.fake_logger)\n dc._dir_exists_read_metadata()\n assert dc.metadata == {}\n assert dc.db_file == dd._db_file\n assert dc.pending_timeout == 10\n assert dc.stale_reads_ok is False\n assert dc.root == self.td\n assert dc.logger == self.fake_logger\n assert dc.account == 'dne0'\n assert dc.datadir == os.path.join(self.td, 'dne0')\n assert dc._dir_exists is False\n", "method_code": " def _dir_exists_read_metadata(self):\n self._dir_exists = os_path.exists(self.datadir)\n if self._dir_exists:\n self.metadata = _read_metadata(self.datadir)\n return self._dir_exists\n ", "context": "class DiskCommon(object):\n def _dir_exists_read_metadata(self): ...\n def __init__(self, root, drive, account, logger, pending_timeout=None, stale_reads_ok=False): ...\n def is_deleted(self): ...\n def empty(self): ...\n def update_metadata(self, metadata): ...\n\n self.db_file = _db_file\n self.metadata = {}\n self.pending_timeout = pending_timeout or 10\n self.stale_reads_ok = stale_reads_ok\n self.root = root\n self.logger = logger\n self.account = account\n self.datadir = os.path.join(root, drive)\n self._dir_exists = None\n", "repository": "portante/gluster-swift", "test_name": "test__dir_exists_read_metadata_exists", "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_000083.py"} {"focal_file": "gluster/swift/common/DiskDir.py", "focal_class": null, "focal_method": "is_deleted", "tests": "import unittest\n\nclass Test_is_deleted(unittest.TestCase):\n def test_is_deleted(self):\n dc = dd.DiskCommon(self.td, self.fake_drives[0], self.fake_accounts[0], self.fake_logger)\n assert dc.is_deleted() == False\n", "method_code": " def is_deleted(self):\n return not os_path.exists(self.datadir)\n ", "context": "class DiskCommon(object):\n def is_deleted(self): ...\n def __init__(self, root, drive, account, logger, pending_timeout=None, stale_reads_ok=False): ...\n def _dir_exists_read_metadata(self): ...\n def empty(self): ...\n def update_metadata(self, metadata): ...\n\n self.db_file = _db_file\n self.metadata = {}\n self.pending_timeout = pending_timeout or 10\n self.stale_reads_ok = stale_reads_ok\n self.root = root\n self.logger = logger\n self.account = account\n self.datadir = os.path.join(root, drive)\n self._dir_exists = None\n", "repository": "portante/gluster-swift", "test_name": "test_is_deleted", "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_000084.py"} {"focal_file": "gluster/swift/common/DiskDir.py", "focal_class": null, "focal_method": "update_metadata", "tests": "import unittest\n\nclass Test_update_metadata(unittest.TestCase):\n def test_update_metadata(self):\n dc = dd.DiskCommon(self.td, self.fake_drives[0], self.fake_accounts[0], self.fake_logger)\n utils.create_container_metadata(dc.datadir)\n dc.metadata = dd._read_metadata(dc.datadir)\n md_copy = dc.metadata.copy()\n\n def _mock_write_metadata(path, md):\n self.fail('write_metadata should not have been called')\n orig_wm = dd.write_metadata\n dd.write_metadata = _mock_write_metadata\n try:\n dc.update_metadata({})\n assert dc.metadata == md_copy\n dc.update_metadata(md_copy)\n assert dc.metadata == md_copy\n finally:\n dd.write_metadata = orig_wm\n dc.update_metadata({'X-Container-Meta-foo': '42'})\n assert 'X-Container-Meta-foo' in dc.metadata\n assert dc.metadata['X-Container-Meta-foo'] == '42'\n md = pickle.loads(_getxattr(dc.datadir, utils.METADATA_KEY))\n assert dc.metadata == md, '%r != %r' % (dc.metadata, md)\n del dc.metadata['X-Container-Meta-foo']\n assert dc.metadata == md_copy\n\n def test_metadata(self):\n broker = self._get_broker(account='a', container='c')\n broker.initialize(self.initial_ts)\n first_timestamp = normalize_timestamp(1)\n first_value = '1'\n broker.update_metadata({'First': [first_value, first_timestamp]})\n self.assert_('First' in broker.metadata)\n self.assertEquals(broker.metadata['First'], [first_value, first_timestamp])\n second_timestamp = normalize_timestamp(2)\n second_value = '2'\n broker.update_metadata({'Second': [second_value, second_timestamp]})\n self.assert_('First' in broker.metadata)\n self.assertEquals(broker.metadata['First'], [first_value, first_timestamp])\n self.assert_('Second' in broker.metadata)\n self.assertEquals(broker.metadata['Second'], [second_value, second_timestamp])\n first_timestamp = normalize_timestamp(3)\n first_value = '1b'\n broker.update_metadata({'First': [first_value, first_timestamp]})\n self.assert_('First' in broker.metadata)\n self.assertEquals(broker.metadata['First'], [first_value, first_timestamp])\n self.assert_('Second' in broker.metadata)\n self.assertEquals(broker.metadata['Second'], [second_value, second_timestamp])\n second_timestamp = normalize_timestamp(4)\n second_value = ''\n broker.update_metadata({'Second': [second_value, second_timestamp]})\n self.assert_('First' in broker.metadata)\n self.assertEquals(broker.metadata['First'], [first_value, first_timestamp])\n self.assert_('Second' in broker.metadata)\n self.assertEquals(broker.metadata['Second'], [second_value, second_timestamp])\n", "method_code": " def update_metadata(self, metadata):\n assert self.metadata, 'Valid container/account metadata should have been created by now'\n if metadata:\n new_metadata = self.metadata.copy()\n new_metadata.update(metadata)\n if new_metadata != self.metadata:\n write_metadata(self.datadir, new_metadata)\n self.metadata = new_metadata\n ", "context": "class DiskCommon(object):\n def update_metadata(self, metadata): ...\n def __init__(self, root, drive, account, logger, pending_timeout=None, stale_reads_ok=False): ...\n def _dir_exists_read_metadata(self): ...\n def is_deleted(self): ...\n def empty(self): ...\n\n self.db_file = _db_file\n self.metadata = {}\n self.pending_timeout = pending_timeout or 10\n self.stale_reads_ok = stale_reads_ok\n self.root = root\n self.logger = logger\n self.account = account\n self.datadir = os.path.join(root, drive)\n self._dir_exists = None\n", "repository": "portante/gluster-swift", "test_name": "test_update_metadata", "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, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000085.py"} {"focal_file": "gluster/swift/common/DiskDir.py", "focal_class": null, "focal_method": "empty", "tests": "import unittest\n\nclass Test_empty(unittest.TestCase):\n def test_empty_dir_is_not_empty(self):\n dc = dd.DiskCommon(self.td, self.fake_drives[0], self.fake_accounts[0], self.fake_logger)\n os.makedirs(os.path.join(self.td, self.fake_drives[0], 'aaabbbccc'))\n self.assertFalse(dc.empty())\n\n def test_empty_dir_is_empty(self):\n dc = dd.DiskCommon(self.td, self.fake_drives[0], self.fake_accounts[0], self.fake_logger)\n self.assertTrue(dc.empty())\n\n def test_empty(self):\n broker = self._get_broker(account='a')\n broker.initialize(self.initial_ts)\n self.assert_(broker.empty())\n c1 = self._create_container('c1')\n self.assert_(not broker.empty())\n os.rmdir(c1)\n self.assert_(broker.empty())\n", "method_code": " def empty(self):\n try:\n return dir_empty(self.datadir)\n except FileOrDirNotFoundError:\n return True\n ", "context": "class DiskCommon(object):\n def empty(self): ...\n def __init__(self, root, drive, account, logger, pending_timeout=None, stale_reads_ok=False): ...\n def _dir_exists_read_metadata(self): ...\n def is_deleted(self): ...\n def update_metadata(self, metadata): ...\n\n self.db_file = _db_file\n self.metadata = {}\n self.pending_timeout = pending_timeout or 10\n self.stale_reads_ok = stale_reads_ok\n self.root = root\n self.logger = logger\n self.account = account\n self.datadir = os.path.join(root, drive)\n self._dir_exists = None\n", "repository": "portante/gluster-swift", "test_name": "test_empty_dir_is_not_empty", "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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000086.py"} {"focal_file": "gluster/swift/common/DiskDir.py", "focal_class": null, "focal_method": "put_object", "tests": "import unittest\n\nclass Test_put_object(unittest.TestCase):\n def test_put_object(self):\n broker = self._get_broker(account='a', container='c')\n broker.initialize(self.initial_ts)\n self.assert_(broker.empty())\n broker.put_object('o', normalize_timestamp(time()), 0, 'text/plain', 'd41d8cd98f00b204e9800998ecf8427e')\n self.assert_(broker.empty())\n", "method_code": " def put_object(self, name, timestamp, size, content_type, etag, deleted=0):\n pass\n ", "context": "class DiskDir(DiskCommon):\n def put_object(self, name, timestamp, size, content_type, etag, deleted=0): ...\n def __init__(self, path, drive, account, container, logger, uid=DEFAULT_UID, gid=DEFAULT_GID, **kwargs): ...\n def list_objects_iter(self, limit, marker, end_marker, prefix, delimiter, path=None): ...\n def _update_object_count(self): ...\n def get_info(self): ...\n def initialize(self, timestamp): ...\n def update_put_timestamp(self, timestamp): ...\n def delete_object(self, name, timestamp): ...\n def delete_db(self, timestamp): ...\n def set_x_container_sync_points(self, sync_point1, sync_point2): ...\n\n self.uid = int(uid)\n self.gid = int(gid)\n self.container = container\n self.datadir = os.path.join(self.datadir, self.container)\n", "repository": "portante/gluster-swift", "test_name": "test_put_object", "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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000087.py"} {"focal_file": "gluster/swift/common/DiskDir.py", "focal_class": null, "focal_method": "delete_object", "tests": "import unittest\n\nclass Test_delete_object(unittest.TestCase):\n def test_delete_object(self):\n broker = self._get_broker(account='a', container='c')\n broker.initialize(self.initial_ts)\n self.assert_(broker.empty())\n obj = self._create_file('o.txt')\n self.assert_(not broker.empty())\n broker.delete_object('o', normalize_timestamp(time()))\n self.assert_(not broker.empty())\n os.unlink(obj)\n self.assert_(broker.empty())\n", "method_code": " def delete_object(self, name, timestamp):\n return\n ", "context": "class DiskDir(DiskCommon):\n def delete_object(self, name, timestamp): ...\n def __init__(self, path, drive, account, container, logger, uid=DEFAULT_UID, gid=DEFAULT_GID, **kwargs): ...\n def list_objects_iter(self, limit, marker, end_marker, prefix, delimiter, path=None): ...\n def _update_object_count(self): ...\n def get_info(self): ...\n def put_object(self, name, timestamp, size, content_type, etag, deleted=0): ...\n def initialize(self, timestamp): ...\n def update_put_timestamp(self, timestamp): ...\n def delete_db(self, timestamp): ...\n def set_x_container_sync_points(self, sync_point1, sync_point2): ...\n\n self.uid = int(uid)\n self.gid = int(gid)\n self.container = container\n self.datadir = os.path.join(self.datadir, self.container)\n", "repository": "portante/gluster-swift", "test_name": "test_delete_object", "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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000088.py"} {"focal_file": "gluster/swift/common/DiskDir.py", "focal_class": null, "focal_method": "get_info", "tests": "import unittest\n\nclass Test_get_info(unittest.TestCase):\n def test_get_info(self):\n tf = tarfile.open('common/data/account_tree.tar.bz2', 'r:bz2')\n orig_cwd = os.getcwd()\n os.chdir(os.path.join(self.td, self.fake_drives[0]))\n try:\n tf.extractall()\n finally:\n os.chdir(orig_cwd)\n da = dd.DiskAccount(self.td, self.fake_drives[0], self.fake_accounts[0], self.fake_logger)\n data = da.get_info()\n assert set(data.keys()) == self.get_info_keys\n assert data['account'] == self.fake_accounts[0]\n assert data['created_at'] == '1'\n assert data['put_timestamp'] == '1'\n assert data['delete_timestamp'] == '1'\n assert data['container_count'] == 3\n assert data['object_count'] == 0\n assert data['bytes_used'] == 0\n assert data['hash'] == ''\n assert data['id'] == ''\n\n def test_get_info_empty(self):\n da = dd.DiskAccount(self.td, self.fake_drives[0], self.fake_accounts[0], self.fake_logger)\n data = da.get_info()\n assert set(data.keys()) == self.get_info_keys\n assert data['account'] == self.fake_accounts[0]\n assert data['created_at'] == '1'\n assert data['put_timestamp'] == '1'\n assert data['delete_timestamp'] == '1'\n assert data['container_count'] == 0\n assert data['object_count'] == 0\n assert data['bytes_used'] == 0\n assert data['hash'] == ''\n assert data['id'] == ''\n", "method_code": " def get_info(self):\n \"\"\"\n Get global data for the container.\n :returns: dict with keys: account, container, object_count, bytes_used,\n hash, id, created_at, put_timestamp, delete_timestamp,\n reported_put_timestamp, reported_delete_timestamp,\n reported_object_count, and reported_bytes_used.\n \"\"\"\n if self._dir_exists and Glusterfs._container_update_object_count:\n self._update_object_count()\n data = {'account': self.account, 'container': self.container, 'object_count': self.metadata.get(X_OBJECTS_COUNT, ('0', 0))[0], 'bytes_used': self.metadata.get(X_BYTES_USED, ('0', 0))[0], 'hash': '', 'id': '', 'created_at': '1', 'put_timestamp': self.metadata.get(X_PUT_TIMESTAMP, ('0', 0))[0], 'delete_timestamp': '1', 'reported_put_timestamp': '1', 'reported_delete_timestamp': '1', 'reported_object_count': '1', 'reported_bytes_used': '1', 'x_container_sync_point1': self.metadata.get('x_container_sync_point1', -1), 'x_container_sync_point2': self.metadata.get('x_container_sync_point2', -1)}\n return data\n ", "context": "class DiskDir(DiskCommon):\n def get_info(self): ...\n def __init__(self, path, drive, account, container, logger, uid=DEFAULT_UID, gid=DEFAULT_GID, **kwargs): ...\n def list_objects_iter(self, limit, marker, end_marker, prefix, delimiter, path=None): ...\n def _update_object_count(self): ...\n def put_object(self, name, timestamp, size, content_type, etag, deleted=0): ...\n def initialize(self, timestamp): ...\n def update_put_timestamp(self, timestamp): ...\n def delete_object(self, name, timestamp): ...\n def delete_db(self, timestamp): ...\n def set_x_container_sync_points(self, sync_point1, sync_point2): ...\n\n self.uid = int(uid)\n self.gid = int(gid)\n self.container = container\n self.datadir = os.path.join(self.datadir, self.container)\n", "repository": "portante/gluster-swift", "test_name": "test_get_info", "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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000089.py"} {"focal_file": "gluster/swift/common/DiskDir.py", "focal_class": null, "focal_method": "list_objects_iter", "tests": "import unittest\n\nclass Test_list_objects_iter(unittest.TestCase):\n def test_list_objects_iter(self):\n broker = self._get_broker(account='a', container='c')\n broker.initialize(self.initial_ts)\n for obj1 in xrange(4):\n for obj2 in xrange(125):\n self._create_file('%d.d/%04d' % (obj1, obj2))\n for obj in xrange(125):\n self._create_file('2.d/0051.d/%04d' % obj)\n for obj in xrange(125):\n self._create_file('3.d/%04d.d/0049' % obj)\n listing = broker.list_objects_iter(100, '', None, None, '')\n self.assertEquals(len(listing), 100)\n self.assertEquals(listing[0][0], '0.d/0000')\n self.assertEquals(listing[-1][0], '0.d/0099')\n listing = broker.list_objects_iter(100, '', '0.d/0050', None, '')\n self.assertEquals(len(listing), 50)\n self.assertEquals(listing[0][0], '0.d/0000')\n self.assertEquals(listing[-1][0], '0.d/0049')\n listing = broker.list_objects_iter(100, '0.d/0099', None, None, '')\n self.assertEquals(len(listing), 100)\n self.assertEquals(listing[0][0], '0.d/0100')\n self.assertEquals(listing[-1][0], '1.d/0074')\n listing = broker.list_objects_iter(55, '1.d/0074', None, None, '')\n self.assertEquals(len(listing), 55)\n self.assertEquals(listing[0][0], '1.d/0075')\n self.assertEquals(listing[-1][0], '2.d/0004')\n listing = broker.list_objects_iter(10, '', None, '0.d/01', '')\n self.assertEquals(len(listing), 10)\n self.assertEquals(listing[0][0], '0.d/0100')\n self.assertEquals(listing[-1][0], '0.d/0109')\n listing = broker.list_objects_iter(10, '', None, '0.d/', '/')\n self.assertEquals(len(listing), 10)\n self.assertEquals(listing[0][0], '0.d/0000')\n self.assertEquals(listing[-1][0], '0.d/0009')\n listing = broker.list_objects_iter(10, '', None, None, '', '0.d')\n self.assertEquals(len(listing), 10)\n self.assertEquals(listing[0][0], '0.d/0000')\n self.assertEquals(listing[-1][0], '0.d/0009')\n listing = broker.list_objects_iter(10, '', None, '', '/')\n self.assertEquals(len(listing), 0)\n listing = broker.list_objects_iter(10, '2', None, None, '/')\n self.assertEquals(len(listing), 0)\n listing = broker.list_objects_iter(10, '2.d/', None, None, '/')\n self.assertEquals(len(listing), 0)\n listing = broker.list_objects_iter(10, '2.d/0050', None, '2.d/', '/')\n self.assertEquals(len(listing), 10)\n self.assertEquals(listing[0][0], '2.d/0051')\n self.assertEquals(listing[1][0], '2.d/0052')\n self.assertEquals(listing[-1][0], '2.d/0060')\n listing = broker.list_objects_iter(10, '3.d/0045', None, '3.d/', '/')\n self.assertEquals(len(listing), 10)\n self.assertEquals([row[0] for row in listing], ['3.d/0046', '3.d/0047', '3.d/0048', '3.d/0049', '3.d/0050', '3.d/0051', '3.d/0052', '3.d/0053', '3.d/0054', '3.d/0055'])\n listing = broker.list_objects_iter(10, '3.d/0048', None, '3.d/', '/')\n self.assertEquals(len(listing), 10)\n self.assertEquals([row[0] for row in listing], ['3.d/0049', '3.d/0050', '3.d/0051', '3.d/0052', '3.d/0053', '3.d/0054', '3.d/0055', '3.d/0056', '3.d/0057', '3.d/0058'])\n listing = broker.list_objects_iter(10, None, None, '3.d/0049.d/', '/')\n self.assertEquals(len(listing), 1)\n self.assertEquals([row[0] for row in listing], ['3.d/0049.d/0049'])\n listing = broker.list_objects_iter(10, None, None, None, None, '3.d/0049.d')\n self.assertEquals(len(listing), 1)\n self.assertEquals([row[0] for row in listing], ['3.d/0049.d/0049'])\n listing = broker.list_objects_iter(2, None, None, '3.d/', '/')\n self.assertEquals(len(listing), 2)\n self.assertEquals([row[0] for row in listing], ['3.d/0000', '3.d/0001'])\n listing = broker.list_objects_iter(2, None, None, None, None, '3.d')\n self.assertEquals(len(listing), 2)\n self.assertEquals([row[0] for row in listing], ['3.d/0000', '3.d/0001'])\n\n def test_list_objects_iter_non_slash(self):\n broker = self._get_broker(account='a', container='c')\n broker.initialize(self.initial_ts)\n for obj1 in xrange(4):\n for obj2 in xrange(125):\n self._create_file('%d:%04d' % (obj1, obj2))\n for obj in xrange(125):\n self._create_file('2:0051:%04d' % obj)\n for obj in xrange(125):\n self._create_file('3:%04d:0049' % obj)\n listing = broker.list_objects_iter(100, '', None, None, '')\n self.assertEquals(len(listing), 100)\n self.assertEquals(listing[0][0], '0:0000')\n self.assertEquals(listing[-1][0], '0:0099')\n listing = broker.list_objects_iter(100, '', '0:0050', None, '')\n self.assertEquals(len(listing), 50)\n self.assertEquals(listing[0][0], '0:0000')\n self.assertEquals(listing[-1][0], '0:0049')\n listing = broker.list_objects_iter(100, '0:0099', None, None, '')\n self.assertEquals(len(listing), 100)\n self.assertEquals(listing[0][0], '0:0100')\n self.assertEquals(listing[-1][0], '1:0074')\n listing = broker.list_objects_iter(55, '1:0074', None, None, '')\n self.assertEquals(len(listing), 55)\n self.assertEquals(listing[0][0], '1:0075')\n self.assertEquals(listing[-1][0], '2:0004')\n listing = broker.list_objects_iter(10, '', None, '0:01', '')\n self.assertEquals(len(listing), 10)\n self.assertEquals(listing[0][0], '0:0100')\n self.assertEquals(listing[-1][0], '0:0109')\n listing = broker.list_objects_iter(10, '', None, '0:', ':')\n self.assertEquals(len(listing), 10)\n self.assertEquals(listing[0][0], '0:0000')\n self.assertEquals(listing[-1][0], '0:0009')\n listing = broker.list_objects_iter(10, '', None, None, '', '0')\n self.assertEquals(len(listing), 0)\n listing = broker.list_objects_iter(10, '', None, '', ':')\n self.assertEquals(len(listing), 4)\n self.assertEquals([row[0] for row in listing], ['0:', '1:', '2:', '3:'])\n listing = broker.list_objects_iter(10, '2', None, None, ':')\n self.assertEquals(len(listing), 2)\n self.assertEquals([row[0] for row in listing], ['2:', '3:'])\n listing = broker.list_objects_iter(10, '2:', None, None, ':')\n self.assertEquals(len(listing), 1)\n self.assertEquals([row[0] for row in listing], ['3:'])\n listing = broker.list_objects_iter(10, '2:0050', None, '2:', ':')\n self.assertEquals(len(listing), 10)\n self.assertEquals(listing[0][0], '2:0051')\n self.assertEquals(listing[1][0], '2:0051:')\n self.assertEquals(listing[2][0], '2:0052')\n self.assertEquals(listing[-1][0], '2:0059')\n listing = broker.list_objects_iter(10, '3:0045', None, '3:', ':')\n self.assertEquals(len(listing), 10)\n self.assertEquals([row[0] for row in listing], ['3:0045:', '3:0046', '3:0046:', '3:0047', '3:0047:', '3:0048', '3:0048:', '3:0049', '3:0049:', '3:0050'])\n self._create_file('3:0049:')\n listing = broker.list_objects_iter(10, '3:0048', None, None, None)\n self.assertEquals(len(listing), 10)\n self.assertEquals([row[0] for row in listing], ['3:0048:0049', '3:0049', '3:0049:', '3:0049:0049', '3:0050', '3:0050:0049', '3:0051', '3:0051:0049', '3:0052', '3:0052:0049'])\n listing = broker.list_objects_iter(10, '3:0048', None, '3:', ':')\n self.assertEquals(len(listing), 10)\n self.assertEquals([row[0] for row in listing], ['3:0048:', '3:0049', '3:0049:', '3:0050', '3:0050:', '3:0051', '3:0051:', '3:0052', '3:0052:', '3:0053'])\n listing = broker.list_objects_iter(10, None, None, '3:0049:', ':')\n self.assertEquals(len(listing), 2)\n self.assertEquals([row[0] for row in listing], ['3:0049:', '3:0049:0049'])\n listing = broker.list_objects_iter(10, None, None, None, None, '3:0049')\n self.assertEquals(len(listing), 0)\n listing = broker.list_objects_iter(2, None, None, '3:', ':')\n self.assertEquals(len(listing), 2)\n self.assertEquals([row[0] for row in listing], ['3:0000', '3:0000:'])\n listing = broker.list_objects_iter(2, None, None, None, None, '3')\n self.assertEquals(len(listing), 0)\n\n def test_list_objects_iter_prefix_delim(self):\n broker = self._get_broker(account='a', container='c')\n broker.initialize(self.initial_ts)\n os.mkdir(os.path.join(self.container, 'pets'))\n os.mkdir(os.path.join(self.container, 'pets', 'dogs'))\n obj1 = os.path.join(self.container, 'pets', 'dogs', '1')\n with open(obj1, 'w') as fp:\n fp.write('one\\n')\n obj2 = os.path.join(self.container, 'pets', 'dogs', '2')\n with open(obj2, 'w') as fp:\n fp.write('two\\n')\n os.mkdir(os.path.join(self.container, 'pets', 'fish'))\n obja = os.path.join(self.container, 'pets', 'fish', 'a')\n with open(obja, 'w') as fp:\n fp.write('A\\n')\n objb = os.path.join(self.container, 'pets', 'fish', 'b')\n with open(objb, 'w') as fp:\n fp.write('B\\n')\n objf = os.path.join(self.container, 'pets', 'fish_info.txt')\n with open(objf, 'w') as fp:\n fp.write('one fish\\n')\n objs = os.path.join(self.container, 'snakes')\n with open(objs, 'w') as fp:\n fp.write('slither\\n')\n listing = broker.list_objects_iter(100, None, None, 'pets/f', '/')\n self.assertEquals([row[0] for row in listing], ['pets/fish_info.txt'])\n listing = broker.list_objects_iter(100, None, None, 'pets/fish', '/')\n self.assertEquals([row[0] for row in listing], ['pets/fish_info.txt'])\n listing = broker.list_objects_iter(100, None, None, 'pets/fish/', '/')\n self.assertEquals([row[0] for row in listing], ['pets/fish/a', 'pets/fish/b'])\n", "method_code": " def list_objects_iter(self, limit, marker, end_marker, prefix, delimiter, path=None):\n \"\"\"\n Returns tuple of name, created_at, size, content_type, etag.\n \"\"\"\n assert limit >= 0\n assert not delimiter or (len(delimiter) == 1 and ord(delimiter) <= 254)\n if path is not None:\n if path:\n prefix = path = path.rstrip('/') + '/'\n else:\n prefix = path\n delimiter = '/'\n elif delimiter and (not prefix):\n prefix = ''\n container_list = []\n objects = self._update_object_count()\n if objects:\n objects.sort()\n else:\n return container_list\n if end_marker:\n objects = filter_end_marker(objects, end_marker)\n if marker and marker >= prefix:\n objects = filter_marker(objects, marker)\n elif prefix:\n objects = filter_prefix_as_marker(objects, prefix)\n if prefix is None:\n pass\n elif not delimiter:\n if not prefix:\n pass\n else:\n objects = filter_prefix(objects, prefix)\n else:\n objects = filter_delimiter(objects, delimiter, prefix, marker, path)\n count = 0\n for obj in objects:\n obj_path = os.path.join(self.datadir, obj)\n metadata = read_metadata(obj_path)\n if not metadata or not validate_object(metadata):\n if delimiter == '/' and obj_path[-1] == delimiter:\n clean_obj_path = obj_path[:-1]\n else:\n clean_obj_path = obj_path\n try:\n metadata = create_object_metadata(clean_obj_path)\n except OSError as e:\n if e.errno != errno.ENOENT:\n raise\n if not Glusterfs._implicit_dir_objects and metadata and (metadata[X_CONTENT_TYPE] == DIR_TYPE) and (not dir_is_object(metadata)):\n continue\n list_item = []\n list_item.append(obj)\n if metadata:\n list_item.append(metadata[X_TIMESTAMP])\n list_item.append(int(metadata[X_CONTENT_LENGTH]))\n list_item.append(metadata[X_CONTENT_TYPE])\n list_item.append(metadata[X_ETAG])\n container_list.append(list_item)\n count += 1\n if count >= limit:\n break\n return container_list\n ", "context": "class DiskDir(DiskCommon):\n def list_objects_iter(self, limit, marker, end_marker, prefix, delimiter, path=None): ...\n def __init__(self, path, drive, account, container, logger, uid=DEFAULT_UID, gid=DEFAULT_GID, **kwargs): ...\n def _update_object_count(self): ...\n def get_info(self): ...\n def put_object(self, name, timestamp, size, content_type, etag, deleted=0): ...\n def initialize(self, timestamp): ...\n def update_put_timestamp(self, timestamp): ...\n def delete_object(self, name, timestamp): ...\n def delete_db(self, timestamp): ...\n def set_x_container_sync_points(self, sync_point1, sync_point2): ...\n\n self.uid = int(uid)\n self.gid = int(gid)\n self.container = container\n self.datadir = os.path.join(self.datadir, self.container)\n", "repository": "portante/gluster-swift", "test_name": "test_list_objects_iter", "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, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000090.py"} {"focal_file": "gluster/swift/common/DiskDir.py", "focal_class": null, "focal_method": "delete_db", "tests": "import unittest\n\nclass Test_delete_db(unittest.TestCase):\n def test_delete_db(self):\n da = dd.DiskAccount(self.td, self.fake_drives[0], self.fake_accounts[0], self.fake_logger)\n assert da._dir_exists == True\n da.delete_db('12345')\n assert da._dir_exists == True\n", "method_code": " def delete_db(self, timestamp):\n \"\"\"\n Delete the container (directory) if empty.\n \n :param timestamp: delete timestamp\n \"\"\"\n rmobjdir(self.datadir)\n ", "context": "class DiskDir(DiskCommon):\n def delete_db(self, timestamp): ...\n def __init__(self, path, drive, account, container, logger, uid=DEFAULT_UID, gid=DEFAULT_GID, **kwargs): ...\n def list_objects_iter(self, limit, marker, end_marker, prefix, delimiter, path=None): ...\n def _update_object_count(self): ...\n def get_info(self): ...\n def put_object(self, name, timestamp, size, content_type, etag, deleted=0): ...\n def initialize(self, timestamp): ...\n def update_put_timestamp(self, timestamp): ...\n def delete_object(self, name, timestamp): ...\n def set_x_container_sync_points(self, sync_point1, sync_point2): ...\n\n self.uid = int(uid)\n self.gid = int(gid)\n self.container = container\n self.datadir = os.path.join(self.datadir, self.container)\n", "repository": "portante/gluster-swift", "test_name": "test_delete_db", "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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000091.py"} {"focal_file": "gluster/swift/common/DiskDir.py", "focal_class": null, "focal_method": "put_container", "tests": "import unittest\n\nclass Test_put_container(unittest.TestCase):\n def test_put_container(self):\n broker = self._get_broker(account='a')\n broker.initialize(self.initial_ts)\n self.assert_(broker.empty())\n broker.put_container('c1', normalize_timestamp(time()), 0, 0, 0)\n self.assert_(broker.empty())\n\n def test_put_container_for_deletes(self):\n broker = self._get_broker(account='a')\n broker.initialize(self.initial_ts)\n self.assert_(broker.empty())\n c1 = self._create_container('c1')\n self.assert_(not broker.empty())\n broker.put_container('c1', 0, normalize_timestamp(time()), 0, 0)\n self.assert_(not broker.empty())\n os.rmdir(c1)\n self.assert_(broker.empty())\n", "method_code": " def put_container(self, container, put_timestamp, del_timestamp, object_count, bytes_used):\n \"\"\"\n Create a container with the given attributes.\n \n :param name: name of the container to create\n :param put_timestamp: put_timestamp of the container to create\n :param delete_timestamp: delete_timestamp of the container to create\n :param object_count: number of objects in the container\n :param bytes_used: number of bytes used by the container\n \"\"\"\n return\n ", "context": "class DiskAccount(DiskCommon):\n def put_container(self, container, put_timestamp, del_timestamp, object_count, bytes_used): ...\n def __init__(self, root, drive, account, logger, **kwargs): ...\n def is_status_deleted(self): ...\n def initialize(self, timestamp): ...\n def update_put_timestamp(self, timestamp): ...\n def delete_db(self, timestamp): ...\n def _update_container_count(self): ...\n def list_containers_iter(self, limit, marker, end_marker, prefix, delimiter): ...\n def get_info(self): ...\n", "repository": "portante/gluster-swift", "test_name": "test_put_container", "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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000092.py"} {"focal_file": "gluster/swift/common/DiskDir.py", "focal_class": null, "focal_method": "list_containers_iter", "tests": "import unittest\n\nclass Test_list_containers_iter(unittest.TestCase):\n def test_list_containers_iter(self):\n broker = self._get_broker(account='a')\n broker.initialize(self.initial_ts)\n for cont1 in xrange(4):\n for cont2 in xrange(125):\n self._create_container('%d-%04d' % (cont1, cont2))\n for cont in xrange(125):\n self._create_container('2-0051-%04d' % cont)\n for cont in xrange(125):\n self._create_container('3-%04d-0049' % cont)\n listing = broker.list_containers_iter(100, '', None, None, '')\n self.assertEquals(len(listing), 100)\n self.assertEquals(listing[0][0], '0-0000')\n self.assertEquals(listing[-1][0], '0-0099')\n listing = broker.list_containers_iter(100, '', '0-0050', None, '')\n self.assertEquals(len(listing), 50)\n self.assertEquals(listing[0][0], '0-0000')\n self.assertEquals(listing[-1][0], '0-0049')\n listing = broker.list_containers_iter(100, '0-0099', None, None, '')\n self.assertEquals(len(listing), 100)\n self.assertEquals(listing[0][0], '0-0100')\n self.assertEquals(listing[-1][0], '1-0074')\n listing = broker.list_containers_iter(55, '1-0074', None, None, '')\n self.assertEquals(len(listing), 55)\n self.assertEquals(listing[0][0], '1-0075')\n self.assertEquals(listing[-1][0], '2-0004')\n listing = broker.list_containers_iter(10, '', None, '0-01', '')\n self.assertEquals(len(listing), 10)\n self.assertEquals(listing[0][0], '0-0100')\n self.assertEquals(listing[-1][0], '0-0109')\n listing = broker.list_containers_iter(10, '', None, '0-01', '-')\n self.assertEquals(len(listing), 10)\n self.assertEquals(listing[0][0], '0-0100')\n self.assertEquals(listing[-1][0], '0-0109')\n listing = broker.list_containers_iter(10, '', None, '0-', '-')\n self.assertEquals(len(listing), 10)\n self.assertEquals(listing[0][0], '0-0000')\n self.assertEquals(listing[-1][0], '0-0009')\n listing = broker.list_containers_iter(10, '', None, '', '-')\n self.assertEquals(len(listing), 4)\n self.assertEquals([row[0] for row in listing], ['0-', '1-', '2-', '3-'])\n listing = broker.list_containers_iter(10, '2-', None, None, '-')\n self.assertEquals(len(listing), 1)\n self.assertEquals([row[0] for row in listing], ['3-'])\n listing = broker.list_containers_iter(10, '', None, '2', '-')\n self.assertEquals(len(listing), 1)\n self.assertEquals([row[0] for row in listing], ['2-'])\n listing = broker.list_containers_iter(10, '2-0050', None, '2-', '-')\n self.assertEquals(len(listing), 10)\n self.assertEquals(listing[0][0], '2-0051')\n self.assertEquals(listing[1][0], '2-0051-')\n self.assertEquals(listing[2][0], '2-0052')\n self.assertEquals(listing[-1][0], '2-0059')\n listing = broker.list_containers_iter(10, '3-0045', None, '3-', '-')\n self.assertEquals(len(listing), 10)\n self.assertEquals([row[0] for row in listing], ['3-0045-', '3-0046', '3-0046-', '3-0047', '3-0047-', '3-0048', '3-0048-', '3-0049', '3-0049-', '3-0050'])\n self._create_container('3-0049-')\n listing = broker.list_containers_iter(10, '3-0048', None, None, None)\n self.assertEquals(len(listing), 10)\n self.assertEquals([row[0] for row in listing], ['3-0048-0049', '3-0049', '3-0049-', '3-0049-0049', '3-0050', '3-0050-0049', '3-0051', '3-0051-0049', '3-0052', '3-0052-0049'])\n listing = broker.list_containers_iter(10, '3-0048', None, '3-', '-')\n self.assertEquals(len(listing), 10)\n self.assertEquals([row[0] for row in listing], ['3-0048-', '3-0049', '3-0049-', '3-0050', '3-0050-', '3-0051', '3-0051-', '3-0052', '3-0052-', '3-0053'])\n listing = broker.list_containers_iter(10, None, None, '3-0049-', '-')\n self.assertEquals(len(listing), 2)\n self.assertEquals([row[0] for row in listing], ['3-0049-', '3-0049-0049'])\n", "method_code": " def list_containers_iter(self, limit, marker, end_marker, prefix, delimiter):\n \"\"\"\n Return tuple of name, object_count, bytes_used, 0(is_subdir).\n Used by account server.\n \"\"\"\n if delimiter and (not prefix):\n prefix = ''\n account_list = []\n containers = self._update_container_count()\n if containers:\n containers.sort()\n else:\n return account_list\n if containers and end_marker:\n containers = filter_end_marker(containers, end_marker)\n if containers:\n if marker and marker >= prefix:\n containers = filter_marker(containers, marker)\n elif prefix:\n containers = filter_prefix_as_marker(containers, prefix)\n if prefix is None:\n pass\n elif not delimiter:\n if not prefix:\n pass\n else:\n containers = filter_prefix(containers, prefix)\n else:\n containers = filter_delimiter(containers, delimiter, prefix, marker)\n count = 0\n for cont in containers:\n list_item = []\n metadata = None\n list_item.append(cont)\n cont_path = os.path.join(self.datadir, cont)\n metadata = _read_metadata(cont_path)\n if not metadata or not validate_container(metadata):\n try:\n metadata = create_container_metadata(cont_path)\n except OSError as e:\n if e.errno != errno.ENOENT:\n raise\n if metadata:\n list_item.append(metadata[X_OBJECTS_COUNT][0])\n list_item.append(metadata[X_BYTES_USED][0])\n list_item.append(0)\n account_list.append(list_item)\n count += 1\n if count >= limit:\n break\n return account_list\n ", "context": "class DiskAccount(DiskCommon):\n def list_containers_iter(self, limit, marker, end_marker, prefix, delimiter): ...\n def __init__(self, root, drive, account, logger, **kwargs): ...\n def is_status_deleted(self): ...\n def initialize(self, timestamp): ...\n def update_put_timestamp(self, timestamp): ...\n def delete_db(self, timestamp): ...\n def put_container(self, container, put_timestamp, del_timestamp, object_count, bytes_used): ...\n def _update_container_count(self): ...\n def get_info(self): ...\n", "repository": "portante/gluster-swift", "test_name": "test_list_containers_iter", "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, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000093.py"} {"focal_file": "gluster/swift/common/DiskDir.py", "focal_class": null, "focal_method": "update_put_timestamp", "tests": "import unittest\n\nclass Test_update_put_timestamp(unittest.TestCase):\n def test_update_put_timestamp_not_updated(self):\n da = dd.DiskAccount(self.td, self.fake_drives[0], self.fake_accounts[0], self.fake_logger)\n da.update_put_timestamp('12345')\n assert da.metadata['X-PUT-Timestamp'][0] != '12345', repr(da.metadata)\n\n def test_update_put_timestamp_updated(self):\n da = dd.DiskAccount(self.td, self.fake_drives[0], self.fake_accounts[0], self.fake_logger)\n exp_pts = str(float(da.metadata['X-PUT-Timestamp'][0]) + 100)\n da.update_put_timestamp(exp_pts)\n assert da.metadata['X-PUT-Timestamp'][0] == exp_pts, repr(da.metadata)\n", "method_code": " def update_put_timestamp(self, timestamp):\n \"\"\"\n Update the PUT timestamp for the container.\n \n If the container does not exist, create it using a PUT timestamp of\n the given value.\n \n If the container does exist, update the PUT timestamp only if it is\n later than the existing value.\n \"\"\"\n if not os_path.exists(self.datadir):\n self.initialize(timestamp)\n elif timestamp > self.metadata[X_PUT_TIMESTAMP]:\n self.metadata[X_PUT_TIMESTAMP] = (timestamp, 0)\n write_metadata(self.datadir, self.metadata)\n ", "context": "class DiskDir(DiskCommon):\n def update_put_timestamp(self, timestamp): ...\n def __init__(self, path, drive, account, container, logger, uid=DEFAULT_UID, gid=DEFAULT_GID, **kwargs): ...\n def list_objects_iter(self, limit, marker, end_marker, prefix, delimiter, path=None): ...\n def _update_object_count(self): ...\n def get_info(self): ...\n def put_object(self, name, timestamp, size, content_type, etag, deleted=0): ...\n def initialize(self, timestamp): ...\n def delete_object(self, name, timestamp): ...\n def delete_db(self, timestamp): ...\n def set_x_container_sync_points(self, sync_point1, sync_point2): ...\n\n self.uid = int(uid)\n self.gid = int(gid)\n self.container = container\n self.datadir = os.path.join(self.datadir, self.container)\n", "repository": "portante/gluster-swift", "test_name": "test_update_put_timestamp_not_updated", "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_000094.py"} {"focal_file": "gluster/swift/common/DiskDir.py", "focal_class": null, "focal_method": "is_status_deleted", "tests": "import unittest\n\nclass Test_is_status_deleted(unittest.TestCase):\n def test_is_status_deleted(self):\n da = dd.DiskAccount(self.td, self.fake_drives[0], self.fake_accounts[0], self.fake_logger)\n assert da.is_status_deleted() == False\n", "method_code": " def is_status_deleted(self):\n \"\"\"\n Only returns true if the status field is set to DELETED.\n \"\"\"\n return False\n ", "context": "class DiskAccount(DiskCommon):\n def is_status_deleted(self): ...\n def __init__(self, root, drive, account, logger, **kwargs): ...\n def initialize(self, timestamp): ...\n def update_put_timestamp(self, timestamp): ...\n def delete_db(self, timestamp): ...\n def put_container(self, container, put_timestamp, del_timestamp, object_count, bytes_used): ...\n def _update_container_count(self): ...\n def list_containers_iter(self, limit, marker, end_marker, prefix, delimiter): ...\n def get_info(self): ...\n", "repository": "portante/gluster-swift", "test_name": "test_is_status_deleted", "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_000095.py"} {"focal_file": "gluster/swift/common/fs_utils.py", "focal_class": null, "focal_method": "do_walk", "tests": "import unittest\n\nclass Test_do_walk(unittest.TestCase):\n def test_do_walk(self):\n tmpparent = mkdtemp()\n try:\n tmpdirs = []\n tmpfiles = []\n for i in range(5):\n tmpdirs.append(mkdtemp(dir=tmpparent).rsplit(os.path.sep, 1)[1])\n tmpfiles.append(mkstemp(dir=tmpparent)[1].rsplit(os.path.sep, 1)[1])\n for path, dirnames, filenames in fs.do_walk(tmpparent):\n assert path == tmpparent\n assert dirnames.sort() == tmpdirs.sort()\n assert filenames.sort() == tmpfiles.sort()\n break\n finally:\n shutil.rmtree(tmpparent)\n", "method_code": "def do_walk(*args, **kwargs):\n return os.walk(*args, **kwargs)", "context": "def do_walk(*args, **kwargs): ...\ndef do_walk(*args, **kwargs): ...\ndef do_write(fd, buf): ...\ndef do_read(fd, n): ...\ndef do_ismount(path): ...\ndef do_mkdir(path): ...\ndef do_listdir(path): ...\ndef dir_empty(path): ...\ndef do_rmdir(path): ...\ndef do_chown(path, uid, gid): ...\ndef do_fchown(fd, uid, gid): ...\ndef do_stat(path): ...\ndef do_fstat(fd): ...\ndef do_open(path, flags, **kwargs): ...\ndef do_close(fd): ...\ndef do_unlink(path, log=True): ...\ndef do_rename(old_path, new_path): ...\ndef do_fsync(fd): ...\ndef do_fdatasync(fd): ...\ndef do_fadvise64(fd, offset, length): ...\ndef do_lseek(fd, pos, how): ...\ndef mkdirs(path): ...\n", "repository": "portante/gluster-swift", "test_name": "test_do_walk", "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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000096.py"} {"focal_file": "gluster/swift/common/fs_utils.py", "focal_class": null, "focal_method": "do_ismount", "tests": "import unittest\n\nclass Test_do_ismount(unittest.TestCase):\n def test_do_ismount_path_not_mount(self):\n tmpdir = mkdtemp()\n try:\n assert False == fs.do_ismount(tmpdir)\n finally:\n shutil.rmtree(tmpdir)\n\n def test_do_ismount_path_error(self):\n\n def _mock_os_lstat(path):\n raise OSError(13, 'foo')\n tmpdir = mkdtemp()\n try:\n with patch('os.lstat', _mock_os_lstat):\n try:\n fs.do_ismount(tmpdir)\n except GlusterFileSystemOSError as err:\n pass\n else:\n self.fail('Expected GlusterFileSystemOSError')\n finally:\n shutil.rmtree(tmpdir)\n\n def test_do_ismount_path_is_root(self):\n assert True == fs.do_ismount('/')\n\n def test_do_ismount_successes_dev(self):\n _os_lstat = os.lstat\n\n class MockStat(object):\n\n def __init__(self, mode, dev, ino):\n self.st_mode = mode\n self.st_dev = dev\n self.st_ino = ino\n\n def _mock_os_lstat(path):\n if path.endswith('..'):\n parent = _os_lstat(path)\n return MockStat(parent.st_mode, parent.st_dev + 1, parent.st_ino)\n else:\n return _os_lstat(path)\n tmpdir = mkdtemp()\n try:\n with patch('os.lstat', _mock_os_lstat):\n try:\n fs.do_ismount(tmpdir)\n except GlusterFileSystemOSError as err:\n self.fail('Unexpected exception')\n else:\n pass\n finally:\n shutil.rmtree(tmpdir)\n\n def test_do_ismount_successes_ino(self):\n _os_lstat = os.lstat\n\n class MockStat(object):\n\n def __init__(self, mode, dev, ino):\n self.st_mode = mode\n self.st_dev = dev\n self.st_ino = ino\n\n def _mock_os_lstat(path):\n if path.endswith('..'):\n return _os_lstat(path)\n else:\n parent_path = os.path.join(path, '..')\n child = _os_lstat(path)\n parent = _os_lstat(parent_path)\n return MockStat(child.st_mode, parent.st_ino, child.st_dev)\n tmpdir = mkdtemp()\n try:\n with patch('os.lstat', _mock_os_lstat):\n try:\n fs.do_ismount(tmpdir)\n except GlusterFileSystemOSError as err:\n self.fail('Unexpected exception')\n else:\n pass\n finally:\n shutil.rmtree(tmpdir)\n", "method_code": "def do_ismount(path):\n \"\"\"\n Test whether a path is a mount point.\n\n This is code hijacked from C Python 2.6.8, adapted to remove the extra\n lstat() system call.\n \"\"\"\n try:\n s1 = os.lstat(path)\n except os.error as err:\n if err.errno == errno.ENOENT:\n return False\n else:\n raise GlusterFileSystemOSError(err.errno, '%s, os.lstat(\"%s\")' % (err.strerror, path))\n if stat.S_ISLNK(s1.st_mode):\n return False\n try:\n s2 = os.lstat(os.path.join(path, '..'))\n except os.error as err:\n raise GlusterFileSystemOSError(err.errno, '%s, os.lstat(\"%s\")' % (err.strerror, os.path.join(path, '..')))\n dev1 = s1.st_dev\n dev2 = s2.st_dev\n if dev1 != dev2:\n return True\n ino1 = s1.st_ino\n ino2 = s2.st_ino\n if ino1 == ino2:\n return True\n return False", "context": "def do_ismount(path): ...\ndef do_walk(*args, **kwargs): ...\ndef do_write(fd, buf): ...\ndef do_read(fd, n): ...\ndef do_ismount(path): ...\ndef do_mkdir(path): ...\ndef do_listdir(path): ...\ndef dir_empty(path): ...\ndef do_rmdir(path): ...\ndef do_chown(path, uid, gid): ...\ndef do_fchown(fd, uid, gid): ...\ndef do_stat(path): ...\ndef do_fstat(fd): ...\ndef do_open(path, flags, **kwargs): ...\ndef do_close(fd): ...\ndef do_unlink(path, log=True): ...\ndef do_rename(old_path, new_path): ...\ndef do_fsync(fd): ...\ndef do_fdatasync(fd): ...\ndef do_fadvise64(fd, offset, length): ...\ndef do_lseek(fd, pos, how): ...\ndef mkdirs(path): ...\n", "repository": "portante/gluster-swift", "test_name": "test_do_ismount_path_not_mount", "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, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000097.py"} {"focal_file": "gluster/swift/common/fs_utils.py", "focal_class": null, "focal_method": "do_open", "tests": "import unittest\n\nclass Test_do_open(unittest.TestCase):\n def test_do_open(self):\n _fd, tmpfile = mkstemp()\n try:\n fd = fs.do_open(tmpfile, os.O_RDONLY)\n try:\n os.write(fd, 'test')\n except OSError as err:\n pass\n else:\n self.fail('OSError expected')\n finally:\n os.close(fd)\n finally:\n os.close(_fd)\n os.remove(tmpfile)\n", "method_code": "def do_open(path, flags, **kwargs):\n try:\n fd = os.open(path, flags, **kwargs)\n except OSError as err:\n raise GlusterFileSystemOSError(err.errno, '%s, os.open(\"%s\", %x, %r)' % (err.strerror, path, flags, kwargs))\n return fd", "context": "def do_open(path, flags, **kwargs): ...\ndef do_walk(*args, **kwargs): ...\ndef do_write(fd, buf): ...\ndef do_read(fd, n): ...\ndef do_ismount(path): ...\ndef do_mkdir(path): ...\ndef do_listdir(path): ...\ndef dir_empty(path): ...\ndef do_rmdir(path): ...\ndef do_chown(path, uid, gid): ...\ndef do_fchown(fd, uid, gid): ...\ndef do_stat(path): ...\ndef do_fstat(fd): ...\ndef do_open(path, flags, **kwargs): ...\ndef do_close(fd): ...\ndef do_unlink(path, log=True): ...\ndef do_rename(old_path, new_path): ...\ndef do_fsync(fd): ...\ndef do_fdatasync(fd): ...\ndef do_fadvise64(fd, offset, length): ...\ndef do_lseek(fd, pos, how): ...\ndef mkdirs(path): ...\n", "repository": "portante/gluster-swift", "test_name": "test_do_open", "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_000098.py"} {"focal_file": "gluster/swift/common/fs_utils.py", "focal_class": null, "focal_method": "do_write", "tests": "import unittest\n\nclass Test_do_write(unittest.TestCase):\n def test_do_write(self):\n fd, tmpfile = mkstemp()\n try:\n cnt = fs.do_write(fd, 'test')\n assert cnt == len('test')\n finally:\n os.close(fd)\n os.remove(tmpfile)\n\n def test_do_write_err(self):\n fd, tmpfile = mkstemp()\n try:\n fd1 = os.open(tmpfile, os.O_RDONLY)\n try:\n fs.do_write(fd1, 'test')\n except GlusterFileSystemOSError:\n pass\n else:\n self.fail('GlusterFileSystemOSError expected')\n finally:\n os.close(fd1)\n except GlusterFileSystemOSError as ose:\n self.fail('Open failed with %s' % ose.strerror)\n finally:\n os.close(fd)\n os.remove(tmpfile)\n", "method_code": "def do_write(fd, buf):\n try:\n cnt = os.write(fd, buf)\n except OSError as err:\n raise GlusterFileSystemOSError(err.errno, '%s, os.write(\"%s\", ...)' % (err.strerror, fd))\n return cnt", "context": "def do_write(fd, buf): ...\ndef do_walk(*args, **kwargs): ...\ndef do_write(fd, buf): ...\ndef do_read(fd, n): ...\ndef do_ismount(path): ...\ndef do_mkdir(path): ...\ndef do_listdir(path): ...\ndef dir_empty(path): ...\ndef do_rmdir(path): ...\ndef do_chown(path, uid, gid): ...\ndef do_fchown(fd, uid, gid): ...\ndef do_stat(path): ...\ndef do_fstat(fd): ...\ndef do_open(path, flags, **kwargs): ...\ndef do_close(fd): ...\ndef do_unlink(path, log=True): ...\ndef do_rename(old_path, new_path): ...\ndef do_fsync(fd): ...\ndef do_fdatasync(fd): ...\ndef do_fadvise64(fd, offset, length): ...\ndef do_lseek(fd, pos, how): ...\ndef mkdirs(path): ...\n", "repository": "portante/gluster-swift", "test_name": "test_do_write", "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, 1, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000099.py"} {"focal_file": "gluster/swift/common/fs_utils.py", "focal_class": null, "focal_method": "mkdirs", "tests": "import unittest\n\nclass Test_mkdirs(unittest.TestCase):\n def test_mkdirs(self):\n tmpdir = mkdtemp()\n try:\n fs.mkdirs(os.path.join(tmpdir, 'a', 'b', 'c'))\n except OSError:\n self.fail('Unexpected exception')\n else:\n pass\n finally:\n shutil.rmtree(tmpdir)\n", "method_code": "def mkdirs(path):\n \"\"\"\n Ensures the path is a directory or makes it if not. Errors if the path\n exists but is a file or on permissions failure.\n\n :param path: path to create\n \"\"\"\n try:\n os.makedirs(path)\n except OSError as err:\n if err.errno == errno.EEXIST and os.path.isdir(path):\n return\n raise GlusterFileSystemOSError(err.errno, '%s, os.makedirs(\"%s\")' % (err.strerror, path))", "context": "def mkdirs(path): ...\ndef do_walk(*args, **kwargs): ...\ndef do_write(fd, buf): ...\ndef do_read(fd, n): ...\ndef do_ismount(path): ...\ndef do_mkdir(path): ...\ndef do_listdir(path): ...\ndef dir_empty(path): ...\ndef do_rmdir(path): ...\ndef do_chown(path, uid, gid): ...\ndef do_fchown(fd, uid, gid): ...\ndef do_stat(path): ...\ndef do_fstat(fd): ...\ndef do_open(path, flags, **kwargs): ...\ndef do_close(fd): ...\ndef do_unlink(path, log=True): ...\ndef do_rename(old_path, new_path): ...\ndef do_fsync(fd): ...\ndef do_fdatasync(fd): ...\ndef do_fadvise64(fd, offset, length): ...\ndef do_lseek(fd, pos, how): ...\ndef mkdirs(path): ...\n", "repository": "portante/gluster-swift", "test_name": "test_mkdirs", "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_000100.py"} {"focal_file": "gluster/swift/common/fs_utils.py", "focal_class": null, "focal_method": "do_mkdir", "tests": "import unittest\n\nclass Test_do_mkdir(unittest.TestCase):\n def test_do_mkdir(self):\n try:\n path = os.path.join('/tmp', str(random.random()))\n fs.do_mkdir(path)\n assert os.path.exists(path)\n assert fs.do_mkdir(path) is None\n finally:\n os.rmdir(path)\n\n def test_do_mkdir_err(self):\n try:\n path = os.path.join('/tmp', str(random.random()), str(random.random()))\n fs.do_mkdir(path)\n except GlusterFileSystemOSError:\n pass\n else:\n self.fail('GlusterFileSystemOSError expected')\n", "method_code": "def do_mkdir(path):\n try:\n os.mkdir(path)\n except OSError as err:\n if err.errno == errno.EEXIST:\n logging.warn('fs_utils: os.mkdir - path %s already exists', path)\n else:\n raise GlusterFileSystemOSError(err.errno, '%s, os.mkdir(\"%s\")' % (err.strerror, path))", "context": "def do_mkdir(path): ...\ndef do_walk(*args, **kwargs): ...\ndef do_write(fd, buf): ...\ndef do_read(fd, n): ...\ndef do_ismount(path): ...\ndef do_mkdir(path): ...\ndef do_listdir(path): ...\ndef dir_empty(path): ...\ndef do_rmdir(path): ...\ndef do_chown(path, uid, gid): ...\ndef do_fchown(fd, uid, gid): ...\ndef do_stat(path): ...\ndef do_fstat(fd): ...\ndef do_open(path, flags, **kwargs): ...\ndef do_close(fd): ...\ndef do_unlink(path, log=True): ...\ndef do_rename(old_path, new_path): ...\ndef do_fsync(fd): ...\ndef do_fdatasync(fd): ...\ndef do_fadvise64(fd, offset, length): ...\ndef do_lseek(fd, pos, how): ...\ndef mkdirs(path): ...\n", "repository": "portante/gluster-swift", "test_name": "test_do_mkdir", "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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000101.py"} {"focal_file": "gluster/swift/common/fs_utils.py", "focal_class": null, "focal_method": "do_listdir", "tests": "import unittest\n\nclass Test_do_listdir(unittest.TestCase):\n def test_do_listdir(self):\n tmpdir = mkdtemp()\n try:\n subdir = []\n for i in range(5):\n subdir.append(mkdtemp(dir=tmpdir).rsplit(os.path.sep, 1)[1])\n assert subdir.sort() == fs.do_listdir(tmpdir).sort()\n finally:\n shutil.rmtree(tmpdir)\n\n def test_do_listdir_err(self):\n try:\n path = os.path.join('/tmp', str(random.random()))\n fs.do_listdir(path)\n except GlusterFileSystemOSError:\n pass\n else:\n self.fail('GlusterFileSystemOSError expected')\n", "method_code": "def do_listdir(path):\n try:\n buf = os.listdir(path)\n except OSError as err:\n raise GlusterFileSystemOSError(err.errno, '%s, os.listdir(\"%s\")' % (err.strerror, path))\n return buf", "context": "def do_listdir(path): ...\ndef do_walk(*args, **kwargs): ...\ndef do_write(fd, buf): ...\ndef do_read(fd, n): ...\ndef do_ismount(path): ...\ndef do_mkdir(path): ...\ndef do_listdir(path): ...\ndef dir_empty(path): ...\ndef do_rmdir(path): ...\ndef do_chown(path, uid, gid): ...\ndef do_fchown(fd, uid, gid): ...\ndef do_stat(path): ...\ndef do_fstat(fd): ...\ndef do_open(path, flags, **kwargs): ...\ndef do_close(fd): ...\ndef do_unlink(path, log=True): ...\ndef do_rename(old_path, new_path): ...\ndef do_fsync(fd): ...\ndef do_fdatasync(fd): ...\ndef do_fadvise64(fd, offset, length): ...\ndef do_lseek(fd, pos, how): ...\ndef mkdirs(path): ...\n", "repository": "portante/gluster-swift", "test_name": "test_do_listdir", "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, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000102.py"} {"focal_file": "gluster/swift/common/fs_utils.py", "focal_class": null, "focal_method": "do_fstat", "tests": "import unittest\n\nclass Test_do_fstat(unittest.TestCase):\n def test_do_fstat(self):\n tmpdir = mkdtemp()\n try:\n fd, tmpfile = mkstemp(dir=tmpdir)\n buf1 = os.stat(tmpfile)\n buf2 = fs.do_fstat(fd)\n assert buf1 == buf2\n finally:\n os.close(fd)\n os.remove(tmpfile)\n os.rmdir(tmpdir)\n\n def test_do_fstat_err(self):\n try:\n fs.do_fstat(1000)\n except GlusterFileSystemOSError:\n pass\n else:\n self.fail('Expected GlusterFileSystemOSError')\n", "method_code": "def do_fstat(fd):\n try:\n stats = os.fstat(fd)\n except OSError as err:\n raise GlusterFileSystemOSError(err.errno, '%s, os.fstat(%s)' % (err.strerror, fd))\n return stats", "context": "def do_fstat(fd): ...\ndef do_walk(*args, **kwargs): ...\ndef do_write(fd, buf): ...\ndef do_read(fd, n): ...\ndef do_ismount(path): ...\ndef do_mkdir(path): ...\ndef do_listdir(path): ...\ndef dir_empty(path): ...\ndef do_rmdir(path): ...\ndef do_chown(path, uid, gid): ...\ndef do_fchown(fd, uid, gid): ...\ndef do_stat(path): ...\ndef do_fstat(fd): ...\ndef do_open(path, flags, **kwargs): ...\ndef do_close(fd): ...\ndef do_unlink(path, log=True): ...\ndef do_rename(old_path, new_path): ...\ndef do_fsync(fd): ...\ndef do_fdatasync(fd): ...\ndef do_fadvise64(fd, offset, length): ...\ndef do_lseek(fd, pos, how): ...\ndef mkdirs(path): ...\n", "repository": "portante/gluster-swift", "test_name": "test_do_fstat", "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, 1, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000103.py"} {"focal_file": "gluster/swift/common/fs_utils.py", "focal_class": null, "focal_method": "do_stat", "tests": "import unittest\n\nclass Test_do_stat(unittest.TestCase):\n def test_do_stat(self):\n tmpdir = mkdtemp()\n try:\n fd, tmpfile = mkstemp(dir=tmpdir)\n buf1 = os.stat(tmpfile)\n buf2 = fs.do_stat(tmpfile)\n assert buf1 == buf2\n finally:\n os.close(fd)\n os.remove(tmpfile)\n os.rmdir(tmpdir)\n\n def test_do_stat_enoent(self):\n res = fs.do_stat(os.path.join('/tmp', str(random.random())))\n assert res is None\n\n def test_do_stat_err(self):\n\n def mock_os_stat_eacces(path):\n raise OSError(errno.EACCES, os.strerror(errno.EACCES))\n try:\n with patch('os.stat', mock_os_stat_eacces):\n fs.do_stat('/tmp')\n except GlusterFileSystemOSError:\n pass\n else:\n self.fail('GlusterFileSystemOSError expected')\n\n def test_do_stat_eio_once(self):\n count = [0]\n _os_stat = os.stat\n\n def mock_os_stat_eio(path):\n count[0] += 1\n if count[0] <= 1:\n raise OSError(errno.EIO, os.strerror(errno.EIO))\n return _os_stat(path)\n with patch('os.stat', mock_os_stat_eio):\n fs.do_stat('/tmp') is not None\n\n def test_do_stat_eio_ten(self):\n\n def mock_os_stat_eio(path):\n raise OSError(errno.EIO, os.strerror(errno.EIO))\n try:\n with patch('os.stat', mock_os_stat_eio):\n fs.do_stat('/tmp')\n except GlusterFileSystemOSError:\n pass\n else:\n self.fail('GlusterFileSystemOSError expected')\n", "method_code": "def do_stat(path):\n serr = None\n for i in range(0, _STAT_ATTEMPTS):\n try:\n stats = os.stat(path)\n except OSError as err:\n if err.errno == errno.EIO:\n serr = err\n sleep(random.uniform(0.001, 0.005))\n continue\n if err.errno == errno.ENOENT:\n stats = None\n else:\n raise GlusterFileSystemOSError(err.errno, '%s, os.stat(\"%s\")[%d attempts]' % (err.strerror, path, i))\n if i > 0:\n logging.warn(\"fs_utils.do_stat(): os.stat('%s') retried %d times (%s)\", path, i, 'success' if stats else 'failure')\n return stats\n else:\n raise GlusterFileSystemOSError(serr.errno, '%s, os.stat(\"%s\")[%d attempts]' % (serr.strerror, path, _STAT_ATTEMPTS))", "context": "def do_stat(path): ...\ndef do_walk(*args, **kwargs): ...\ndef do_write(fd, buf): ...\ndef do_read(fd, n): ...\ndef do_ismount(path): ...\ndef do_mkdir(path): ...\ndef do_listdir(path): ...\ndef dir_empty(path): ...\ndef do_rmdir(path): ...\ndef do_chown(path, uid, gid): ...\ndef do_fchown(fd, uid, gid): ...\ndef do_stat(path): ...\ndef do_fstat(fd): ...\ndef do_open(path, flags, **kwargs): ...\ndef do_close(fd): ...\ndef do_unlink(path, log=True): ...\ndef do_rename(old_path, new_path): ...\ndef do_fsync(fd): ...\ndef do_fdatasync(fd): ...\ndef do_fadvise64(fd, offset, length): ...\ndef do_lseek(fd, pos, how): ...\ndef mkdirs(path): ...\n", "repository": "portante/gluster-swift", "test_name": "test_do_stat", "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, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000104.py"} {"focal_file": "gluster/swift/common/fs_utils.py", "focal_class": null, "focal_method": "do_close", "tests": "import unittest\n\nclass Test_do_close(unittest.TestCase):\n def test_do_close(self):\n fd, tmpfile = mkstemp()\n try:\n fs.do_close(fd)\n try:\n os.write(fd, 'test')\n except OSError:\n pass\n else:\n self.fail('OSError expected')\n finally:\n os.remove(tmpfile)\n\n def test_do_close_err_fd(self):\n fd, tmpfile = mkstemp()\n try:\n fs.do_close(fd)\n try:\n fs.do_close(fd)\n except GlusterFileSystemOSError:\n pass\n else:\n self.fail('GlusterFileSystemOSError expected')\n finally:\n os.remove(tmpfile)\n", "method_code": "def do_close(fd):\n try:\n os.close(fd)\n except OSError as err:\n raise GlusterFileSystemOSError(err.errno, '%s, os.close(%s)' % (err.strerror, fd))", "context": "def do_close(fd): ...\ndef do_walk(*args, **kwargs): ...\ndef do_write(fd, buf): ...\ndef do_read(fd, n): ...\ndef do_ismount(path): ...\ndef do_mkdir(path): ...\ndef do_listdir(path): ...\ndef dir_empty(path): ...\ndef do_rmdir(path): ...\ndef do_chown(path, uid, gid): ...\ndef do_fchown(fd, uid, gid): ...\ndef do_stat(path): ...\ndef do_fstat(fd): ...\ndef do_open(path, flags, **kwargs): ...\ndef do_close(fd): ...\ndef do_unlink(path, log=True): ...\ndef do_rename(old_path, new_path): ...\ndef do_fsync(fd): ...\ndef do_fdatasync(fd): ...\ndef do_fadvise64(fd, offset, length): ...\ndef do_lseek(fd, pos, how): ...\ndef mkdirs(path): ...\n", "repository": "portante/gluster-swift", "test_name": "test_do_close", "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_000105.py"} {"focal_file": "gluster/swift/common/fs_utils.py", "focal_class": null, "focal_method": "do_unlink", "tests": "import unittest\n\nclass Test_do_unlink(unittest.TestCase):\n def test_do_unlink(self):\n fd, tmpfile = mkstemp()\n try:\n assert fs.do_unlink(tmpfile) is None\n assert not os.path.exists(tmpfile)\n res = fs.do_unlink(os.path.join('/tmp', str(random.random())))\n assert res is None\n finally:\n os.close(fd)\n\n def test_do_unlink_err(self):\n tmpdir = mkdtemp()\n try:\n fs.do_unlink(tmpdir)\n except GlusterFileSystemOSError:\n pass\n else:\n self.fail('GlusterFileSystemOSError expected')\n finally:\n os.rmdir(tmpdir)\n", "method_code": "def do_unlink(path, log=True):\n try:\n os.unlink(path)\n except OSError as err:\n if err.errno != errno.ENOENT:\n raise GlusterFileSystemOSError(err.errno, '%s, os.unlink(\"%s\")' % (err.strerror, path))\n elif log:\n logging.warn('fs_utils: os.unlink failed on non-existent path: %s', path)", "context": "def do_unlink(path, log=True): ...\ndef do_walk(*args, **kwargs): ...\ndef do_write(fd, buf): ...\ndef do_read(fd, n): ...\ndef do_ismount(path): ...\ndef do_mkdir(path): ...\ndef do_listdir(path): ...\ndef dir_empty(path): ...\ndef do_rmdir(path): ...\ndef do_chown(path, uid, gid): ...\ndef do_fchown(fd, uid, gid): ...\ndef do_stat(path): ...\ndef do_fstat(fd): ...\ndef do_open(path, flags, **kwargs): ...\ndef do_close(fd): ...\ndef do_unlink(path, log=True): ...\ndef do_rename(old_path, new_path): ...\ndef do_fsync(fd): ...\ndef do_fdatasync(fd): ...\ndef do_fadvise64(fd, offset, length): ...\ndef do_lseek(fd, pos, how): ...\ndef mkdirs(path): ...\n", "repository": "portante/gluster-swift", "test_name": "test_do_unlink", "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, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000106.py"} {"focal_file": "gluster/swift/common/fs_utils.py", "focal_class": null, "focal_method": "do_rename", "tests": "import unittest\n\nclass Test_do_rename(unittest.TestCase):\n def test_do_rename(self):\n srcpath = mkdtemp()\n try:\n destpath = os.path.join('/tmp', str(random.random()))\n fs.do_rename(srcpath, destpath)\n assert not os.path.exists(srcpath)\n assert os.path.exists(destpath)\n finally:\n os.rmdir(destpath)\n\n def test_do_rename_err(self):\n try:\n srcpath = os.path.join('/tmp', str(random.random()))\n destpath = os.path.join('/tmp', str(random.random()))\n fs.do_rename(srcpath, destpath)\n except GlusterFileSystemOSError:\n pass\n else:\n self.fail('GlusterFileSystemOSError expected')\n", "method_code": "def do_rename(old_path, new_path):\n try:\n os.rename(old_path, new_path)\n except OSError as err:\n raise GlusterFileSystemOSError(err.errno, '%s, os.rename(\"%s\", \"%s\")' % (err.strerror, old_path, new_path))", "context": "def do_rename(old_path, new_path): ...\ndef do_walk(*args, **kwargs): ...\ndef do_write(fd, buf): ...\ndef do_read(fd, n): ...\ndef do_ismount(path): ...\ndef do_mkdir(path): ...\ndef do_listdir(path): ...\ndef dir_empty(path): ...\ndef do_rmdir(path): ...\ndef do_chown(path, uid, gid): ...\ndef do_fchown(fd, uid, gid): ...\ndef do_stat(path): ...\ndef do_fstat(fd): ...\ndef do_open(path, flags, **kwargs): ...\ndef do_close(fd): ...\ndef do_unlink(path, log=True): ...\ndef do_rename(old_path, new_path): ...\ndef do_fsync(fd): ...\ndef do_fdatasync(fd): ...\ndef do_fadvise64(fd, offset, length): ...\ndef do_lseek(fd, pos, how): ...\ndef mkdirs(path): ...\n", "repository": "portante/gluster-swift", "test_name": "test_do_rename", "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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000107.py"} {"focal_file": "gluster/swift/common/fs_utils.py", "focal_class": null, "focal_method": "dir_empty", "tests": "import unittest\n\nclass Test_dir_empty(unittest.TestCase):\n def test_dir_empty(self):\n tmpdir = mkdtemp()\n try:\n subdir = mkdtemp(dir=tmpdir)\n assert not fs.dir_empty(tmpdir)\n assert fs.dir_empty(subdir)\n finally:\n shutil.rmtree(tmpdir)\n\n def test_dir_empty_err(self):\n\n def _mock_os_listdir(path):\n raise OSError(13, 'foo')\n with patch('os.listdir', _mock_os_listdir):\n try:\n fs.dir_empty('/tmp')\n except GlusterFileSystemOSError:\n pass\n else:\n self.fail('GlusterFileSystemOSError exception expected')\n\n def test_dir_empty_notfound(self):\n try:\n assert fs.dir_empty(os.path.join('/tmp', str(random.random())))\n except FileOrDirNotFoundError:\n pass\n else:\n self.fail('FileOrDirNotFoundError exception expected')\n\n def test_dir_empty_notdir(self):\n fd, tmpfile = mkstemp()\n try:\n try:\n fs.dir_empty(tmpfile)\n except NotDirectoryError:\n pass\n else:\n self.fail('NotDirectoryError exception expected')\n finally:\n os.close(fd)\n os.unlink(tmpfile)\n", "method_code": "def dir_empty(path):\n \"\"\"\n Return true if directory is empty (or does not exist), false otherwise.\n\n :param path: Directory path\n :returns: True/False\n \"\"\"\n try:\n files = do_listdir(path)\n return not files\n except GlusterFileSystemOSError as err:\n if err.errno == errno.ENOENT:\n raise FileOrDirNotFoundError()\n if err.errno == errno.ENOTDIR:\n raise NotDirectoryError()\n raise", "context": "def dir_empty(path): ...\ndef do_walk(*args, **kwargs): ...\ndef do_write(fd, buf): ...\ndef do_read(fd, n): ...\ndef do_ismount(path): ...\ndef do_mkdir(path): ...\ndef do_listdir(path): ...\ndef dir_empty(path): ...\ndef do_rmdir(path): ...\ndef do_chown(path, uid, gid): ...\ndef do_fchown(fd, uid, gid): ...\ndef do_stat(path): ...\ndef do_fstat(fd): ...\ndef do_open(path, flags, **kwargs): ...\ndef do_close(fd): ...\ndef do_unlink(path, log=True): ...\ndef do_rename(old_path, new_path): ...\ndef do_fsync(fd): ...\ndef do_fdatasync(fd): ...\ndef do_fadvise64(fd, offset, length): ...\ndef do_lseek(fd, pos, how): ...\ndef mkdirs(path): ...\n", "repository": "portante/gluster-swift", "test_name": "test_dir_empty", "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, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000108.py"} {"focal_file": "gluster/swift/common/fs_utils.py", "focal_class": null, "focal_method": "do_rmdir", "tests": "import unittest\n\nclass Test_do_rmdir(unittest.TestCase):\n def test_do_rmdir(self):\n tmpdir = mkdtemp()\n try:\n subdir = mkdtemp(dir=tmpdir)\n fd, tmpfile = mkstemp(dir=tmpdir)\n try:\n fs.do_rmdir(tmpfile)\n except GlusterFileSystemOSError:\n pass\n else:\n self.fail('Expected GlusterFileSystemOSError')\n assert os.path.exists(subdir)\n try:\n fs.do_rmdir(tmpdir)\n except GlusterFileSystemOSError:\n pass\n else:\n self.fail('Expected GlusterFileSystemOSError')\n assert os.path.exists(subdir)\n fs.do_rmdir(subdir)\n assert not os.path.exists(subdir)\n finally:\n os.close(fd)\n shutil.rmtree(tmpdir)\n", "method_code": "def do_rmdir(path):\n try:\n os.rmdir(path)\n except OSError as err:\n raise GlusterFileSystemOSError(err.errno, '%s, os.rmdir(\"%s\")' % (err.strerror, path))", "context": "def do_rmdir(path): ...\ndef do_walk(*args, **kwargs): ...\ndef do_write(fd, buf): ...\ndef do_read(fd, n): ...\ndef do_ismount(path): ...\ndef do_mkdir(path): ...\ndef do_listdir(path): ...\ndef dir_empty(path): ...\ndef do_rmdir(path): ...\ndef do_chown(path, uid, gid): ...\ndef do_fchown(fd, uid, gid): ...\ndef do_stat(path): ...\ndef do_fstat(fd): ...\ndef do_open(path, flags, **kwargs): ...\ndef do_close(fd): ...\ndef do_unlink(path, log=True): ...\ndef do_rename(old_path, new_path): ...\ndef do_fsync(fd): ...\ndef do_fdatasync(fd): ...\ndef do_fadvise64(fd, offset, length): ...\ndef do_lseek(fd, pos, how): ...\ndef mkdirs(path): ...\n", "repository": "portante/gluster-swift", "test_name": "test_do_rmdir", "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, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000109.py"} {"focal_file": "gluster/swift/common/fs_utils.py", "focal_class": null, "focal_method": "do_chown", "tests": "import unittest\n\nclass Test_do_chown(unittest.TestCase):\n def test_chown_dir(self):\n tmpdir = mkdtemp()\n try:\n subdir = mkdtemp(dir=tmpdir)\n buf = os.stat(subdir)\n if buf.st_uid == 0:\n raise SkipTest\n else:\n try:\n fs.do_chown(subdir, 20000, 20000)\n except GlusterFileSystemOSError as ex:\n if ex.errno != errno.EPERM:\n self.fail('Expected GlusterFileSystemOSError(errno=EPERM)')\n else:\n self.fail('Expected GlusterFileSystemOSError')\n finally:\n shutil.rmtree(tmpdir)\n\n def test_chown_file(self):\n tmpdir = mkdtemp()\n try:\n fd, tmpfile = mkstemp(dir=tmpdir)\n buf = os.stat(tmpfile)\n if buf.st_uid == 0:\n raise SkipTest\n else:\n try:\n fs.do_chown(tmpfile, 20000, 20000)\n except GlusterFileSystemOSError as ex:\n if ex.errno != errno.EPERM:\n self.fail('Expected GlusterFileSystemOSError(errno=EPERM')\n else:\n self.fail('Expected GlusterFileSystemOSError')\n finally:\n os.close(fd)\n shutil.rmtree(tmpdir)\n", "method_code": "def do_chown(path, uid, gid):\n try:\n os.chown(path, uid, gid)\n except OSError as err:\n raise GlusterFileSystemOSError(err.errno, '%s, os.chown(\"%s\", %s, %s)' % (err.strerror, path, uid, gid))", "context": "def do_chown(path, uid, gid): ...\ndef do_walk(*args, **kwargs): ...\ndef do_write(fd, buf): ...\ndef do_read(fd, n): ...\ndef do_ismount(path): ...\ndef do_mkdir(path): ...\ndef do_listdir(path): ...\ndef dir_empty(path): ...\ndef do_rmdir(path): ...\ndef do_chown(path, uid, gid): ...\ndef do_fchown(fd, uid, gid): ...\ndef do_stat(path): ...\ndef do_fstat(fd): ...\ndef do_open(path, flags, **kwargs): ...\ndef do_close(fd): ...\ndef do_unlink(path, log=True): ...\ndef do_rename(old_path, new_path): ...\ndef do_fsync(fd): ...\ndef do_fdatasync(fd): ...\ndef do_fadvise64(fd, offset, length): ...\ndef do_lseek(fd, pos, how): ...\ndef mkdirs(path): ...\n", "repository": "portante/gluster-swift", "test_name": "test_chown_dir", "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, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000110.py"} {"focal_file": "gluster/swift/common/fs_utils.py", "focal_class": null, "focal_method": "do_fchown", "tests": "import unittest\n\nclass Test_do_fchown(unittest.TestCase):\n def test_fchown(self):\n tmpdir = mkdtemp()\n try:\n fd, tmpfile = mkstemp(dir=tmpdir)\n buf = os.stat(tmpfile)\n if buf.st_uid == 0:\n raise SkipTest\n else:\n try:\n fs.do_fchown(fd, 20000, 20000)\n except GlusterFileSystemOSError as ex:\n if ex.errno != errno.EPERM:\n self.fail('Expected GlusterFileSystemOSError(errno=EPERM)')\n else:\n self.fail('Expected GlusterFileSystemOSError')\n finally:\n os.close(fd)\n shutil.rmtree(tmpdir)\n\n def test_fchown_err(self):\n tmpdir = mkdtemp()\n try:\n fd, tmpfile = mkstemp(dir=tmpdir)\n fd_rd = os.open(tmpfile, os.O_RDONLY)\n buf = os.stat(tmpfile)\n if buf.st_uid == 0:\n raise SkipTest\n else:\n try:\n fs.do_fchown(fd_rd, 20000, 20000)\n except GlusterFileSystemOSError as ex:\n if ex.errno != errno.EPERM:\n self.fail('Expected GlusterFileSystemOSError(errno=EPERM)')\n else:\n self.fail('Expected GlusterFileSystemOSError')\n finally:\n os.close(fd_rd)\n os.close(fd)\n shutil.rmtree(tmpdir)\n", "method_code": "def do_fchown(fd, uid, gid):\n try:\n os.fchown(fd, uid, gid)\n except OSError as err:\n raise GlusterFileSystemOSError(err.errno, '%s, os.fchown(%s, %s, %s)' % (err.strerror, fd, uid, gid))", "context": "def do_fchown(fd, uid, gid): ...\ndef do_walk(*args, **kwargs): ...\ndef do_write(fd, buf): ...\ndef do_read(fd, n): ...\ndef do_ismount(path): ...\ndef do_mkdir(path): ...\ndef do_listdir(path): ...\ndef dir_empty(path): ...\ndef do_rmdir(path): ...\ndef do_chown(path, uid, gid): ...\ndef do_fchown(fd, uid, gid): ...\ndef do_stat(path): ...\ndef do_fstat(fd): ...\ndef do_open(path, flags, **kwargs): ...\ndef do_close(fd): ...\ndef do_unlink(path, log=True): ...\ndef do_rename(old_path, new_path): ...\ndef do_fsync(fd): ...\ndef do_fdatasync(fd): ...\ndef do_fadvise64(fd, offset, length): ...\ndef do_lseek(fd, pos, how): ...\ndef mkdirs(path): ...\n", "repository": "portante/gluster-swift", "test_name": "test_fchown", "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, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000111.py"} {"focal_file": "gluster/swift/common/fs_utils.py", "focal_class": null, "focal_method": "do_fsync", "tests": "import unittest\n\nclass Test_do_fsync(unittest.TestCase):\n def test_do_fsync(self):\n tmpdir = mkdtemp()\n try:\n fd, tmpfile = mkstemp(dir=tmpdir)\n try:\n os.write(fd, 'test')\n with patch('os.fsync', mock_os_fsync):\n assert fs.do_fsync(fd) is None\n except GlusterFileSystemOSError as ose:\n self.fail('Opening a temporary file failed with %s' % ose.strerror)\n else:\n os.close(fd)\n finally:\n shutil.rmtree(tmpdir)\n\n def test_do_fsync_err(self):\n tmpdir = mkdtemp()\n try:\n fd, tmpfile = mkstemp(dir=tmpdir)\n os.write(fd, 'test')\n with patch('os.fsync', mock_os_fsync):\n assert fs.do_fsync(fd) is None\n os.close(fd)\n try:\n fs.do_fsync(fd)\n except GlusterFileSystemOSError:\n pass\n else:\n self.fail('Expected GlusterFileSystemOSError')\n finally:\n shutil.rmtree(tmpdir)\n", "method_code": "def do_fsync(fd):\n try:\n os.fsync(fd)\n except OSError as err:\n raise GlusterFileSystemOSError(err.errno, '%s, os.fsync(\"%s\")' % (err.strerror, fd))", "context": "def do_fsync(fd): ...\ndef do_walk(*args, **kwargs): ...\ndef do_write(fd, buf): ...\ndef do_read(fd, n): ...\ndef do_ismount(path): ...\ndef do_mkdir(path): ...\ndef do_listdir(path): ...\ndef dir_empty(path): ...\ndef do_rmdir(path): ...\ndef do_chown(path, uid, gid): ...\ndef do_fchown(fd, uid, gid): ...\ndef do_stat(path): ...\ndef do_fstat(fd): ...\ndef do_open(path, flags, **kwargs): ...\ndef do_close(fd): ...\ndef do_unlink(path, log=True): ...\ndef do_rename(old_path, new_path): ...\ndef do_fsync(fd): ...\ndef do_fdatasync(fd): ...\ndef do_fadvise64(fd, offset, length): ...\ndef do_lseek(fd, pos, how): ...\ndef mkdirs(path): ...\n", "repository": "portante/gluster-swift", "test_name": "test_do_fsync", "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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000112.py"} {"focal_file": "gluster/swift/common/fs_utils.py", "focal_class": null, "focal_method": "do_fdatasync", "tests": "import unittest\n\nclass Test_do_fdatasync(unittest.TestCase):\n def test_do_fdatasync(self):\n tmpdir = mkdtemp()\n try:\n fd, tmpfile = mkstemp(dir=tmpdir)\n try:\n os.write(fd, 'test')\n with patch('os.fdatasync', mock_os_fdatasync):\n assert fs.do_fdatasync(fd) is None\n except GlusterFileSystemOSError as ose:\n self.fail('Opening a temporary file failed with %s' % ose.strerror)\n else:\n os.close(fd)\n finally:\n shutil.rmtree(tmpdir)\n\n def test_do_fdatasync_err(self):\n tmpdir = mkdtemp()\n try:\n fd, tmpfile = mkstemp(dir=tmpdir)\n os.write(fd, 'test')\n with patch('os.fdatasync', mock_os_fdatasync):\n assert fs.do_fdatasync(fd) is None\n os.close(fd)\n try:\n fs.do_fdatasync(fd)\n except GlusterFileSystemOSError:\n pass\n else:\n self.fail('Expected GlusterFileSystemOSError')\n finally:\n shutil.rmtree(tmpdir)\n", "method_code": "def do_fdatasync(fd):\n try:\n os.fdatasync(fd)\n except AttributeError:\n do_fsync(fd)\n except OSError as err:\n raise GlusterFileSystemOSError(err.errno, '%s, os.fsync(\"%s\")' % (err.strerror, fd))", "context": "def do_fdatasync(fd): ...\ndef do_walk(*args, **kwargs): ...\ndef do_write(fd, buf): ...\ndef do_read(fd, n): ...\ndef do_ismount(path): ...\ndef do_mkdir(path): ...\ndef do_listdir(path): ...\ndef dir_empty(path): ...\ndef do_rmdir(path): ...\ndef do_chown(path, uid, gid): ...\ndef do_fchown(fd, uid, gid): ...\ndef do_stat(path): ...\ndef do_fstat(fd): ...\ndef do_open(path, flags, **kwargs): ...\ndef do_close(fd): ...\ndef do_unlink(path, log=True): ...\ndef do_rename(old_path, new_path): ...\ndef do_fsync(fd): ...\ndef do_fdatasync(fd): ...\ndef do_fadvise64(fd, offset, length): ...\ndef do_lseek(fd, pos, how): ...\ndef mkdirs(path): ...\n", "repository": "portante/gluster-swift", "test_name": "test_do_fdatasync", "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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000113.py"} {"focal_file": "WebSocket/src/mod_pywebsocket/handshake/hybi00.py", "focal_class": null, "focal_method": "_validate_subprotocol", "tests": "import unittest\n\nclass Test_validate_subprotocol(unittest.TestCase):\n def test_validate_subprotocol(self):\n _validate_subprotocol('sample')\n _validate_subprotocol('Sample')\n _validate_subprotocol('sample~protocol')\n _validate_subprotocol('sample protocol')\n self.assertRaises(HandshakeException, _validate_subprotocol, '')\n self.assertRaises(HandshakeException, _validate_subprotocol, 'sample\\x19protocol')\n self.assertRaises(HandshakeException, _validate_subprotocol, 'sample\\x7fprotocol')\n self.assertRaises(HandshakeException, _validate_subprotocol, u'日本')\n", "method_code": "def _validate_subprotocol(subprotocol):\n \"\"\"Checks if characters in subprotocol are in range between U+0020 and\n U+007E. A value in the Sec-WebSocket-Protocol field need to satisfy this\n requirement.\n\n See the Section 4.1. Opening handshake of the spec.\n \"\"\"\n if not subprotocol:\n raise HandshakeException('Invalid subprotocol name: empty')\n for c in subprotocol:\n if not 32 <= ord(c) <= 126:\n raise HandshakeException('Illegal character in subprotocol name: %r' % c)", "context": "def _validate_subprotocol(subprotocol): ...\ndef _validate_subprotocol(subprotocol): ...\ndef _check_header_lines(request, mandatory_headers): ...\ndef _build_location(request): ...\n", "repository": "wanghy0113/webofweb", "test_name": "test_validate_subprotocol", "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_000114.py"} {"focal_file": "WebSocket/src/test/mock.py", "focal_class": null, "focal_method": "readline", "tests": "import unittest\n\nclass Test_readline(unittest.TestCase):\n def test_readline(self):\n self.assertEqual('ABC\\r\\n', self._conn.readline())\n self.assertEqual('DEFG\\r\\n', self._conn.readline())\n self.assertEqual('\\r\\n', self._conn.readline())\n self.assertEqual('HIJK', self._conn.readline())\n self.assertEqual('', self._conn.readline())\n\n def test_read_and_readline(self):\n self.assertEqual('ABC\\r\\nD', self._conn.read(6))\n self.assertEqual('EFG\\r\\n', self._conn.readline())\n self.assertEqual('\\r\\nHIJK', self._conn.read(9))\n self.assertEqual('', self._conn.readline())\n", "method_code": " def readline(self):\n \"\"\"Override mod_python.apache.mp_conn.readline.\"\"\"\n if self._read_pos >= len(self._read_data):\n return ''\n end_index = self._read_data.find('\\n', self._read_pos) + 1\n if not end_index:\n end_index = len(self._read_data)\n return self._read_up_to(end_index)\n ", "context": "class MockConn(_MockConnBase):\n def readline(self): ...\n def __init__(self, read_data): ...\n def read(self, length): ...\n def _read_up_to(self, end_index): ...\n\n self._read_data = read_data\n self._read_pos = 0\n", "repository": "wanghy0113/webofweb", "test_name": "test_readline", "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_000115.py"} {"focal_file": "Unit Tests/calculator.py", "focal_class": null, "focal_method": "add", "tests": "import unittest\n\nclass Test_add(unittest.TestCase):\n def test_add(self):\n self.assertEqual(calculator.add(10, 5), 15)\n self.assertEqual(calculator.add(-1, 1), 0)\n self.assertEqual(calculator.add(-2, -2), -4)\n", "method_code": "def add(a, b):\n return a + b", "context": "def add(a, b): ...\ndef add(a, b): ...\ndef mul(a, b): ...\n", "repository": "prasad01dalavi/python-snippets", "test_name": "test_add", "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_000116.py"} {"focal_file": "Unit Tests/calculator.py", "focal_class": null, "focal_method": "mul", "tests": "import unittest\n\nclass Test_mul(unittest.TestCase):\n def test_mul(self):\n self.assertEqual(calculator.mul(10, 5), 50)\n self.assertEqual(calculator.mul(-1, 0), 0)\n self.assertEqual(calculator.mul(-2, -2), 4)\n", "method_code": "def mul(a, b):\n return a * b", "context": "def mul(a, b): ...\ndef add(a, b): ...\ndef mul(a, b): ...\n", "repository": "prasad01dalavi/python-snippets", "test_name": "test_mul", "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_000117.py"} {"focal_file": "applyaf.py", "focal_class": null, "focal_method": "apply_antenna_factor", "tests": "import unittest\n\nclass Test_apply_antenna_factor(unittest.TestCase):\n def test_applying_antenna_factor(self):\n known_incident_field = np.array([(312879000.0, 44.200116867), (314719000.0, 43.704955533), (318398000.0, 44.4234524), (320238000.0, 44.224091067), (322078000.0, 43.717929733), (325758000.0, 43.557791067)], dtype=self.my_data_type)\n calculated_incident_field = applyaf.apply_antenna_factor(self.spectrum_analyzer_readings, self.antenna_factors, self.cable_losses)\n np.testing.assert_array_equal(calculated_incident_field['frequency'], known_incident_field['frequency'])\n np.testing.assert_array_almost_equal(calculated_incident_field['amplitude_db'], known_incident_field['amplitude_db'])\n\n def test_applying_antenna_factor_without_cable_loss(self):\n known_incident_field = np.array([(312879000.0, 43.84744), (314719000.0, 43.35142), (318398000.0, 44.0682), (320238000.0, 43.86798), (322078000.0, 43.36096), (325758000.0, 43.199104)], dtype=self.my_data_type)\n calculated_incident_field = applyaf.apply_antenna_factor(self.spectrum_analyzer_readings, self.antenna_factors)\n np.testing.assert_array_equal(calculated_incident_field['frequency'], known_incident_field['frequency'])\n np.testing.assert_array_almost_equal(calculated_incident_field['amplitude_db'], known_incident_field['amplitude_db'])\n", "method_code": "def apply_antenna_factor(analyzer_readings, antenna_factors, cable_losses=False, keep_max=True):\n \"\"\"Apply the antenna factor and cable losses to the input data.\n\n Applies the frequency dependent antenna factor and, optionally, the cable\n losses to a given input data (typically spectrum analyzer readings). Before\n interpolating the frequencies of the antenna factors and cable losses onto\n the dataset, any duplicate frequency entries are removed and either the\n minimum or maximum amplitude value is kept depending on the user's\n selection.\n\n This is used to calculate the incident field which is defined as:\n E(dBuV/m) = AF(dB) + Vsa(dBuV) + cable_loss(dB)\n\n\n as given by Eqn 7.62 in *Introduction to Electromagnetic Compatibility* 2nd\n edition by Clayton Paul.\n\n Args:\n analyzer_readings: A 1D numpy structured array containing the fields\n 'frequency' and 'amplitude_db'.\n antenna_factors: A 1D numpy structured array containing the fields\n 'frequency' and 'amplitude_db'.\n cables_losses: A 1D numpy structured array containing the fields\n 'frequency' and 'amplitude_db'.\n keep_max: A boolean determining whether the max or min amplitudes are\n kept whenever duplicate frequency entries are found in the\n antenna_factors or cable_losses arrays.\n\n Returns:\n A 1D numpy structured array containing the incident field.\n \"\"\"\n analyzer_readings_no_duplicates = _remove_duplicate_frequencies(analyzer_readings, keep_max)\n antenna_factors_no_duplicates = _remove_duplicate_frequencies(antenna_factors, keep_max)\n antenna_factors_at_analyzer_frequencies = np.interp(analyzer_readings_no_duplicates['frequency'], antenna_factors_no_duplicates['frequency'], antenna_factors_no_duplicates['amplitude_db'])\n if isinstance(cable_losses, np.ndarray):\n cable_losses_no_duplicates = _remove_duplicate_frequencies(cable_losses, keep_max)\n cable_losses_at_analyzer_frequencies = np.interp(analyzer_readings_no_duplicates['frequency'], cable_losses_no_duplicates['frequency'], cable_losses_no_duplicates['amplitude_db'])\n incident_field = analyzer_readings_no_duplicates\n incident_field['amplitude_db'] += antenna_factors_at_analyzer_frequencies\n incident_field['amplitude_db'] += cable_losses_at_analyzer_frequencies\n else:\n incident_field = analyzer_readings_no_duplicates\n incident_field['amplitude_db'] += antenna_factors_at_analyzer_frequencies\n return incident_field", "context": "def apply_antenna_factor(analyzer_readings, antenna_factors, cable_losses=False, keep_max=True): ...\ndef _is_valid_file(parser, arg): ...\ndef _read_csv_file(filename, freq_unit_multiplier): ...\ndef _remove_duplicate_frequencies(unsorted_array, keep_max=True): ...\ndef apply_antenna_factor(analyzer_readings, antenna_factors, cable_losses=False, keep_max=True): ...\ndef remove_antenna_factor(analyzer_readings, antenna_factors, cable_losses=False, keep_max=True): ...\n", "repository": "questrail/applyaf", "test_name": "test_applying_antenna_factor", "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_000118.py"} {"focal_file": "applyaf.py", "focal_class": null, "focal_method": "remove_antenna_factor", "tests": "import unittest\n\nclass Test_remove_antenna_factor(unittest.TestCase):\n def test_applying_then_removing_antenna_factor(self):\n given_analyzer_readings = np.array([(312879000.0, 43.84744), (314719000.0, 43.35142), (318398000.0, 44.0682), (320238000.0, 43.86798), (322078000.0, 43.36096), (325758000.0, 43.199104)], dtype=self.my_data_type)\n calculated_incident_field = applyaf.apply_antenna_factor(given_analyzer_readings, self.antenna_factors, self.cable_losses)\n calculated_analyzer_readings = applyaf.remove_antenna_factor(calculated_incident_field, self.antenna_factors, self.cable_losses)\n np.testing.assert_array_equal(calculated_analyzer_readings['frequency'], given_analyzer_readings['frequency'])\n np.testing.assert_array_almost_equal(calculated_analyzer_readings['amplitude_db'], given_analyzer_readings['amplitude_db'])\n", "method_code": "def remove_antenna_factor(analyzer_readings, antenna_factors, cable_losses=False, keep_max=True):\n \"\"\"Remove the antenna factor and cable losses to the input data.\n\n Removes the frequency dependent antenna factor and, optionally, the cable\n losses to a given input data (typically spectrum analyzer readings). Before\n interpolating the frequencies of the antenna factors and cable losses onto\n the dataset, any duplicate frequency entries are removed and either the\n minimum or maximum amplitude value is kept depending on the user's\n selection.\n\n Args:\n analyzer_readings: A 1D numpy structured array containing the fields\n 'frequency' and 'amplitude_db'.\n antenna_factors: A 1D numpy structured array containing the fields\n 'frequency' and 'amplitude_db'.\n cables_losses: A 1D numpy structured array containing the fields\n 'frequency' and 'amplitude_db'.\n keep_max: A boolean determining whether the max or min amplitudes are\n kept whenever duplicate frequency entries are found in the\n antenna_factors or cable_losses arrays.\n\n Returns:\n A 1D numpy structured array containing the incident field.\n \"\"\"\n analyzer_readings_no_duplicates = _remove_duplicate_frequencies(analyzer_readings, keep_max)\n antenna_factors_no_duplicates = _remove_duplicate_frequencies(antenna_factors, keep_max)\n antenna_factors_at_analyzer_frequencies = np.interp(analyzer_readings_no_duplicates['frequency'], antenna_factors_no_duplicates['frequency'], antenna_factors_no_duplicates['amplitude_db'])\n if isinstance(cable_losses, np.ndarray):\n cable_losses_no_duplicates = _remove_duplicate_frequencies(cable_losses, keep_max)\n cable_losses_at_analyzer_frequencies = np.interp(analyzer_readings_no_duplicates['frequency'], cable_losses_no_duplicates['frequency'], cable_losses_no_duplicates['amplitude_db'])\n incident_field = analyzer_readings_no_duplicates\n incident_field['amplitude_db'] -= antenna_factors_at_analyzer_frequencies\n incident_field['amplitude_db'] -= cable_losses_at_analyzer_frequencies\n else:\n incident_field = analyzer_readings_no_duplicates\n incident_field['amplitude_db'] -= antenna_factors_at_analyzer_frequencies\n return incident_field", "context": "def remove_antenna_factor(analyzer_readings, antenna_factors, cable_losses=False, keep_max=True): ...\ndef _is_valid_file(parser, arg): ...\ndef _read_csv_file(filename, freq_unit_multiplier): ...\ndef _remove_duplicate_frequencies(unsorted_array, keep_max=True): ...\ndef apply_antenna_factor(analyzer_readings, antenna_factors, cable_losses=False, keep_max=True): ...\ndef remove_antenna_factor(analyzer_readings, antenna_factors, cable_losses=False, keep_max=True): ...\n", "repository": "questrail/applyaf", "test_name": "test_applying_then_removing_antenna_factor", "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_000119.py"} {"focal_file": "applyaf.py", "focal_class": null, "focal_method": "_remove_duplicate_frequencies", "tests": "import unittest\n\nclass Test_remove_duplicate_frequencies(unittest.TestCase):\n def test_remove_duplicates_keep_max(self):\n array_without_dups_kept_max = applyaf._remove_duplicate_frequencies(self.given_array_with_duplicates, True)\n np.testing.assert_array_equal(array_without_dups_kept_max, self.given_array_without_duplicates_kept_max)\n\n def test_remove_duplicates_keep_min(self):\n array_without_dups_kept_min = applyaf._remove_duplicate_frequencies(self.given_array_with_duplicates, keep_max=False)\n np.testing.assert_array_equal(array_without_dups_kept_min, self.given_array_without_duplicates_kept_min)\n", "method_code": "def _remove_duplicate_frequencies(unsorted_array, keep_max=True):\n \"\"\"Remove duplicates and sort by frequency\n\n Given a structured numpy array with 'frequency' and 'amplitude_db' fields,\n sort that array first by frequency and then by amplitude. Depending on\n whether the user wants to keep the max or min value, return the sorted\n array containing no duplicate frequency entries.\n Remove the duplicate frequencies.\n\n Args:\n unsorted_array: A 1D numpy structured array with fields 'frequency' and\n 'amplitude_db'.\n keep_max: A boolean determing if the max or min amplitude values will\n be kept when duplicate frequencies are found.\n\n Returns:\n A sorted 1D numpy structured array with fields 'frequency' and\n 'amplitude_db' with no duplicate frequencies.\n \"\"\"\n sorted_array = np.sort(unsorted_array, order=['frequency', 'amplitude_db'])\n if keep_max:\n sorted_array = sorted_array[::-1]\n unique_indices = np.unique(sorted_array['frequency'], return_index=True)[1]\n return sorted_array[unique_indices]", "context": "def _remove_duplicate_frequencies(unsorted_array, keep_max=True): ...\ndef _is_valid_file(parser, arg): ...\ndef _read_csv_file(filename, freq_unit_multiplier): ...\ndef _remove_duplicate_frequencies(unsorted_array, keep_max=True): ...\ndef apply_antenna_factor(analyzer_readings, antenna_factors, cable_losses=False, keep_max=True): ...\ndef remove_antenna_factor(analyzer_readings, antenna_factors, cable_losses=False, keep_max=True): ...\n", "repository": "questrail/applyaf", "test_name": "test_remove_duplicates_keep_max", "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_000120.py"} {"focal_file": "arghelper.py", "focal_class": null, "focal_method": "extant_file", "tests": "import unittest\n\nclass Test_extant_file(unittest.TestCase):\n def test_extant_file_exists(self):\n \"\"\"Test that a file exists\"\"\"\n self.assertEqual(arghelper.extant_file(self.existing_file), self.existing_file)\n", "method_code": "def extant_file(arg):\n \"\"\"Facade for extant_item(arg, arg_type=\"file\")\n \"\"\"\n return extant_item(arg, 'file')", "context": "def extant_file(arg): ...\ndef extant_file(arg): ...\ndef extant_dir(arg): ...\ndef extant_item(arg, arg_type): ...\ndef parse_config_input_output(args=sys.argv): ...\ndef parse_config(args=sys.argv): ...\n", "repository": "questrail/arghelper", "test_name": "test_extant_file_exists", "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_000121.py"} {"focal_file": "arghelper.py", "focal_class": null, "focal_method": "parse_config_input_output", "tests": "import unittest\n\nclass Test_parse_config_input_output(unittest.TestCase):\n def test_parse_config_input_output(self):\n \"\"\"Test the parse_config_input_output function\"\"\"\n args = arghelper.parse_config_input_output(self.argv)\n self.assertEqual(args.config_file, self.config_file)\n self.assertEqual(args.input_dir, self.input_dir)\n self.assertEqual(args.output_dir, self.output_dir)\n", "method_code": "def parse_config_input_output(args=sys.argv):\n \"\"\"Parse the args using the config_file, input_dir, output_dir pattern\n\n Args:\n args: sys.argv\n\n Returns:\n The populated namespace object from parser.parse_args().\n\n Raises:\n TBD\n \"\"\"\n parser = argparse.ArgumentParser(description='Process the input files using the given config')\n parser.add_argument('config_file', help='Configuration file.', metavar='FILE', type=extant_file)\n parser.add_argument('input_dir', help='Directory containing the input files.', metavar='DIR', type=extant_dir)\n parser.add_argument('output_dir', help='Directory where the output files should be saved.', metavar='DIR', type=extant_dir)\n return parser.parse_args(args[1:])", "context": "def parse_config_input_output(args=sys.argv): ...\ndef extant_file(arg): ...\ndef extant_dir(arg): ...\ndef extant_item(arg, arg_type): ...\ndef parse_config_input_output(args=sys.argv): ...\ndef parse_config(args=sys.argv): ...\n", "repository": "questrail/arghelper", "test_name": "test_parse_config_input_output", "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_000122.py"} {"focal_file": "arghelper.py", "focal_class": null, "focal_method": "parse_config", "tests": "import unittest\n\nclass Test_parse_config(unittest.TestCase):\n def test_parse_config(self):\n \"\"\"Test the parse_config function\"\"\"\n args = arghelper.parse_config(self.argv)\n self.assertEqual(args.config_file, self.config_file)\n", "method_code": "def parse_config(args=sys.argv):\n \"\"\"Parse the args using the config_file pattern\n\n Args:\n args: sys.argv\n\n Returns:\n The populated namespace object from parser.parse_args().\n\n Raises:\n TBD\n \"\"\"\n parser = argparse.ArgumentParser(description='Read in the config file')\n parser.add_argument('config_file', help='Configuration file.', metavar='FILE', type=extant_file)\n return parser.parse_args(args[1:])", "context": "def parse_config(args=sys.argv): ...\ndef extant_file(arg): ...\ndef extant_dir(arg): ...\ndef extant_item(arg, arg_type): ...\ndef parse_config_input_output(args=sys.argv): ...\ndef parse_config(args=sys.argv): ...\n", "repository": "questrail/arghelper", "test_name": "test_parse_config", "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_000123.py"} {"focal_file": "taffmat.py", "focal_class": null, "focal_method": "_format_exponent_notation", "tests": "import unittest\n\nclass Test_format_exponent_notation(unittest.TestCase):\n def test_printing_exponent_notation(self):\n numbers_to_test = (2e-05, 4e-05, 8e-05, 0.0002, 0.0004, 0.0008, 0.002)\n number_as_string = [taffmat._format_exponent_notation(number_to_convert, 6, 3) for number_to_convert in numbers_to_test]\n correct_representation = ['2.000000e-005', '4.000000e-005', '8.000000e-005', '2.000000e-004', '4.000000e-004', '8.000000e-004', '2.000000e-003']\n self.assertEqual(number_as_string, correct_representation)\n", "method_code": "def _format_exponent_notation(input_number, precision, num_exponent_digits):\n \"\"\"\n Format the exponent notation. Python's exponent notation doesn't allow\n for a user-defined number of exponent digits.\n\n Based on [Anurag Uniyal's answer][answer] to the StackOverflow\n question ['Python - number of digits in exponent'][question]\n\n [question]: http://stackoverflow.com/q/9910972/95592\n [answer]: http://stackoverflow.com/a/9911741/95592\n \"\"\"\n python_exponent_notation = '{number:.{precision}e}'.format(number=input_number, precision=precision)\n mantissa, exponent = python_exponent_notation.split('e')\n return '{mantissa}e{exponent:+0{exp_num}d}'.format(mantissa=mantissa, exponent=int(exponent), exp_num=num_exponent_digits + 1)", "context": "def _format_exponent_notation(input_number, precision, num_exponent_digits): ...\ndef _append_windows_newlines(input_list_of_strings): ...\ndef _apply_slope_and_offset(data_array, number_of_series, slope, y_offset): ...\ndef _remove_slope_and_offset(data_array, number_of_series, slope, y_offset): ...\ndef _format_exponent_notation(input_number, precision, num_exponent_digits): ...\ndef _read_taffmat_hdr(input_hdr_file): ...\ndef change_slope(data_array, series, gain): ...\ndef _read_taffmat_dat(input_dat_file, file_type, number_of_series, slope, y_offset): ...\ndef _write_taffmat_hdr(header_data, output_hdr_filename): ...\ndef _write_taffmat_dat(data_array, number_of_series, slope, y_offset, output_dat_filename): ...\ndef read_taffmat(input_file): ...\ndef write_taffmat(data_array, header_data, output_base_filename): ...\ndef write_taffmat_slice(data_array, header_data, output_base_filename, starting_data_index, ending_data_index): ...\n", "repository": "questrail/taffmat", "test_name": "test_printing_exponent_notation", "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_000124.py"} {"focal_file": "taffmat.py", "focal_class": null, "focal_method": "change_slope", "tests": "import unittest\n\nclass Test_change_slope(unittest.TestCase):\n def test_changing_slope(self):\n data_array_new_slope = taffmat.change_slope(self.given_data_array_float, 0, 0.5)\n np.testing.assert_array_equal(data_array_new_slope, self.given_data_array_new_slope, 'Failed applying 1/2 gain to slope of series 0')\n np.testing.assert_array_equal(self.given_data_array_float, self.given_data_array_new_slope)\n", "method_code": "def change_slope(data_array, series, gain):\n \"\"\"Apply gain to the desired series in a data_array\n\n Args:\n data_array:\n series: integer listing the series to apply the gain (0-based)\n gain: float by which all data for given series will be multiplied\n\n Return:\n data_array: Return by reference\n\n Raises:\n N/A\n \"\"\"\n data_array[series] = gain * data_array[series]\n return data_array", "context": "def change_slope(data_array, series, gain): ...\ndef _append_windows_newlines(input_list_of_strings): ...\ndef _apply_slope_and_offset(data_array, number_of_series, slope, y_offset): ...\ndef _remove_slope_and_offset(data_array, number_of_series, slope, y_offset): ...\ndef _format_exponent_notation(input_number, precision, num_exponent_digits): ...\ndef _read_taffmat_hdr(input_hdr_file): ...\ndef change_slope(data_array, series, gain): ...\ndef _read_taffmat_dat(input_dat_file, file_type, number_of_series, slope, y_offset): ...\ndef _write_taffmat_hdr(header_data, output_hdr_filename): ...\ndef _write_taffmat_dat(data_array, number_of_series, slope, y_offset, output_dat_filename): ...\ndef read_taffmat(input_file): ...\ndef write_taffmat(data_array, header_data, output_base_filename): ...\ndef write_taffmat_slice(data_array, header_data, output_base_filename, starting_data_index, ending_data_index): ...\n", "repository": "questrail/taffmat", "test_name": "test_changing_slope", "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_000125.py"} {"focal_file": "taffmat.py", "focal_class": null, "focal_method": "write_taffmat_slice", "tests": "import unittest\n\nclass Test_write_taffmat_slice(unittest.TestCase):\n def test_writing_dat_file_slice(self):\n \"\"\"\n Write the first 1000 elements of data_array to a new .dat and .hdr\n file. Then read the new .dat file and make sure it matches the first\n 1000 elements of the original data_array\n \"\"\"\n slice_output_base_filename = os.path.join(self.test_taffmat_directory, 'test_slice_output_taffmat')\n number_of_samples_in_slice = 1000\n original_data_array = np.copy(self.data_array[:, 0:number_of_samples_in_slice])\n taffmat.write_taffmat_slice(self.data_array, self.header_data, slice_output_base_filename, 0, number_of_samples_in_slice - 1)\n slice_data_array, slice_time_vector, slice_header_data = taffmat.read_taffmat(slice_output_base_filename)\n self.assertEqual(slice_data_array.shape[1], number_of_samples_in_slice, 'Number of samples in slice incorrect.')\n np.testing.assert_array_equal(slice_data_array, original_data_array, 'The sliced data array does not equal the original data array.')\n", "method_code": "def write_taffmat_slice(data_array, header_data, output_base_filename, starting_data_index, ending_data_index):\n \"\"\"\n Write the TAFFmat .dat and .hdr given the starting and ending\n data points to include in the .dat file.\n\n The only change to the .hdr file from the given header_data\n dictionary is that the number of samples will be recalculated\n based on the starting and ending data points to be written.\n \"\"\"\n data_array_copy = data_array.copy()\n sliced_data_array = data_array_copy[:, starting_data_index:ending_data_index + 1]\n sliced_header_data = header_data\n new_number_of_samples = ending_data_index + 1 - starting_data_index\n sliced_header_data['number_of_samples'] = new_number_of_samples\n sliced_header_data['voice_memo_on'] = False\n sliced_header_data['dataset'] = os.path.basename(output_base_filename).upper()\n write_taffmat(sliced_data_array, sliced_header_data, output_base_filename)\n return", "context": "def write_taffmat_slice(data_array, header_data, output_base_filename, starting_data_index, ending_data_index): ...\ndef _append_windows_newlines(input_list_of_strings): ...\ndef _apply_slope_and_offset(data_array, number_of_series, slope, y_offset): ...\ndef _remove_slope_and_offset(data_array, number_of_series, slope, y_offset): ...\ndef _format_exponent_notation(input_number, precision, num_exponent_digits): ...\ndef _read_taffmat_hdr(input_hdr_file): ...\ndef change_slope(data_array, series, gain): ...\ndef _read_taffmat_dat(input_dat_file, file_type, number_of_series, slope, y_offset): ...\ndef _write_taffmat_hdr(header_data, output_hdr_filename): ...\ndef _write_taffmat_dat(data_array, number_of_series, slope, y_offset, output_dat_filename): ...\ndef read_taffmat(input_file): ...\ndef write_taffmat(data_array, header_data, output_base_filename): ...\ndef write_taffmat_slice(data_array, header_data, output_base_filename, starting_data_index, ending_data_index): ...\n", "repository": "questrail/taffmat", "test_name": "test_writing_dat_file_slice", "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_000126.py"} {"focal_file": "dirwalker.py", "focal_class": null, "focal_method": "find_filenames_with_extensions", "tests": "import unittest\n\nclass Test_find_filenames_with_extensions(unittest.TestCase):\n def test_find_single_file_without_extension_period(self):\n \"\"\"Find extensions that don't have a period\"\"\"\n test_set = set([self.known_sample_file_06_js])\n self.assertEqual(dirwalker.find_filenames_with_extensions(self.sample_dir, ['js']), test_set)\n\n def test_find_multiple_files_without_extension_period(self):\n \"\"\"Find extensions in recursive directories\"\"\"\n test_set = set([self.known_sample_file_01_txt, self.known_sample_file_02_txt, self.known_sample_level_2_file_01_txt, self.known_sample_level_2_file_02_txt])\n self.assertEqual(dirwalker.find_filenames_with_extensions(self.sample_dir, ['txt']), test_set)\n\n def test_find_multiple_files_without_recursion(self):\n \"\"\"Find extensions without recursing subdirectories\"\"\"\n test_set = set([self.known_sample_file_01_txt, self.known_sample_file_02_txt])\n self.assertEqual(dirwalker.find_filenames_with_extensions(self.sample_dir, ['txt'], recurse=False), test_set)\n\n def test_find_single_file_with_extension_period(self):\n \"\"\"Find extensions that have a period\"\"\"\n test_set = set([self.known_sample_file_06_js])\n self.assertEqual(dirwalker.find_filenames_with_extensions(self.sample_dir, ['.js']), test_set)\n\n def test_find_multiple_extensions(self):\n \"\"\"Find more than one extension\"\"\"\n test_set = set([self.known_sample_file_05_py, self.known_sample_file_06_js, self.known_sample_level_2_file_05_py])\n self.assertEqual(dirwalker.find_filenames_with_extensions(self.sample_dir, ['js', '.py']), test_set)\n", "method_code": "def find_filenames_with_extensions(search_directory, extensions, recurse=True):\n \"\"\"Find filenames with given extensions.\n\n Args:\n search_directory: A string of the absolute or relative directory to\n search.\n extensions: A list or tuple of strings containing the extensions to\n look for.\n recurse: A boolean indicating whether or not to recurse any\n subdirectories.\n\n Returns:\n A set of filenames found.\n \"\"\"\n files_found = set()\n search_directory = os.path.abspath(search_directory)\n if recurse:\n for root, dirs, files in os.walk(search_directory):\n for filename in files:\n current_file = os.path.join(root, filename)\n for extension in extensions:\n if filename.endswith(extension):\n files_found.add(current_file)\n else:\n for filename in os.listdir(search_directory):\n for extension in extensions:\n if filename.endswith(extension):\n current_file = os.path.join(search_directory, filename)\n files_found.add(current_file)\n return files_found", "context": "def find_filenames_with_extensions(search_directory, extensions, recurse=True): ...\ndef find_filenames_with_extensions(search_directory, extensions, recurse=True): ...\n", "repository": "questrail/dirwalker", "test_name": "test_find_single_file_without_extension_period", "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_000127.py"} {"focal_file": "src/lib/bs4/tests/test_builder_registry.py", "focal_class": null, "focal_method": "builder_for_features", "tests": "import unittest\n\nclass Test_builder_for_features(unittest.TestCase):\n def test_register_with_no_features(self):\n builder = self.builder_for_features()\n self.assertEqual(self.registry.lookup('foo'), None)\n self.assertEqual(self.registry.lookup(), builder)\n", "method_code": " def builder_for_features(self, *feature_list):\n cls = type('Builder_' + '_'.join(feature_list), (object,), {'features': feature_list})\n self.registry.register(cls)\n return cls\n ", "context": "class RegistryTest(unittest.TestCase):\n def builder_for_features(self, *feature_list): ...\n def setUp(self): ...\n def test_register_with_no_features(self): ...\n def test_register_with_features_makes_lookup_succeed(self): ...\n def test_lookup_fails_when_no_builder_implements_feature(self): ...\n def test_lookup_gets_most_recent_registration_when_no_feature_specified(self): ...\n def test_lookup_fails_when_no_tree_builders_registered(self): ...\n def test_lookup_gets_most_recent_builder_supporting_all_features(self): ...\n def test_lookup_fails_when_cannot_reconcile_requested_features(self): ...\n", "repository": "ghostlandr/chat-webhook-responder", "test_name": "test_register_with_no_features", "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_000128.py"} {"focal_file": "debile/master/arches.py", "focal_class": null, "focal_method": "arch_matches", "tests": "import unittest\n\nclass Test_arch_matches(unittest.TestCase):\n def test_arch_matches_arch_equal_alias(self):\n self.assertTrue(arch_matches('amd64', 'amd64'))\n\n def test_arch_matches_pseudo_arches(self):\n self.assertFalse(arch_matches('all', 'amd64'))\n self.assertFalse(arch_matches('source', 'amd64'))\n\n def test_arch_matches_any_arch(self):\n self.assertTrue(arch_matches('amd64', 'any'))\n\n def test_arch_matches_linux_any_alias(self):\n self.assertTrue(arch_matches('amd64', 'linux-any'))\n self.assertTrue(arch_matches('linux-amd64', 'linux-any'))\n self.assertFalse(arch_matches('hurd-i386', 'linux-any'))\n\n def test_arch_matches_ends_with_any(self):\n self.assertTrue(arch_matches('bsd-amd64', 'bsd-any'))\n self.assertFalse(arch_matches('linux-amd64', 'kfreebsd-any'))\n\n def test_arch_matches_without_dash(self):\n self.assertFalse(arch_matches('any', 'amd64'))\n", "method_code": "def arch_matches(arch, alias):\n \"\"\"\n Check if given arch `arch` matches the other arch `alias`. This is most\n useful for the complex any-* rules.\n \"\"\"\n if arch == alias:\n return True\n if arch == 'all' or arch == 'source':\n return False\n if alias == 'any':\n return True\n if alias == 'linux-any':\n return '-' not in arch or 'linux' in arch.split('-')\n if alias.endswith('-any'):\n osname, _ = alias.split('-', 1)\n return osname in arch.split('-')\n if '-' not in arch and '-' not in alias:\n return False\n out, err, ret = run_command(['/usr/bin/dpkg-architecture', '-a%s' % arch, '-i%s' % alias])\n return ret == 0", "context": "def arch_matches(arch, alias): ...\ndef arch_matches(arch, alias): ...\ndef get_preferred_affinity(affinity_preference, valid_affinities, valid_arches): ...\ndef get_source_arches(dsc_arches, valid_arches): ...\n", "repository": "opencollab/debile", "test_name": "test_arch_matches_arch_equal_alias", "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_000129.py"} {"focal_file": "debile/master/arches.py", "focal_class": null, "focal_method": "get_preferred_affinity", "tests": "import unittest\n\nclass Test_get_preferred_affinity(unittest.TestCase):\n @mock.patch('debile.master.arches.arch_matches', return_value=True)\n def test_get_preferred_affinity(self, mock):\n affinity = ['amd64']\n valid = ['i386']\n arch = get_preferred_affinity(affinity, valid, self.arches)\n self.assertEquals(arch.name, 'amd64')\n", "method_code": "def get_preferred_affinity(affinity_preference, valid_affinities, valid_arches):\n \"\"\"\n Given a list of strings representing the preffered affinities in the\n config, a list of string with valid affinities of the source, and a list\n of valid architectures in the suite, return the arch object to use as\n affinity for arch \"all\" jobs.\n \"\"\"\n for affinity in affinity_preference:\n arch = None\n for x in valid_arches:\n if x.name == affinity:\n arch = x\n break\n if arch is None:\n continue\n for alias in valid_affinities:\n if arch_matches(affinity, alias):\n return arch\n raise ValueError(\"No valid affinity - preferences: '%s'; valid: '%s'; arches %s\" % (', '.join(affinity_preference), ', '.join(valid_affinities), ', '.join([x.name for x in valid_arches])))", "context": "def get_preferred_affinity(affinity_preference, valid_affinities, valid_arches): ...\ndef arch_matches(arch, alias): ...\ndef get_preferred_affinity(affinity_preference, valid_affinities, valid_arches): ...\ndef get_source_arches(dsc_arches, valid_arches): ...\n", "repository": "opencollab/debile", "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": [0, 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": "debile/master/arches.py", "focal_class": null, "focal_method": "get_source_arches", "tests": "import unittest\n\nclass Test_get_source_arches(unittest.TestCase):\n @mock.patch('debile.master.arches.arch_matches', return_value=True)\n def test_get_source_arches_without_matches(self, mock):\n dsc_arch = ['amd64', 'sparc']\n ret = get_source_arches(dsc_arch, self.arches)\n self.assertEquals(ret[0].name, 'amd64')\n self.assertEquals(ret[1].name, 'sparc')\n", "method_code": "def get_source_arches(dsc_arches, valid_arches):\n \"\"\"\n Given a list of strings with the Architectures data from the dsc,\n and a list of valid Arch objects from the suite, return the Arch\n objects to add to the Source object.\n \"\"\"\n ret = []\n for arch in valid_arches:\n for alias in dsc_arches:\n if arch_matches(arch.name, alias):\n ret.append(arch)\n break\n return ret", "context": "def get_source_arches(dsc_arches, valid_arches): ...\ndef arch_matches(arch, alias): ...\ndef get_preferred_affinity(affinity_preference, valid_affinities, valid_arches): ...\ndef get_source_arches(dsc_arches, valid_arches): ...\n", "repository": "opencollab/debile", "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": [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": "debile/master/changes.py", "focal_class": null, "focal_method": "is_source_only_upload", "tests": "import unittest\n\nclass Test_is_source_only_upload(unittest.TestCase):\n @mock.patch('debile.master.changes.Changes.get_files', return_value=['debile.udeb'])\n def test_is_source_only_upload_with_udeb_file(self, mock_get_files):\n self.assertFalse(self.change.is_source_only_upload())\n\n @mock.patch('debile.master.changes.Changes.get_files', return_value=['debile.deb'])\n def test_is_source_only_upload_with_deb_file(self, mock_get_files):\n self.assertFalse(self.change.is_source_only_upload())\n\n @mock.patch('debile.master.changes.Changes.get_files', return_value=['debile.changes'])\n def test_is_source_only_upload_with_changes_file(self, mock_get_files):\n self.assertTrue(self.change.is_source_only_upload())\n", "method_code": " def is_source_only_upload(self):\n for f in self.get_files():\n if f.endswith('.deb') or f.endswith('.udeb'):\n return False\n return True\n ", "context": "class Changes(object):\n def is_source_only_upload(self): ...\n def __init__(self, filename=None, string=None): ...\n def is_binary_only_upload(self): ...\n def get_filename(self): ...\n def get_changes_file(self): ...\n def get_files(self): ...\n def __getitem__(self, key): ...\n def __contains__(self, key): ...\n def get(self, key, default=None): ...\n def get_component(self): ...\n def get_priority(self): ...\n def get_dsc_obj(self): ...\n def get_dsc(self): ...\n def get_diff(self): ...\n def get_pool_path(self): ...\n def get_package_name(self): ...\n def _parse_section(self, section): ...\n def validate(self, check_hash='md5', keyring=None): ...\n def validate_signature(self, keyring): ...\n def validate_checksums(self, check_hash='md5'): ...\n\n self.is_python3 = False\n", "repository": "opencollab/debile", "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": [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": "debile/master/changes.py", "focal_class": null, "focal_method": "is_binary_only_upload", "tests": "import unittest\n\nclass Test_is_binary_only_upload(unittest.TestCase):\n @mock.patch('debile.master.changes.Changes.get_files', return_value=['debile.udeb'])\n def test_is_binary_only_upload_with_udeb_file(self, mock_get_files):\n self.assertTrue(self.change.is_binary_only_upload())\n\n @mock.patch('debile.master.changes.Changes.get_files', return_value=['debile.deb'])\n def test_is_binary_only_upload_with_deb_file(self, mock_get_files):\n self.assertTrue(self.change.is_binary_only_upload())\n\n @mock.patch('debile.master.changes.Changes.get_files', return_value=['debile.changes'])\n def test_is_binary_only_upload_with_changes_file(self, mock_get_files):\n self.assertFalse(self.change.is_binary_only_upload())\n", "method_code": " def is_binary_only_upload(self):\n for f in self.get_files():\n if not (f.endswith('.deb') or f.endswith('.udeb')):\n return False\n return True\n ", "context": "class Changes(object):\n def is_binary_only_upload(self): ...\n def __init__(self, filename=None, string=None): ...\n def is_source_only_upload(self): ...\n def get_filename(self): ...\n def get_changes_file(self): ...\n def get_files(self): ...\n def __getitem__(self, key): ...\n def __contains__(self, key): ...\n def get(self, key, default=None): ...\n def get_component(self): ...\n def get_priority(self): ...\n def get_dsc_obj(self): ...\n def get_dsc(self): ...\n def get_diff(self): ...\n def get_pool_path(self): ...\n def get_package_name(self): ...\n def _parse_section(self, section): ...\n def validate(self, check_hash='md5', keyring=None): ...\n def validate_signature(self, keyring): ...\n def validate_checksums(self, check_hash='md5'): ...\n\n self.is_python3 = False\n", "repository": "opencollab/debile", "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": [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": "debile/master/changes.py", "focal_class": null, "focal_method": "validate_signature", "tests": "import unittest\n\nclass Test_validate_signature(unittest.TestCase):\n @mock.patch('debile.master.changes.run_command', return_value=('[GNUPG:] GOODSIG\\n[GNUPG:] VALIDSIG 000ABC345', 0, 0))\n @mock.patch('debile.master.changes.Changes.get_changes_file', return_value='debile.dsc')\n def test_validate_signature_with_valid_sign(self, mock, mock_changes):\n key = self.change.validate_signature('tests/resources/keyring')\n self.assertTrue(mock.is_called)\n self.assertEquals(key, '000ABC345')\n", "method_code": " def validate_signature(self, keyring):\n \"\"\"\n Validate the GPG signature of a .changes file.\n \n Throws a :class:`dput.exceptions.ChangesFileException` if there's\n an issue with the GPG signature. Returns the GPG key ID.\n \"\"\"\n gpg_output, gpg_output_stderr, exit_status = run_command(['gpg', '--batch', '--status-fd', '1', '--no-default-keyring', '--keyring', keyring, '--verify', self.get_changes_file()])\n if exit_status == -1:\n raise ChangesFileException('Unknown problem while verifying signature')\n if self.is_python3:\n gpg_output_stderr = str(gpg_output_stderr, encoding='utf8')\n if self.is_python3:\n gpg_output = gpg_output.decode(encoding='UTF-8')\n if gpg_output.count('[GNUPG:] GOODSIG'):\n pass\n elif gpg_output.count('[GNUPG:] BADSIG'):\n raise ChangesFileException('Bad signature')\n elif gpg_output.count('[GNUPG:] ERRSIG'):\n raise ChangesFileException('Error verifying signature')\n elif gpg_output.count('[GNUPG:] NODATA'):\n raise ChangesFileException('No signature on')\n else:\n raise ChangesFileException('Unknown problem while verifying signature')\n key = None\n for line in gpg_output.split('\\n'):\n if line.startswith('[GNUPG:] VALIDSIG'):\n key = line.split()[2]\n return key\n ", "context": "class Changes(object):\n def validate_signature(self, keyring): ...\n def __init__(self, filename=None, string=None): ...\n def is_source_only_upload(self): ...\n def is_binary_only_upload(self): ...\n def get_filename(self): ...\n def get_changes_file(self): ...\n def get_files(self): ...\n def __getitem__(self, key): ...\n def __contains__(self, key): ...\n def get(self, key, default=None): ...\n def get_component(self): ...\n def get_priority(self): ...\n def get_dsc_obj(self): ...\n def get_dsc(self): ...\n def get_diff(self): ...\n def get_pool_path(self): ...\n def get_package_name(self): ...\n def _parse_section(self, section): ...\n def validate(self, check_hash='md5', keyring=None): ...\n def validate_checksums(self, check_hash='md5'): ...\n\n self.is_python3 = False\n", "repository": "opencollab/debile", "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_000134.py"} {"focal_file": "debile/master/changes.py", "focal_class": null, "focal_method": "__getitem__", "tests": "import unittest\n\nclass Test_getitem(unittest.TestCase):\n @mock.patch('debile.utils.deb822.Changes', return_value={'distribution': 'unstable'})\n def test_get_item(self, mock):\n new_change = changes.Changes(string='Update package')\n self.assertEquals(new_change.__getitem__('distribution'), 'unstable')\n", "method_code": " def __getitem__(self, key):\n \"\"\"\n Returns the value of the rfc822 key specified.\n \n ``key``\n Key of data to request.\n \"\"\"\n return self._data[key]\n ", "context": "class Changes(object):\n def __getitem__(self, key): ...\n def __init__(self, filename=None, string=None): ...\n def is_source_only_upload(self): ...\n def is_binary_only_upload(self): ...\n def get_filename(self): ...\n def get_changes_file(self): ...\n def get_files(self): ...\n def __contains__(self, key): ...\n def get(self, key, default=None): ...\n def get_component(self): ...\n def get_priority(self): ...\n def get_dsc_obj(self): ...\n def get_dsc(self): ...\n def get_diff(self): ...\n def get_pool_path(self): ...\n def get_package_name(self): ...\n def _parse_section(self, section): ...\n def validate(self, check_hash='md5', keyring=None): ...\n def validate_signature(self, keyring): ...\n def validate_checksums(self, check_hash='md5'): ...\n\n self.is_python3 = False\n", "repository": "opencollab/debile", "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": [0, 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": "debile/master/changes.py", "focal_class": null, "focal_method": "__contains__", "tests": "import unittest\n\nclass Test_contains(unittest.TestCase):\n @mock.patch('debile.utils.deb822.Changes', return_value={'key': 'value'})\n def test_contains(self, mock):\n new_change = changes.Changes(string='Update package')\n self.assertTrue(new_change.__contains__('key'))\n", "method_code": " def __contains__(self, key):\n \"\"\"\n Returns whether the specified RFC822 key exists.\n \n ``key``\n Key of data to check for existence.\n \"\"\"\n return key in self._data\n ", "context": "class Changes(object):\n def __contains__(self, key): ...\n def __init__(self, filename=None, string=None): ...\n def is_source_only_upload(self): ...\n def is_binary_only_upload(self): ...\n def get_filename(self): ...\n def get_changes_file(self): ...\n def get_files(self): ...\n def __getitem__(self, key): ...\n def get(self, key, default=None): ...\n def get_component(self): ...\n def get_priority(self): ...\n def get_dsc_obj(self): ...\n def get_dsc(self): ...\n def get_diff(self): ...\n def get_pool_path(self): ...\n def get_package_name(self): ...\n def _parse_section(self, section): ...\n def validate(self, check_hash='md5', keyring=None): ...\n def validate_signature(self, keyring): ...\n def validate_checksums(self, check_hash='md5'): ...\n\n self.is_python3 = False\n", "repository": "opencollab/debile", "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": [0, 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": "debile/slave/wrappers/cppcheck.py", "focal_class": null, "focal_method": "parse_cppcheck", "tests": "import unittest\n\nclass Test_parse_cppcheck(unittest.TestCase):\n def test_cppcheck_wrappers(self):\n cpp_analysis = cppcheck(self.file_path, self.firehose_results)\n issues = parse_cppcheck(cpp_analysis[1])\n i = 0\n for issue in issues:\n if issue.testid == 'toomanyconfigs':\n found = issue\n i += 1\n self.assertEquals(found.testid, 'toomanyconfigs')\n self.assertEquals(found.location.file.givenpath, 'src/lib_json/json_value.cpp')\n self.assertEquals(found.location.point.line, 0)\n self.assertEquals(found.location.point.column, 0)\n self.assertEquals(found.severity, 'style')\n self.assertIsNone(found.notes)\n self.assertIsNone(found.customfields)\n self.assertTrue(i > 4)\n", "method_code": "def parse_cppcheck(payload):\n tree = lxml.etree.fromstring(payload.encode('utf-16'))\n for result in tree.xpath('//results/error'):\n if 'file' not in result.attrib:\n continue\n path = result.attrib['file']\n line = result.attrib['line']\n severity = result.attrib['severity']\n message = result.attrib['msg']\n testid = result.attrib['id']\n yield Issue(cwe=None, testid=testid, location=Location(file=File(path, None), function=None, point=Point(int(line), 0) if line else None), severity=severity, message=Message(text=message), notes=None, trace=None)", "context": "def parse_cppcheck(payload): ...\ndef parse_cppcheck(payload): ...\n", "repository": "opencollab/debile", "test_name": "test_cppcheck_wrappers", "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, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000137.py"} {"focal_file": "debile/master/dud.py", "focal_class": null, "focal_method": "get_firehose_file", "tests": "import unittest\n\nclass Test_get_firehose_file(unittest.TestCase):\n @mock.patch('debile.master.dud.Dud.get_files', return_value=['debile.firehose.xml'])\n def test_get_firehose_file(self, mock_get_files):\n self.assertEquals(self.dud.get_firehose_file(), 'debile.firehose.xml')\n", "method_code": " def get_firehose_file(self):\n for item in self.get_files():\n if item.endswith('.firehose.xml'):\n return item\n ", "context": "class Dud(object):\n def get_firehose_file(self): ...\n def __init__(self, filename=None, string=None): ...\n def get_filename(self): ...\n def get_dud_file(self): ...\n def get_firehose(self): ...\n def get_log_file(self): ...\n def get_files(self): ...\n def __getitem__(self, key): ...\n def __contains__(self, key): ...\n def get(self, key, default=None): ...\n def validate(self, check_hash='md5', keyring=None): ...\n def validate_signature(self, keyring): ...\n def validate_checksums(self, check_hash='md5'): ...\n\n self.is_python3 = False\n", "repository": "opencollab/debile", "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": [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": "debile/master/dud.py", "focal_class": null, "focal_method": "get_log_file", "tests": "import unittest\n\nclass Test_get_log_file(unittest.TestCase):\n @mock.patch('debile.master.dud.Dud.get_files', return_value=['debile.log'])\n def test_get_log_file(self, mock_get_files):\n self.assertEquals(self.dud.get_log_file(), 'debile.log')\n", "method_code": " def get_log_file(self):\n for item in self.get_files():\n if item.endswith('.log'):\n return item\n ", "context": "class Dud(object):\n def get_log_file(self): ...\n def __init__(self, filename=None, string=None): ...\n def get_filename(self): ...\n def get_dud_file(self): ...\n def get_firehose(self): ...\n def get_firehose_file(self): ...\n def get_files(self): ...\n def __getitem__(self, key): ...\n def __contains__(self, key): ...\n def get(self, key, default=None): ...\n def validate(self, check_hash='md5', keyring=None): ...\n def validate_signature(self, keyring): ...\n def validate_checksums(self, check_hash='md5'): ...\n\n self.is_python3 = False\n", "repository": "opencollab/debile", "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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000139.py"} {"focal_file": "debile/master/dud.py", "focal_class": null, "focal_method": "validate_signature", "tests": "import unittest\n\nclass Test_validate_signature(unittest.TestCase):\n @mock.patch('debile.master.dud.run_command', return_value=('[GNUPG:] GOODSIG\\n[GNUPG:] VALIDSIG 000ABC345', 0, 0))\n @mock.patch('debile.master.dud.Dud.get_dud_file', return_value='debile.dud')\n def test_validate_signature_with_valid_sign(self, mock_dud, mock):\n key = self.dud.validate_signature('tests/resources/keyring')\n self.assertTrue(mock.is_called)\n self.assertEquals(key, '000ABC345')\n", "method_code": " def validate_signature(self, keyring):\n \"\"\"\n Validate the GPG signature of a .changes file.\n \"\"\"\n gpg_output, gpg_output_stderr, exit_status = run_command(['gpg', '--batch', '--status-fd', '1', '--no-default-keyring', '--keyring', keyring, '--verify', self.get_dud_file()])\n if exit_status == -1:\n raise DudFileException('Unknown problem while verifying signature')\n if self.is_python3:\n gpg_output_stderr = str(gpg_output_stderr, encoding='utf8')\n if self.is_python3:\n gpg_output = gpg_output.decode(encoding='UTF-8')\n if gpg_output.count('[GNUPG:] GOODSIG'):\n pass\n elif gpg_output.count('[GNUPG:] BADSIG'):\n raise DudFileException('Bad signature')\n elif gpg_output.count('[GNUPG:] ERRSIG'):\n raise DudFileException('Error verifying signature')\n elif gpg_output.count('[GNUPG:] NODATA'):\n raise DudFileException('No signature on')\n else:\n raise DudFileException('Unknown problem while verifying signature')\n key = None\n for line in gpg_output.split('\\n'):\n if line.startswith('[GNUPG:] VALIDSIG'):\n key = line.split()[2]\n return key\n ", "context": "class Dud(object):\n def validate_signature(self, keyring): ...\n def __init__(self, filename=None, string=None): ...\n def get_filename(self): ...\n def get_dud_file(self): ...\n def get_firehose(self): ...\n def get_firehose_file(self): ...\n def get_log_file(self): ...\n def get_files(self): ...\n def __getitem__(self, key): ...\n def __contains__(self, key): ...\n def get(self, key, default=None): ...\n def validate(self, check_hash='md5', keyring=None): ...\n def validate_checksums(self, check_hash='md5'): ...\n\n self.is_python3 = False\n", "repository": "opencollab/debile", "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_000140.py"} {"focal_file": "debile/master/filerepo.py", "focal_class": null, "focal_method": "add_dud", "tests": "import unittest\n\nclass Test_add_dud(unittest.TestCase):\n @mock.patch('os.path.isdir', return_value=False)\n @mock.patch('os.makedirs')\n @mock.patch('debile.master.dud.Dud.get_dud_file', return_value=['debile.dud'])\n @mock.patch('debile.master.dud.Dud.get_files', return_value=['debile'])\n @mock.patch('shutil.copy2')\n @mock.patch('os.chmod')\n @mock.patch('os.path.basename', return_value='debile')\n def test_add_dud(self, mock_basename, mock_chmod, mock_copy, mock_get_files, mock_dud, mock_makedirs, mock_path):\n self.filerepo.add_dud('/tmp', self.dud, 666)\n self.assertTrue(mock_makedirs.called)\n self.assertTrue(mock_copy.called)\n args, _ = mock_copy.call_args\n self.assertEquals(args, ('debile', '/tmp'))\n self.assertTrue(mock_chmod.called)\n args, kwargs = mock_chmod.call_args\n self.assertEquals(args, ('/tmp/debile', 666))\n", "method_code": " def add_dud(self, path, dud, mode):\n if os.path.isdir(path):\n raise FilesAlreadyRegistered()\n os.makedirs(path)\n for fp in [dud.get_dud_file()] + dud.get_files():\n shutil.copy2(fp, path)\n os.chmod('%s/%s' % (path, os.path.basename(fp)), mode)\n ", "context": "class FileRepo(object):\n def add_dud(self, path, dud, mode): ...", "repository": "opencollab/debile", "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_000141.py"} {"focal_file": "tools/debile_slave_import_conf.py", "focal_class": null, "focal_method": "get_attribute_from_tarfile", "tests": "import unittest\n\nclass Test_get_attribute_from_tarfile(unittest.TestCase):\n def test_get_attribute_from_tarfile(self):\n with tarfile.open('tests/resources/blade01.tar.gz', 'r:gz') as tf:\n fingerprint = import_conf.get_attribute_from_tarfile('fingerprint', tf)\n name_tar = import_conf.get_attribute_from_tarfile('name', tf)\n self.assertEqual(fingerprint, self.key)\n self.assertEqual(name_tar, self.name)\n", "method_code": "def get_attribute_from_tarfile(attribute, tarfile):\n return tarfile.extractfile(attribute).read().strip()", "context": "def get_attribute_from_tarfile(attribute, tarfile): ...\ndef editconf(conf_dir): ...\ndef get_attribute_from_tarfile(attribute, tarfile): ...\ndef ensure_uid(user): ...\ndef import_pgp(user, pgp_key, key_type, keyring, gpg_home_dir): ...\ndef write_conf(conf_dir, name, key, auth_method): ...\ndef import_conf(user, conf_dir, tarball, keyring, secret_keyring, auth_method, gpg_home_dir): ...\ndef parse_args(args): ...\n", "repository": "opencollab/debile", "test_name": "test_get_attribute_from_tarfile", "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_000142.py"} {"focal_file": "tools/debile_slave_import_conf.py", "focal_class": null, "focal_method": "editconf", "tests": "import unittest\n\nclass Test_editconf(unittest.TestCase):\n def test_editconf(self):\n data = dict(A='a', B='b')\n self.write_yaml(data)\n with import_conf.editconf('/tmp/') as config:\n config['A'] = 'b'\n config['B'] = 'a'\n config['C'] = 'c'\n out = self.load_yaml()\n self.assertEqual(out['A'], 'b')\n self.assertEqual(out['B'], 'a')\n self.assertEqual(out['C'], 'c')\n", "method_code": "def editconf(conf_dir):\n where = conf_dir + 'slave.yaml'\n with open(where, 'r') as fd:\n info = yaml.load(fd)\n yield info\n with open(where, 'w') as fd:\n yaml.dump(info, fd)", "context": "@contextmanager\ndef editconf(conf_dir): ...\ndef editconf(conf_dir): ...\ndef get_attribute_from_tarfile(attribute, tarfile): ...\ndef ensure_uid(user): ...\ndef import_pgp(user, pgp_key, key_type, keyring, gpg_home_dir): ...\ndef write_conf(conf_dir, name, key, auth_method): ...\ndef import_conf(user, conf_dir, tarball, keyring, secret_keyring, auth_method, gpg_home_dir): ...\ndef parse_args(args): ...\n", "repository": "opencollab/debile", "test_name": "test_editconf", "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_000143.py"} {"focal_file": "tools/debile_slave_import_conf.py", "focal_class": null, "focal_method": "write_conf", "tests": "import unittest\n\nclass Test_write_conf(unittest.TestCase):\n def test_write_conf_ssl_auth(self):\n data = dict(xmlrpc=dict(host='localhost', port='22017'), gpg='00000')\n self.write_yaml(data)\n import_conf.write_conf('/tmp/', self.name, self.key, 'ssl')\n out = self.load_yaml()\n self.assertEqual(out['gpg'], self.key)\n self.assertEqual(out['xmlrpc']['keyfile'], '/tmp/blade01.key')\n self.assertEqual(out['xmlrpc']['certfile'], '/tmp/blade01.crt')\n self.assertEqual(out['xmlrpc']['auth_method'], 'ssl')\n", "method_code": "def write_conf(conf_dir, name, key, auth_method):\n with editconf(conf_dir) as config:\n config['gpg'] = key\n if 'xmlrpc' in config:\n xmlrpc = config['xmlrpc']\n if auth_method == 'ssl':\n xmlrpc['keyfile'] = conf_dir + name + '.key'\n xmlrpc['certfile'] = conf_dir + name + '.crt'\n xmlrpc['auth_method'] = 'ssl'\n print(\"WARNING: I haven't copied the x.509 key and certificateto {0} and {1}\".format(xmlrpc['keyfile'], xmlrpc['certfile']))\n print('Please copy those files manually, run `debile-slave-import-cred`, or patch this script to handle those two files')\n print('That last solution is best. See https://github.com/opencollab/debile/issues/4')\n elif auth_method == 'simple':\n xmlrpc['auth_method'] = 'simple'", "context": "def write_conf(conf_dir, name, key, auth_method): ...\ndef editconf(conf_dir): ...\ndef get_attribute_from_tarfile(attribute, tarfile): ...\ndef ensure_uid(user): ...\ndef import_pgp(user, pgp_key, key_type, keyring, gpg_home_dir): ...\ndef write_conf(conf_dir, name, key, auth_method): ...\ndef import_conf(user, conf_dir, tarball, keyring, secret_keyring, auth_method, gpg_home_dir): ...\ndef parse_args(args): ...\n", "repository": "opencollab/debile", "test_name": "test_write_conf_ssl_auth", "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_000144.py"} {"focal_file": "tools/debile_slave_import_conf.py", "focal_class": null, "focal_method": "import_conf", "tests": "import unittest\n\nclass Test_import_conf(unittest.TestCase):\n def test_import_conf_simple_auth(self):\n conf_dir = '/tmp/'\n tarball = 'tests/resources/blade01.tar.gz'\n auth_method = 'simple'\n data = dict(xmlrpc=dict(host='localhost', port='22017'), gpg='00000')\n self.write_yaml(data)\n import_conf.import_conf(self.user, conf_dir, tarball, self.keyring, self.secret_keyring, auth_method, self.gpg_home)\n out = self.load_yaml()\n self.assertEqual(out['gpg'], self.key)\n public_out, _, _ = run_command(['gpg', '--list-keys', '--keyring', self.keyring])\n secret_out, _, _ = run_command(['gpg', '--list-keys', '--keyring', self.secret_keyring])\n self.assertTrue('Debile Autobuilder (Debile Slave Key (blade01))' in public_out)\n self.assertTrue('Debile Autobuilder (Debile Slave Key (blade01))' in secret_out)\n\n def test_import_conf_ssl_auth(self):\n conf_dir = '/tmp/'\n tarball = 'tests/resources/blade01.tar.gz'\n auth_method = 'ssl'\n data = dict(xmlrpc=dict(host='localhost', port='22017'), gpg='00000')\n self.write_yaml(data)\n import_conf.import_conf(self.user, conf_dir, tarball, self.keyring, self.secret_keyring, auth_method, self.gpg_home)\n out = self.load_yaml()\n self.assertEqual(out['gpg'], self.key)\n self.assertEqual(out['xmlrpc']['keyfile'], '/tmp/blade01.key')\n self.assertEqual(out['xmlrpc']['certfile'], '/tmp/blade01.crt')\n public_out, _, _ = run_command(['gpg', '--list-keys', '--keyring', self.keyring])\n secret_out, _, _ = run_command(['gpg', '--list-keys', '--keyring', self.secret_keyring])\n self.assertTrue('Debile Autobuilder (Debile Slave Key (blade01))' in public_out)\n self.assertTrue('Debile Autobuilder (Debile Slave Key (blade01))' in secret_out)\n", "method_code": "def import_conf(user, conf_dir, tarball, keyring, secret_keyring, auth_method, gpg_home_dir):\n \"\"\"\n Import the slave configuration from the tarball.\n :param str auth: authentication method (ssl or simple)\n :param str conf_dir: path to the debile configuration\n :param str auth_method: authentication backend (ssl or simple)\n\n \"\"\"\n with tarfile.open(tarball, 'r:gz') as tf:\n name = get_attribute_from_tarfile('name', tf)\n key = get_attribute_from_tarfile('fingerprint', tf)\n write_conf(conf_dir, name, key, auth_method)\n import_pgp(user, get_attribute_from_tarfile('key.pub', tf), 'public', keyring, gpg_home_dir)\n import_pgp(user, get_attribute_from_tarfile('key.priv', tf), 'secret', secret_keyring, gpg_home_dir)", "context": "def import_conf(user, conf_dir, tarball, keyring, secret_keyring, auth_method, gpg_home_dir): ...\ndef editconf(conf_dir): ...\ndef get_attribute_from_tarfile(attribute, tarfile): ...\ndef ensure_uid(user): ...\ndef import_pgp(user, pgp_key, key_type, keyring, gpg_home_dir): ...\ndef write_conf(conf_dir, name, key, auth_method): ...\ndef import_conf(user, conf_dir, tarball, keyring, secret_keyring, auth_method, gpg_home_dir): ...\ndef parse_args(args): ...\n", "repository": "opencollab/debile", "test_name": "test_import_conf_simple_auth", "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_000145.py"} {"focal_file": "debile/master/interface.py", "focal_class": null, "focal_method": "create_builder", "tests": "import unittest\n\nclass Test_create_builder(unittest.TestCase):\n def test_create_builder(self):\n self.interface.create_builder('blade01', self.blade01_key, ip='10.0.0.1')\n b = self.session.query(Builder).filter_by(name='blade01').one()\n assert b.ssl is None\n assert b.ip == '10.0.0.1'\n assert b.pgp == '7C367D02AF6D20DCF2BFB686E8D62122F818733D'\n", "method_code": " def create_builder(self, name, pgp, ssl=None, ip=None):\n \"\"\"\n :param str name: name of the builder\n :param str pgp: path to the pgp public keyfile\n :param str ssl: path to the ssl certificate\n :param str ip: ip address of the builder\n \"\"\"\n if NAMESPACE.session.query(Builder).filter_by(name=name).first():\n raise ValueError('Slave already exists.')\n pgp = import_pgp(self.pgp_keyring, pgp)\n if ssl is not None:\n ssl = import_ssl(self.ssl_keyring, ssl, name)\n b = Builder(name=name, maintainer=NAMESPACE.user, pgp=pgp, ssl=ssl, last_ping=datetime.utcnow())\n elif ip is not None:\n b = Builder(name=name, maintainer=NAMESPACE.user, pgp=pgp, ip=ip, last_ping=datetime.utcnow())\n else:\n raise ValueError('Need either ssl certificate or ip address')\n NAMESPACE.session.add(b)\n emit('create', 'slave', b.debilize())\n return b.debilize()\n ", "context": "class DebileMasterInterface(object):\n @user_method\n def create_builder(self, name, pgp, ssl=None, ip=None): ...\n def __init__(self, ssl_keyring=None, pgp_keyring=None): ...\n def builder_whoami(self): ...\n def user_whoami(self): ...\n def get_next_job(self, suites, components, arches, checks): ...\n def close_job(self, job_id, failed): ...\n def forfeit_job(self, job_id): ...\n def get_group(self, group_id): ...\n def get_source(self, source_id): ...\n def get_binary(self, binary_id): ...\n def get_job(self, job_id): ...\n def update_builder_keys(self, name, pgp, ssl): ...\n def disable_builder(self, name): ...\n def create_user(self, name, email, pgp, ssl=None, ip=None): ...\n def update_user_keys(self, email, pgp, ssl): ...\n def disable_user(self, email): ...\n def rerun_job(self, job_id): ...\n def rerun_check(self, name): ...\n def retry_failed(self): ...\n def set_check(self, check, *args): ...\n def enable_check(self, check, group, suite): ...\n def list_checks(self, *args): ...\n\n self.ssl_keyring = ssl_keyring\n self.pgp_keyring = pgp_keyring\n\n shutdown_request = False\n", "repository": "opencollab/debile", "test_name": "test_create_builder", "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_000146.py"} {"focal_file": "debile/master/keyrings.py", "focal_class": null, "focal_method": "import_pgp", "tests": "import unittest\n\nclass Test_import_pgp(unittest.TestCase):\n @mock.patch('debile.master.keyrings.run_command', return_value=('[GNUPG:] IMPORT_OK KEY 000XXX000', 0, 0))\n def test_import_pgp_successful(self, mock):\n fingerprint = import_pgp('keyring', 'data')\n self.assertEquals(fingerprint, '000XXX000')\n", "method_code": "def import_pgp(keyring, keydata):\n \"\"\"\n keydata should be public key data to be imported to the keyring.\n The return value will be the sha1 fingerprint of the public key added.\n \"\"\"\n out, err, ret = run_command(['gpg', '--batch', '--status-fd', '1', '--no-default-keyring', '--keyring', keyring, '--import'], input=keydata)\n fingerprint = None\n for line in out.split('\\n'):\n data = line.split()\n if not data or data[0] != '[GNUPG:]':\n continue\n if data[1] == 'IMPORT_OK':\n fingerprint = data[3]\n break\n else:\n raise ValueError('GPG failed to import pgp public key')\n return fingerprint", "context": "def import_pgp(keyring, keydata): ...\ndef import_pgp(keyring, keydata): ...\ndef import_ssl(keyring, certdata, cn=None, email=None): ...\ndef clean_ssl_keyring(keyring, session): ...\n", "repository": "opencollab/debile", "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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000147.py"} {"focal_file": "debile/master/keyrings.py", "focal_class": null, "focal_method": "import_ssl", "tests": "import unittest\n\nclass Test_import_ssl(unittest.TestCase):\n @mock.patch('debile.master.keyrings.run_command', return_value=('subject=emailAddress=email2\\nSHA1 Fingerprint=00XX00', 0, 0))\n def test_import_ssl_successful(self, mock):\n fingerprint = import_ssl('tests/resources/keyring', 'certdata')\n os.remove('tests/resources/keyring')\n self.assertEquals(fingerprint, '00XX00')\n", "method_code": "def import_ssl(keyring, certdata, cn=None, email=None):\n \"\"\"\n certdata should be pem-formated certificate data to be added to the\n keyring. The return value will be the sha1 fingerprint of the certificate\n added.\n \"\"\"\n out, err, ret = run_command(['openssl', 'x509', '-noout', '-inform', 'pem', '-sha1', '-fingerprint', '-subject'], input=certdata)\n fingerprint = None\n subject = None\n for line in out.split('\\n'):\n data = line.split('=', 1)\n if data[0] == 'SHA1 Fingerprint':\n fingerprint = data[1].replace(':', '')\n if data[0] == 'subject':\n subject = data[1].split('/')\n if fingerprint is None or subject is None:\n raise ValueError('OpensSSL failed to parse ssl certificate.')\n if cn and (not 'CN={cn}'.format(cn=cn) in subject) or (email and (not 'emailAddress={email}'.format(email=email) in subject)):\n raise ValueError('Incorrect subject of ssl certificate (cn=\"%s\", emailAddress=\"%s\", subject=\"%s\")' % (cn, email, subject))\n keyring = open(keyring, 'a')\n fcntl.lockf(keyring, fcntl.LOCK_EX)\n keyring.write(certdata)\n keyring.close()\n return fingerprint", "context": "def import_ssl(keyring, certdata, cn=None, email=None): ...\ndef import_pgp(keyring, keydata): ...\ndef import_ssl(keyring, certdata, cn=None, email=None): ...\ndef clean_ssl_keyring(keyring, session): ...\n", "repository": "opencollab/debile", "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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000148.py"} {"focal_file": "debile/slave/wrappers/lintian.py", "focal_class": null, "focal_method": "parse_lintian", "tests": "import unittest\n\nclass Test_parse_lintian(unittest.TestCase):\n def test_lintian_wrappers(self):\n lintian_analysis = lintian(self.filepath, self.firehose_results)\n issues = parse_lintian(lintian_analysis[1].splitlines(), self.filepath)\n i = 0\n for issue in issues:\n if issue.testid == 'no-symbols-control-file':\n found = issue\n i += 1\n self.assertEquals(found.testid, 'no-symbols-control-file')\n self.assertEquals(found.location.file.givenpath, 'tests/resources/libjsoncpp0_0.6.0~rc2-3.1_amd64.deb')\n self.assertIsNone(found.location.point)\n self.assertEquals(found.severity, 'info')\n self.assertIsNone(found.notes)\n self.assertIsNone(found.customfields)\n self.assertTrue('libjsoncpp0: no-symbols-control-file usr/lib/libjsoncpp.so.0.6.0' in found.message.text)\n self.assertTrue(i > 1)\n", "method_code": "def parse_lintian(lines, fpath):\n severities = {'w': 'warning', 'e': 'error', 'p': 'pedantic', 'i': 'info', 'x': 'experimental', 'o': 'override'}\n for line in lines:\n if line.startswith('N:'):\n continue\n info = LINE_RE.match(line).groupdict()\n severity = info['severity'].lower()\n if severity in severities:\n severity = severities[severity]\n else:\n severity = severity.upper()\n yield Issue(cwe=None, testid=info['testid'], location=Location(file=File(fpath, None), function=None, point=None), severity=severity, message=Message(text=line), notes=None, trace=None)", "context": "def parse_lintian(lines, fpath): ...\ndef parse_lintian(lines, fpath): ...\n", "repository": "opencollab/debile", "test_name": "test_lintian_wrappers", "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_000149.py"} {"focal_file": "debile/master/utils.py", "focal_class": null, "focal_method": "_init_config", "tests": "import unittest\n\nclass Test_init_config(unittest.TestCase):\n def test_init_config(self):\n config = utils._init_config('tests/resources/master.yaml')\n self.assertEquals(config['database'], 'sqlite:////srv/debile/debile.db')\n self.assertIsNotNone(config['fedmsg'])\n self.assertIsNotNone(config['xmlrpc'])\n self.assertIsNotNone(config['repo'])\n self.assertIsNotNone(config['keyrings'])\n", "method_code": "def _init_config(path):\n config.update(get_config(name='master.yaml', path=path))\n return config", "context": "def _init_config(path): ...\ndef _init_config(path): ...\ndef _init_sqlalchemy(config): ...\ndef _init_fedmsg(config): ...\ndef init_master(confpath=None, fedmsg=True): ...\ndef session(): ...\ndef emit(topic, modname, message): ...\n", "repository": "opencollab/debile", "test_name": "test_init_config", "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_000150.py"} {"focal_file": "debile/master/utils.py", "focal_class": null, "focal_method": "_init_sqlalchemy", "tests": "import unittest\n\nclass Test_init_sqlalchemy(unittest.TestCase):\n @mock.patch('debile.master.utils.create_engine')\n @mock.patch('debile.master.utils.Session.configure')\n def test_init_sqlalchemy(self, mock_configure, mock_engine):\n config = {'database': 'sqlite:////srv/debile/debile.db'}\n utils._init_sqlalchemy(config)\n self.assertTrue(mock_engine.called)\n self.assertTrue(mock_configure.called)\n args, kwargs = mock_engine.call_args\n self.assertEquals(args, ('sqlite:////srv/debile/debile.db',))\n self.assertFalse(kwargs['implicit_returning'])\n", "method_code": "def _init_sqlalchemy(config):\n engine = create_engine(config['database'], implicit_returning=False)\n Session.configure(bind=engine)", "context": "def _init_sqlalchemy(config): ...\ndef _init_config(path): ...\ndef _init_sqlalchemy(config): ...\ndef _init_fedmsg(config): ...\ndef init_master(confpath=None, fedmsg=True): ...\ndef session(): ...\ndef emit(topic, modname, message): ...\n", "repository": "opencollab/debile", "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_000151.py"} {"focal_file": "debile/master/reprepro.py", "focal_class": null, "focal_method": "add_changes", "tests": "import unittest\n\nclass Test_add_changes(unittest.TestCase):\n @mock.patch('debile.utils.deb822.Changes', return_value={'distribution': 'unstable'})\n @mock.patch('debile.master.reprepro.Repo.include')\n @mock.patch('debile.master.changes.Changes.get_changes_file', return_value='mock.dsc')\n def test_add_changes(self, mock_changes, mock_reprepro, mock):\n changes = Changes(string='Some change')\n self.repo.add_changes(changes)\n args, _ = mock_reprepro.call_args\n self.assertEquals(args, ('unstable', 'mock.dsc'))\n", "method_code": " def add_changes(self, changes):\n dist = changes['distribution']\n self.include(dist, changes.get_changes_file())\n ", "context": "class Repo(object):\n def add_changes(self, changes): ...\n def __init__(self, root): ...\n def _exec(self, *args): ...\n def include(self, distribution, changes): ...\n def includedeb(self, distribution, deb): ...\n def includeudeb(self, distribution, udeb): ...\n def includedsc(self, distributions, dsc): ...\n def list(self, distribution, name): ...\n def clearvanished(self): ...\n def find_dsc(self, source): ...\n\n self.root = root\n", "repository": "opencollab/debile", "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": [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": "debile/master/reprepro.py", "focal_class": null, "focal_method": "include", "tests": "import unittest\n\nclass Test_include(unittest.TestCase):\n @mock.patch('debile.master.reprepro.run_command', return_value=(0, 0, 0))\n def test_include(self, mock):\n out, stderr, ret = self.repo.include('unstable', 'test.changes')\n self.assertTrue(mock.called)\n self.assertEquals((out, stderr, ret), (0, 0, 0))\n", "method_code": " def include(self, distribution, changes):\n try:\n return self._exec('include', distribution, changes)\n except RepoException as e:\n error = e.message\n if error == 254:\n raise RepoSourceAlreadyRegistered()\n raise\n ", "context": "class Repo(object):\n def include(self, distribution, changes): ...\n def __init__(self, root): ...\n def add_changes(self, changes): ...\n def _exec(self, *args): ...\n def includedeb(self, distribution, deb): ...\n def includeudeb(self, distribution, udeb): ...\n def includedsc(self, distributions, dsc): ...\n def list(self, distribution, name): ...\n def clearvanished(self): ...\n def find_dsc(self, source): ...\n\n self.root = root\n", "repository": "opencollab/debile", "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_000153.py"} {"focal_file": "debile/utils/commands.py", "focal_class": null, "focal_method": "run_command", "tests": "import unittest\n\nclass Test_run_command(unittest.TestCase):\n def test_run_command_wrong_one(self):\n output, output_stderr, exit_status = run_command('ls2')\n self.assertNotEqual(exit_status, 0)\n\n def test_run_command_simple_one(self):\n output, output_stderr, exit_status = run_command(['echo', 'hello'])\n self.assertEqual(exit_status, 0)\n\n def test_run_command_without_list(self):\n output, output_stderr, exit_status = run_command('echo -e hello\\nworld')\n self.assertEqual(exit_status, 0)\n\n def test_run_command_with_input(self):\n command_input = 'test run command'\n output, output_stderr, exit_status = run_command('cat', command_input)\n self.assertEqual(output, 'test run command')\n self.assertEqual(exit_status, 0)\n", "method_code": "def run_command(command, input=None):\n if not isinstance(command, list):\n command = shlex.split(command)\n if not input:\n input = None\n elif isinstance(input, unicode_type):\n input = input.encode('utf-8')\n elif not isinstance(input, binary_type):\n input = input.read()\n try:\n pipe = subprocess.Popen(command, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n except OSError:\n return (None, None, -1)\n output, stderr = pipe.communicate(input=input)\n output, stderr = (c.decode('utf-8', errors='ignore') for c in (output, stderr))\n return (output, stderr, pipe.returncode)", "context": "def run_command(command, input=None): ...\ndef run_command(command, input=None): ...\ndef safe_run(cmd, input=None, expected=0): ...\n", "repository": "opencollab/debile", "test_name": "test_run_command_wrong_one", "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_000154.py"} {"focal_file": "debile/utils/commands.py", "focal_class": null, "focal_method": "safe_run", "tests": "import unittest\n\nclass Test_safe_run(unittest.TestCase):\n def test_safe_run_simple(self):\n output, output_stderr, exit_status = safe_run('ls', expected=0)\n self.assertEqual(exit_status, 0)\n", "method_code": "def safe_run(cmd, input=None, expected=0):\n if not isinstance(expected, tuple):\n expected = (expected,)\n out, err, ret = run_command(cmd, input=input)\n if ret not in expected:\n raise SubprocessError(out, err, ret, cmd)\n return (out, err, ret)", "context": "def safe_run(cmd, input=None, expected=0): ...\ndef run_command(command, input=None): ...\ndef safe_run(cmd, input=None, expected=0): ...\n", "repository": "opencollab/debile", "test_name": "test_safe_run_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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000155.py"} {"focal_file": "debile/utils/config.py", "focal_class": null, "focal_method": "_find_config_file", "tests": "import unittest\n\nclass Test_find_config_file(unittest.TestCase):\n def test_find_config_file_that_exists(self):\n found_file = config_utils._find_config_file('config.yaml')\n self.assertEqual(found_file, self.config)\n", "method_code": "def _find_config_file(name):\n dirs = [os.getenv('XDG_CONFIG_HOME', os.path.expanduser('~/.config'))]\n dirs += os.getenv('XDG_CONFIG_DIRS', '/etc/xdg').split(':')\n dirs += ['/etc']\n for dir in dirs:\n file = '{dir}/debile/{name}'.format(dir=dir, name=name)\n if os.path.isfile(file):\n return file\n raise Exception('Could not find %s' % name)", "context": "def _find_config_file(name): ...\ndef _find_config_file(name): ...\ndef get_config(name, path=None): ...\n", "repository": "opencollab/debile", "test_name": "test_find_config_file_that_exists", "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_000156.py"} {"focal_file": "debile/utils/config.py", "focal_class": null, "focal_method": "get_config", "tests": "import unittest\n\nclass Test_get_config(unittest.TestCase):\n def test_get_config(self):\n file_content = config_utils.get_config('config.yaml')\n self.assertEqual(file_content['A'], 'a')\n", "method_code": "def get_config(name, path=None):\n with open(path or _find_config_file(name), 'r') as f:\n return yaml.safe_load(f)", "context": "def get_config(name, path=None): ...\ndef _find_config_file(name): ...\ndef get_config(name, path=None): ...\n", "repository": "opencollab/debile", "test_name": "test_get_config", "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_000157.py"} {"focal_file": "debile/utils/xmlrpc.py", "focal_class": null, "focal_method": "get_proxy", "tests": "import unittest\n\nclass Test_get_proxy(unittest.TestCase):\n def test_get_proxy_simple_auth(self):\n data = dict(xmlrpc=dict(host='localhost', port='22017'))\n proxy = get_proxy(data, 'simple')\n self.assertEquals(proxy.__dict__['_ServerProxy__host'], 'localhost:22017')\n self.assertTrue(proxy.__dict__['_ServerProxy__allow_none'])\n\n def test_get_proxy_ssl_auth(self):\n data = dict(xmlrpc=dict(host='localhost', port='22017', keyfile='~/keyfile.key', certfile='~/certfile.crt'))\n proxy = get_proxy(data, 'ssl')\n self.assertEquals(proxy.__dict__['_ServerProxy__host'], 'localhost:22017')\n self.assertTrue(proxy.__dict__['_ServerProxy__allow_none'])\n self.assertIsInstance(proxy.__dict__['_ServerProxy__transport'], DebileSafeTransport)\n", "method_code": "def get_proxy(config, auth_method):\n xml = config.get('xmlrpc', None)\n if xml is None:\n raise Exception('No xmlrpc found in slave yaml')\n proxy = None\n if auth_method == 'simple':\n proxy = xmlrpclib.ServerProxy('http://{host}:{port}/'.format(host=xml['host'], port=xml['port']), allow_none=True)\n else:\n proxy = xmlrpclib.ServerProxy('https://{host}:{port}/'.format(host=xml['host'], port=xml['port']), transport=DebileSafeTransport(key_file=xml.get('keyfile', None), cert_file=xml.get('certfile', None), ca_certs=xml.get('ca_certs', '/etc/ssl/certs/ca-certificates.crt')), allow_none=True)\n return proxy", "context": "def get_proxy(config, auth_method): ...\ndef get_host_list(cert): ...\ndef validate(cert, hostname): ...\ndef get_proxy(config, auth_method): ...\ndef get_auth_method(args, config): ...\n", "repository": "opencollab/debile", "test_name": "test_get_proxy_simple_auth", "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_000158.py"} {"focal_file": "footballscoring/gameclock.py", "focal_class": "GameClock", "focal_method": "toggle", "tests": "import unittest\n\nclass Test_GameClock_toggle(unittest.TestCase):\n def testClockToggle(self):\n print('Testing toggling clock...')\n game_clock = GameClock(1)\n self.assertEqual(game_clock.running, False)\n game_clock.toggle()\n self.assertEqual(game_clock.running, True)\n game_clock.toggle()\n self.assertEqual(game_clock.running, False)\n", "method_code": " def toggle(self):\n \"\"\"Toggles the current running status of the clock.\n \n Args:\n None\n Returns:\n None\n \"\"\"\n self.running = not self.running\n ", "context": "class GameClock():\n def toggle(self): ...\n def __init__(self, quarter_length, interval_ms=10): ...\n def change_quarter_length(self, quarter_length): ...\n def reset_clock(self, stop_clock=True): ...\n def set_clock(self, minutes, seconds, stop_clock=True): ...\n def start(self): ...\n def stop(self): ...\n def process_clock(self): ...\n\n self.running = False\n self.remaining_time = timedelta(minutes=quarter_length)\n self.previous_update_time = None\n self.interval_ms = interval_ms\n self.scheduler = BackgroundScheduler()\n", "repository": "zapfdk/pyfootballscoring", "test_name": "testClockToggle", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0], "smell_labels": ["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, 1, 0, 1, 0, 0], "pynose_source_file": "test_000159.py"} {"focal_file": "footballscoring/gamestate.py", "focal_class": null, "focal_method": "reset_first_down", "tests": "import unittest\n\nclass Test_reset_first_down(unittest.TestCase):\n def testResetFirstDown(self):\n print('Testing resetting first down...')\n self.game_state.set_state_property('down', 3)\n self.game_state.set_state_property('distance', 9)\n self.game_state.reset_first_down()\n self.assertEqual(self.game_state.state['down'], 1)\n self.assertEqual(self.game_state.state['distance'], 10)\n", "method_code": " def reset_first_down(self):\n \"\"\"Resets state to first down and 10 yds distance.\n \n Args:\n None\n Returns:\n None\n \"\"\"\n self.state['down'] = 1\n self.state['distance'] = 10\n ", "context": "class GameState():\n def reset_first_down(self): ...\n def __init__(self): ...\n def init_game(self): ...\n def reset_half(self, half=2): ...\n def modify_state_property(self, var_to_set, value, team=None): ...\n def check_team_property(self, var_to_set, team): ...\n def set_state_property(self, var_to_set, value, team=None): ...\n", "repository": "zapfdk/pyfootballscoring", "test_name": "testResetFirstDown", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "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_000160.py"} {"focal_file": "footballscoring/gamestate.py", "focal_class": null, "focal_method": "modify_state_property", "tests": "import unittest\n\nclass Test_modify_state_property(unittest.TestCase):\n def testModifyingStateProperty(self):\n print('Testing incrementation and decrementation of state properties...')\n self.assertRaises(ValueError, self.game_state.modify_state_property, 'down', -1)\n for action in ['down', 'distance', 'quarter', 'ball_on']:\n self.game_state.modify_state_property(action, value=1)\n self.assertEqual(self.game_state.state['down'], 2)\n self.assertEqual(self.game_state.state['distance'], 11)\n self.assertEqual(self.game_state.state['quarter'], 2)\n self.assertEqual(self.game_state.state['ball_on'], 36)\n for action in ['down', 'distance', 'quarter', 'ball_on']:\n self.game_state.modify_state_property(action, value=-1)\n self.assertEqual(self.game_state.state['down'], 1)\n self.assertEqual(self.game_state.state['distance'], 10)\n self.assertEqual(self.game_state.state['quarter'], 1)\n self.assertEqual(self.game_state.state['ball_on'], 35)\n self.game_state.modify_state_property('score', Score.TOUCHDOWN, team=Team.HOME)\n self.assertEqual(self.game_state.state['score'][Team.HOME], 6)\n self.game_state.modify_state_property('score', Score.FIELDGOAL, team=Team.GUEST)\n self.assertEqual(self.game_state.state['score'][Team.GUEST], 3)\n self.game_state.modify_state_property('timeouts', -1, team=Team.HOME)\n self.assertEqual(self.game_state.state['timeouts'][Team.HOME], 2)\n self.game_state.modify_state_property('timeouts', -2, team=Team.GUEST)\n self.assertEqual(self.game_state.state['timeouts'][Team.GUEST], 1)\n self.assertRaises(ValueError, self.game_state.modify_state_property, 'timeouts', -2, Team.GUEST)\n", "method_code": " def modify_state_property(self, var_to_set, value, team=None):\n \"\"\"Increase or decrease property. Checks if property to set is a team property. \n \n Args:\n var_to_set (str): The property you want to modify.\n value (int): The value you want to increase or decrease the property by. For decrementation, simply pass a negative value.\n team (int, optional): If the property is a team property, you can specify the team here. \n Returns: \n None\n \"\"\"\n if self.check_team_property(var_to_set, team):\n current_property_value = self.state[var_to_set][team]\n new_property_value = current_property_value + value\n if Constraints.check_constraint(var_to_set, new_property_value):\n self.state[var_to_set][team] = new_property_value\n else:\n current_property_value = self.state[var_to_set]\n new_property_value = current_property_value + value\n if Constraints.check_constraint(var_to_set, new_property_value):\n self.state[var_to_set] = new_property_value\n ", "context": "class GameState():\n def modify_state_property(self, var_to_set, value, team=None): ...\n def __init__(self): ...\n def init_game(self): ...\n def reset_first_down(self): ...\n def reset_half(self, half=2): ...\n def check_team_property(self, var_to_set, team): ...\n def set_state_property(self, var_to_set, value, team=None): ...\n", "repository": "zapfdk/pyfootballscoring", "test_name": "testModifyingStateProperty", "smells": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 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, 1, 0, 0, 0, 0], "pynose_source_file": "test_000161.py"} {"focal_file": "pathmap/cykloserver.py", "focal_class": null, "focal_method": "_get_js_output", "tests": "import unittest\n\nclass Test_get_js_output(unittest.TestCase):\n def test__get_js_output_known_values(self):\n \"\"\"_get_js_output should give known output for known input\"\"\"\n known_pairs = [('', ''), ('1+2', ''), ('console.log(1+2)', '3'), ('\\n n = 1;\\n for (i = 0; i < 10; i++) {\\n n += 1;\\n }\\n console.log(n)\\n ', '11')]\n for inp, out in known_pairs:\n self.assertEqual(self.c._get_js_output(inp).strip(), out)\n", "method_code": " def _get_js_output(self, script):\n \"\"\"Run script in nodejs and return its output\"\"\"\n process = subprocess.Popen(['nodejs'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n return process.communicate(input=script.encode('utf8'))[0].decode('utf8')\n ", "context": "class CykloserverMapDownloader(MapDownloader):\n def _get_js_output(self, script): ...\n def __init__(self): ...\n def _url2dict(self, url): ...\n def _renew_token(self): ...\n def lon_lat_to_tiles(self, lon, lat): ...\n def _download_tile(self, x, y, filename): ...\n def _tile_filename(self, x, y): ...\n def get_tile(self, x, y): ...\n def gpx2path(self, filename): ...\n\n self.s = requests.Session()\n self.xres = 256\n self.yres = 256\n self.last_token_acquired = 0\n self.proj_to = pyproj.Proj('+init=EPSG:3857')\n self.proj_from = pyproj.Proj('+init=EPSG:4326')\n self.bx = [4095.9754, 0.000204431397]\n self.by = [4095.71512, -0.000204373254]\n self._renew_lock = Lock()\n", "repository": "nimral/pathmap", "test_name": "test__get_js_output_known_values", "smells": [0, 1, 0, 0, 0, 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": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000162.py"} {"focal_file": "pathmap/cykloserver.py", "focal_class": null, "focal_method": "_renew_token", "tests": "import unittest\n\nclass Test_renew_token(unittest.TestCase):\n def test__renew_token(self):\n \"\"\"should get 200 OK on http://webtiles.timepress.cz/cyklo_256/13/4493/2803\n\n after running _renew_token, that is\n \"\"\"\n self.c._renew_token()\n url = 'http://webtiles.timepress.cz/cyklo_256/13/4493/2803'\n self.assertEqual(self.c.s.get(url).status_code, 200)\n", "method_code": " def _renew_token(self):\n \"\"\"Prepare requests.Session self.s for subsequent downloading of\n tiles\n \"\"\"\n if self.s:\n self.s.close()\n self.s = requests.Session()\n url_atlas = 'http://www.cykloserver.cz/cykloatlas/'\n r_atlas = self.s.get(url_atlas)\n root = html.fromstring(r_atlas.content)\n url = [x for x in root.xpath('.//script') if x.get('src') and 'readauthloader2' in x.get('src')][0].get('src')\n self.atributes = self._url2dict(url)['atributes']\n self.s.get('http://www.cykloserver.cz/cykloatlas/readautha4b2.php', params=self.atributes)\n script = self.s.post('http://www.cykloserver.cz/cykloatlas/tagetpass2.php', data=self.atributes).content.decode('utf8')\n script += 'console.log(_tt_pass)'\n tt_pass = self._get_js_output(script).strip()\n atributes = self.atributes.copy()\n atributes['pass'] = tt_pass\n script_parts = []\n script_parts.append(\"\\n function __tt_descramble(data) {\\n var res = '';\\n \\n var pos = 0;\\n \\n var chnk = data.substr(pos, 3);\\n while (chnk.length == 3) {\\n res+= String.fromCharCode(Number(chnk));\\n \\n pos+= 3;\\n chnk = data.substr(pos, 3);\\n }\\n \\n return res;\\n }\")\n script_parts.append(self.s.post('http://www.cykloserver.cz/cykloatlas/tagettoken2.php', data=atributes).content.decode('utf8'))\n script_parts.append('\\n console.log(__tt_tokenm)\\n console.log(__tt_tokent)\\n console.log(__tt_tokenk)\\n ')\n tt_tokenm, tt_tokent, tt_tokenk = self._get_js_output('\\n'.join(script_parts)).split()\n self.s.get('http://webtiles.timepress.cz/set_token', params={'token': tt_tokenk}).content.decode('utf8')\n ", "context": "class CykloserverMapDownloader(MapDownloader):\n def _renew_token(self): ...\n def __init__(self): ...\n def _get_js_output(self, script): ...\n def _url2dict(self, url): ...\n def lon_lat_to_tiles(self, lon, lat): ...\n def _download_tile(self, x, y, filename): ...\n def _tile_filename(self, x, y): ...\n def get_tile(self, x, y): ...\n def gpx2path(self, filename): ...\n\n self.s = requests.Session()\n self.xres = 256\n self.yres = 256\n self.last_token_acquired = 0\n self.proj_to = pyproj.Proj('+init=EPSG:3857')\n self.proj_from = pyproj.Proj('+init=EPSG:4326')\n self.bx = [4095.9754, 0.000204431397]\n self.by = [4095.71512, -0.000204373254]\n self._renew_lock = Lock()\n", "repository": "nimral/pathmap", "test_name": "test__renew_token", "smells": [0, 1, 0, 0, 0, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000163.py"} {"focal_file": "pathmap/cykloserver.py", "focal_class": null, "focal_method": "lon_lat_to_tiles", "tests": "import unittest\n\nclass Test_lon_lat_to_tiles(unittest.TestCase):\n def test_lon_lat_to_tiles_known(self):\n \"\"\"should return known tiles coords for known lon lat pairs\n\n These are longitudes and latitudes of certain tiles' upper left\n corners.\n Compared with delta=0.01 (~ 2.56 px)\n \"\"\"\n lon_lats = [(17.44593229, 49.32475974), (17.35827964, 49.32463261), (17.27046704, 49.35343943), (14.32647425, 50.09219194), (14.23799062, 50.092242), (14.37016985, 50.06426084), (14.2384118, 48.89340921)]\n tiles_coords = [(4493, 2802), (4491, 2802), (4489, 2801), (4422, 2775), (4420, 2775), (4423, 2776), (4420, 2817)]\n for ll, tc in zip(lon_lats, tiles_coords):\n x, y = self.c.lon_lat_to_tiles(*ll)\n self.assertAlmostEqual(x, tc[0], delta=0.01)\n self.assertAlmostEqual(y, tc[1], delta=0.01)\n", "method_code": " def lon_lat_to_tiles(self, lon, lat):\n \"\"\"Convert longitude and latitude to (x, y) tiles coordinates.\n \n Tiles compose a rectangular grid. Numbers of the column\n and row in which a tile lies should be equal to its upper left corner\n coordinates.\n \"\"\"\n trans_x, trans_y = pyproj.transform(self.proj_from, self.proj_to, lon, lat)\n return (self.bx[0] + self.bx[1] * trans_x, self.by[0] + self.by[1] * trans_y)\n ", "context": "class CykloserverMapDownloader(MapDownloader):\n def lon_lat_to_tiles(self, lon, lat): ...\n def __init__(self): ...\n def _get_js_output(self, script): ...\n def _url2dict(self, url): ...\n def _renew_token(self): ...\n def _download_tile(self, x, y, filename): ...\n def _tile_filename(self, x, y): ...\n def get_tile(self, x, y): ...\n def gpx2path(self, filename): ...\n\n self.s = requests.Session()\n self.xres = 256\n self.yres = 256\n self.last_token_acquired = 0\n self.proj_to = pyproj.Proj('+init=EPSG:3857')\n self.proj_from = pyproj.Proj('+init=EPSG:4326')\n self.bx = [4095.9754, 0.000204431397]\n self.by = [4095.71512, -0.000204373254]\n self._renew_lock = Lock()\n", "repository": "nimral/pathmap", "test_name": "test_lon_lat_to_tiles_known", "smells": [0, 1, 0, 0, 0, 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": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000164.py"} {"focal_file": "pathmap/cykloserver.py", "focal_class": null, "focal_method": "_download_tile", "tests": "import unittest\n\nclass Test_download_tile(unittest.TestCase):\n def test__download_tile_known(self):\n \"\"\"Downloaded tiles should be the same as known tiles\"\"\"\n known = [(4492, 2804), (4497, 2804)]\n tdir = tempfile.TemporaryDirectory()\n try:\n for x, y in known:\n fname = '{}/{}'.format(tdir.name, 'file.png')\n self.c._download_tile(x, y, fname)\n im = Image.open(fname)\n im2 = Image.open('pathmap/test/{}'.format(self.c._tile_filename(x, y)))\n self.assertEqual(im.tobytes() == im2.tobytes(), True)\n finally:\n tdir.cleanup()\n", "method_code": " def _download_tile(self, x, y, filename):\n \"\"\"Downloads a tile whose upper left corner has coordinates x, y\n \n Tile gets saved as filename.\"\"\"\n if time.time() - self.last_token_acquired > 60:\n self._renew_lock.acquire()\n if time.time() - self.last_token_acquired > 60:\n self._renew_token()\n self._renew_lock.release()\n r = self.s.get('http://webtiles.timepress.cz/cyklo_256/13/{}/{}'.format(x, y))\n with open(filename, 'wb') as fout:\n fout.write(r.content)\n ", "context": "class CykloserverMapDownloader(MapDownloader):\n def _download_tile(self, x, y, filename): ...\n def __init__(self): ...\n def _get_js_output(self, script): ...\n def _url2dict(self, url): ...\n def _renew_token(self): ...\n def lon_lat_to_tiles(self, lon, lat): ...\n def _tile_filename(self, x, y): ...\n def get_tile(self, x, y): ...\n def gpx2path(self, filename): ...\n\n self.s = requests.Session()\n self.xres = 256\n self.yres = 256\n self.last_token_acquired = 0\n self.proj_to = pyproj.Proj('+init=EPSG:3857')\n self.proj_from = pyproj.Proj('+init=EPSG:4326')\n self.bx = [4095.9754, 0.000204431397]\n self.by = [4095.71512, -0.000204373254]\n self._renew_lock = Lock()\n", "repository": "nimral/pathmap", "test_name": "test__download_tile_known", "smells": [0, 1, 0, 0, 0, 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": [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000165.py"} {"focal_file": "pathmap/cykloserver.py", "focal_class": null, "focal_method": "get_tile", "tests": "import unittest\n\nclass Test_get_tile(unittest.TestCase):\n def test_get_tile_known(self):\n \"\"\"Returned tiles should be the same as known tiles\"\"\"\n known = [(4492, 2804), (4497, 2804)]\n tdir = tempfile.TemporaryDirectory()\n try:\n for x, y in known:\n im = self.c.get_tile(x, y)\n im2 = Image.open('pathmap/test/{}'.format(self.c._tile_filename(x, y)))\n self.assertEqual(im.tobytes() == im2.tobytes(), True)\n finally:\n tdir.cleanup()\n", "method_code": " def get_tile(self, x, y):\n \"\"\"Return a tile (PIL.Image) whose upper left corner has coordinates x, y\"\"\"\n filename = self._tile_filename(x, y)\n im = None\n while True:\n try:\n im = Image.open(filename)\n except (IOError, FileNotFoundError):\n self._download_tile(x, y, filename)\n else:\n return im\n ", "context": "class CykloserverMapDownloader(MapDownloader):\n def get_tile(self, x, y): ...\n def __init__(self): ...\n def _get_js_output(self, script): ...\n def _url2dict(self, url): ...\n def _renew_token(self): ...\n def lon_lat_to_tiles(self, lon, lat): ...\n def _download_tile(self, x, y, filename): ...\n def _tile_filename(self, x, y): ...\n def gpx2path(self, filename): ...\n\n self.s = requests.Session()\n self.xres = 256\n self.yres = 256\n self.last_token_acquired = 0\n self.proj_to = pyproj.Proj('+init=EPSG:3857')\n self.proj_from = pyproj.Proj('+init=EPSG:4326')\n self.bx = [4095.9754, 0.000204431397]\n self.by = [4095.71512, -0.000204373254]\n self._renew_lock = Lock()\n", "repository": "nimral/pathmap", "test_name": "test_get_tile_known", "smells": [0, 1, 0, 0, 0, 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": [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000166.py"} {"focal_file": "pathmap/cykloserver.py", "focal_class": null, "focal_method": "gpx2path", "tests": "import unittest\n\nclass Test_gpx2path(unittest.TestCase):\n def test_gpx2path_known(self):\n \"\"\"Returned paths should be the same as known paths\"\"\"\n gpxes = ['pathmap/test/passau1.gpx']\n paths = [[(17.63872147, 49.22129716), (17.63339996, 49.21883049), (17.62653351, 49.21905474), (17.62104034, 49.21681221), (17.61743546, 49.22006384), (17.60936737, 49.21759711), (17.5985527, 49.21670008), (17.59065628, 49.21647582), (17.58001328, 49.21557877), (17.578125, 49.21400891), (17.57400513, 49.21445744), (17.56490707, 49.21086902), (17.55598068, 49.21008401), (17.55083084, 49.20795323), (17.54619598, 49.20694388)]]\n for gpx, path in zip(gpxes, paths):\n self.assertEqual(self.c.gpx2path(gpx), path)\n", "method_code": " def gpx2path(self, filename):\n \"\"\"Return list of (longitude, latitude) pairs stored as a trek in gpx file filename\"\"\"\n with open(filename, 'r') as fin:\n gpx = ''.join(fin.readlines()[1:])\n root = etree.fromstring(gpx)\n return [(float(e.get('lon')), float(e.get('lat'))) for e in root.getchildren()[0].getchildren()[0].getchildren()]\n ", "context": "class CykloserverMapDownloader(MapDownloader):\n def gpx2path(self, filename): ...\n def __init__(self): ...\n def _get_js_output(self, script): ...\n def _url2dict(self, url): ...\n def _renew_token(self): ...\n def lon_lat_to_tiles(self, lon, lat): ...\n def _download_tile(self, x, y, filename): ...\n def _tile_filename(self, x, y): ...\n def get_tile(self, x, y): ...\n\n self.s = requests.Session()\n self.xres = 256\n self.yres = 256\n self.last_token_acquired = 0\n self.proj_to = pyproj.Proj('+init=EPSG:3857')\n self.proj_from = pyproj.Proj('+init=EPSG:4326')\n self.bx = [4095.9754, 0.000204431397]\n self.by = [4095.71512, -0.000204373254]\n self._renew_lock = Lock()\n", "repository": "nimral/pathmap", "test_name": "test_gpx2path_known", "smells": [0, 1, 0, 0, 0, 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": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000167.py"} {"focal_file": "vecnet/openmalaria/experiment.py", "focal_class": "ExperimentSpecification", "focal_method": "add_sweep", "tests": "import unittest\n\nclass Test_ExperimentSpecification_add_sweep(unittest.TestCase):\n def test_add_sweep_and_arms(self):\n \"\"\" Testing add_sweeps and add_arms functions\n \"\"\"\n fp = open(os.path.join(base_dir, 'files/test_experiment/experiment1.json'), 'r')\n exp = ExperimentSpecification(json.load(fp))\n exp.experiment['base'] = ' @itn@ @irs@ @model@ @p1@ (@p2@) '\n exp.add_sweep('test')\n exp.add_arm('test', '1', {'@p1@': 2, '@p2@': '1'})\n exp.add_arm('test', '2', {'@p1@': 1, '@p2@': 'hey'})\n expected_result = {u' 80 66 model1 2 (1) ', u' 80 66 model3 2 (1) ', u' 80 66 model2 2 (1) ', u' 80 66 model1 1 (hey) ', u' 80 66 model3 1 (hey) ', u' 80 66 model2 1 (hey) ', u' 80 77 model1 2 (1) ', u' 80 77 model3 2 (1) ', u' 80 77 model2 2 (1) ', u' 80 77 model1 1 (hey) ', u' 80 77 model3 1 (hey) ', u' 80 77 model2 1 (hey) ', u' 90 66 model1 2 (1) ', u' 90 66 model3 2 (1) ', u' 90 66 model2 2 (1) ', u' 90 66 model1 1 (hey) ', u' 90 66 model3 1 (hey) ', u' 90 66 model2 1 (hey) '}\n self.assertEqual(set((scenario.xml for scenario in exp.scenarios())), expected_result)\n\n def test_add_sweep(self):\n experiment = {'base': '@itn@ @irs@ ', 'sweeps': {'itn': {'itn 80': {'@itn@': '80'}, 'itn 90': {'@itn@': '90'}}, 'irs': {'irs 66': {'@irs@': '66'}, 'irs 90': {'@irs@': '90'}}}}\n exp = ExperimentSpecification(experiment)\n exp.add_sweep('test')\n self.assertIn('test', exp.experiment['sweeps'])\n", "method_code": " def add_sweep(self, sweep_name):\n self.experiment['sweeps'][sweep_name] = {}\n ", "context": "class ExperimentSpecification():\n def add_sweep(self, sweep_name): ...\n def __init__(self, experiment): ...\n def __str__(self): ...\n def _apply_changes(self, scenario, sweep_name, arm_name): ...\n def _apply_combination(self, scenario, sweeps_applied, combination): ...\n def scenarios(self, generate_seed=False): ...\n def add_arm(self, sweep, arm_name, parameters): ...\n\n self.experiment = experiment\n", "repository": "vecnet/vecnet.openmalaria", "test_name": "test_add_sweep_and_arms", "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_000168.py"} {"focal_file": "vecnet/openmalaria/__init__.py", "focal_class": null, "focal_method": "get_schema_version_from_xml", "tests": "import unittest\n\nclass Test_get_schema_version_from_xml(unittest.TestCase):\n def test_get_schema_version_from_xml(self):\n base_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'files')\n with open(os.path.join(base_dir, os.path.join('test_get_schema_version', 'scenario30.xml'))) as fp:\n schema_version = get_schema_version_from_xml(fp)\n self.assertEqual(schema_version, '30')\n with open(os.path.join(base_dir, os.path.join('test_get_schema_version', 'scenario30.xml'))) as fp:\n schema_version = get_schema_version_from_xml(fp.read())\n self.assertEqual(schema_version, '30')\n with open(os.path.join(base_dir, os.path.join('test_get_schema_version', 'scenario32.xml'))) as fp:\n schema_version = get_schema_version_from_xml(fp.read())\n self.assertEqual(schema_version, '32')\n with open(os.path.join(base_dir, os.path.join('test_get_schema_version', 'non_om_xml.xml'))) as fp:\n schema_version = get_schema_version_from_xml(fp.read())\n self.assertIsNone(schema_version)\n schema_version = get_schema_version_from_xml('')\n self.assertIsNone(schema_version)\n schema_version = get_schema_version_from_xml('abcdef')\n self.assertIsNone(schema_version)\n", "method_code": "def get_schema_version_from_xml(xml):\n \"\"\" Get schemaVersion attribute from OpenMalaria scenario file\n xml - open file or content of xml document to be processed\n \"\"\"\n if isinstance(xml, six.string_types):\n xml = StringIO(xml)\n try:\n tree = ElementTree.parse(xml)\n except ParseError:\n return None\n root = tree.getroot()\n return root.attrib.get('schemaVersion', None)", "context": "def get_schema_version_from_xml(xml): ...\ndef get_schema_version_from_xml(xml): ...\n", "repository": "vecnet/vecnet.openmalaria", "test_name": "test_get_schema_version_from_xml", "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_000169.py"} {"focal_file": "vecnet/openmalaria/output_parser.py", "focal_class": "OutputParser", "focal_method": "get_cts_measures", "tests": "import unittest\n\nclass Test_OutputParser_get_cts_measures(unittest.TestCase):\n def test_vector_measures(self):\n output_parser = OutputParser(open(os.path.join(base_dir, 'test1.xml')), survey_output_file=open(os.path.join(base_dir, 'test1_output.txt')), cts_output_file=open(os.path.join(base_dir, 'test1_ctsout.txt')))\n self.assertEqual(len(output_parser.cts_output_data['N_v0(arabiensis)']), 1461)\n self.assertEqual(output_parser.get_cts_measures(), ['input EIR', 'simulated EIR', 'human infectiousness', 'N_v0(gambiae)', 'N_v0(arabiensis)', 'N_v0(funestus)', 'N_v0(minor)', 'immunity h', 'immunity Y', 'new infections', 'num transmitting humans', 'ITN coverage', 'IRS coverage', 'GVI coverage', 'alpha_i(gambiae)', 'alpha_i(arabiensis)', 'alpha_i(funestus)', 'alpha_i(minor)', 'P_B(gambiae)', 'P_B(arabiensis)', 'P_B(funestus)', 'P_B(minor)', 'P_C*P_D(gambiae)', 'P_C*P_D(arabiensis)', 'P_C*P_D(funestus)', 'P_C*P_D(minor)'])\n self.assertEqual(len(output_parser.survey_time_list), 241)\n self.assertEqual(len(output_parser.survey_output_data[34, 'funestus']), 241)\n self.assertEqual(output_parser.survey_output_data[21, 1], [[0, 152.089]])\n", "method_code": " def get_cts_measures(self):\n return list(self.cts_output_data.keys())\n ", "context": "class OutputParser():\n def get_cts_measures(self): ...\n def __init__(self, input_file, survey_output_file=None, cts_output_file=None): ...\n def _parse_continuous_output_file(self, cts_output_file): ...\n def _parse_survey_output_file(self, survey_output_file): ...\n def get_survey_measures(self): ...\n def get_monitoring_age_group(self, third_dimension): ...\n def get_survey_measure_name(self, measure_id, third_dimension): ...\n\n self.xml = input_file.read()\n self.scenario = Scenario(self.xml)\n self.survey_time_list = self.scenario.monitoring.surveys\n", "repository": "vecnet/vecnet.openmalaria", "test_name": "test_vector_measures", "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_000170.py"} {"focal_file": "workspace/Python3_Homework02/src/coconuts.py", "focal_class": null, "focal_method": "totalWeight", "tests": "import unittest\n\nclass Test_totalWeight(unittest.TestCase):\n def testInventoryWeight(self):\n \"\"\"\n Gimme 2 South Asian, 1 Middle Eastern, and 3 American coconuts weighing 19 units\n Also check that adding invalid instance of Coconut raises an error\n \"\"\"\n inv = Inventory()\n inv.addCoconut(self.southAsian)\n inv.addCoconut(self.southAsian)\n inv.addCoconut(self.middleEastern)\n inv.addCoconut(self.american)\n inv.addCoconut(self.american)\n inv.addCoconut(self.american)\n observed = inv.totalWeight()\n self.assertEqual(observed, 19.0)\n self.assertRaises(TypeError, inv.addCoconut, 'Dodecelsulfate')\n", "method_code": " def totalWeight(self):\n \"\"\"\n Tally and return the total weight of all of our coconuts\n \"\"\"\n total = 0\n for coconut in self.coconutInventory:\n total += coconut.weight\n return total\n ", "context": "class Inventory(object):\n def totalWeight(self): ...\n def __init__(self): ...\n def addCoconut(self, obj): ...\n\n self.coconutInventory = []\n", "repository": "paulrefalo/Python-2---4", "test_name": "testInventoryWeight", "smells": [0, 1, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000171.py"} {"focal_file": "workspace/Python3_Homework05/src/ccn_safety.py", "focal_class": null, "focal_method": "CCNsafety", "tests": "import unittest\n\nclass Test_CCNsafety(unittest.TestCase):\n def testCCNsafety(self):\n \"\"\"\n Test the hiding of the first 12 digits of a CCN for security\n \"\"\"\n response, count = CCNsafety(text)\n self.assertTrue('555-123-4567' in response)\n self.assertTrue('XXXX-XXXX-XXXX-5555' in response)\n self.assertTrue('XXXX-XXXX-XXXX-5678' in response)\n self.assertFalse('5555-5555-5555-5555' in response)\n self.assertFalse('1234-5678-1234-5678' in response)\n self.assertEqual(2, count)\n self.assertEqual(response, enchilada)\n print(response)\n", "method_code": "def CCNsafety(text):\n \"\"\"\n Hide the first 12 digits of a CNN for security\n \"\"\"\n return re.subn('\\\\d{4}-\\\\d{4}-\\\\d{4}-', 'XXXX-XXXX-XXXX-', text)", "context": "def CCNsafety(text): ...\ndef CCNsafety(text): ...\n", "repository": "paulrefalo/Python-2---4", "test_name": "testCCNsafety", "smells": [0, 1, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0], "pynose_source_file": "test_000172.py"} {"focal_file": "workspace/Python3_Homework06/src/ccn_safety2.py", "focal_class": null, "focal_method": "CCNsafety", "tests": "import unittest\n\nclass Test_CCNsafety(unittest.TestCase):\n def testCCNsafety(self):\n \"\"\"\n Test the hiding of the CCN for security\n \"\"\"\n response = CCNsafety(text)\n self.assertTrue('555-123-4567' in response)\n self.assertTrue('CCN REMOVED FOR YOUR SAFETY' in response)\n self.assertFalse('5555-5555-5555-5555' in response)\n self.assertFalse('1234-5678-1234-5678' in response)\n self.assertEqual(response, enchilada)\n print(response)\n", "method_code": "def CCNsafety(text):\n \"\"\"\n Hide CNN for security\n \"\"\"\n warning = 'CCN REMOVED FOR YOUR SAFETY'\n regex = re.compile(' ## Compile the pattern into regex\\n \\\\d{4}- # first set\\n \\\\d{4}- # second set\\n \\\\d{4}- # third set\\n \\\\d{4} # final set\\n ', re.VERBOSE)\n return regex.sub(warning, text)", "context": "def CCNsafety(text): ...\ndef CCNsafety(text): ...\n", "repository": "paulrefalo/Python-2---4", "test_name": "testCCNsafety", "smells": [0, 1, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0], "pynose_source_file": "test_000173.py"} {"focal_file": "workspace/Python3_Homework07/src/furnishings.py", "focal_class": null, "focal_method": "counter", "tests": "import unittest\n\nclass Test_counter(unittest.TestCase):\n def testCounter(self):\n \"\"\"\n Get the count dict back from counter and check the values are right\n \"\"\"\n count = counter(self.home)\n self.assertEqual(count['Bed'], 2)\n self.assertEqual(count['Sofa'], 1)\n self.assertEqual(count['Table'], 2)\n self.assertEqual(count['Bookshelf'], 1)\n", "method_code": "def counter(furniture):\n \"\"\"\n Create count dict to tally the furniture totals\n \"\"\"\n count = {}\n for item in furniture:\n itemClass = item.__class__.__name__\n if itemClass in count:\n count[itemClass] = count[itemClass] + 1\n else:\n count[itemClass] = 1\n for key, val in sorted(count.items()):\n print(key + ':', val)\n return count", "context": "def counter(furniture): ...\ndef map_the_home(furniture): ...\ndef counter(furniture): ...\n", "repository": "paulrefalo/Python-2---4", "test_name": "testCounter", "smells": [0, 1, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000174.py"} {"focal_file": "workspace/Python3_Lesson02/src/bunchclass.py", "focal_class": null, "focal_method": "pretty", "tests": "import unittest\n\nclass Test_pretty(unittest.TestCase):\n def test_pretty(self):\n self.assertRaises(AttributeError, Bunch, name='Audrey', job='Software Developer', pretty=True)\n b = Bunch(name='Audrey', job='Software Developer')\n p = b.pretty()\n self.assertTrue('Audrey' in p)\n self.assertFalse('pretty: True' in p)\n", "method_code": " def pretty(self):\n text = ''\n for key, value in self.__dict__.items():\n text += '%s: %s\\n' % (key, value)\n return text\n ", "context": "class Bunch(object):\n def pretty(self): ...\n def __init__(self, *args, **kwargs): ...\n", "repository": "paulrefalo/Python-2---4", "test_name": "test_pretty", "smells": [0, 1, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000175.py"} {"focal_file": "workspace/Python3_Lesson02/src/inhairitance.py", "focal_class": null, "focal_method": "hair", "tests": "import unittest\n\nclass Test_hair(unittest.TestCase):\n def test_hair(self):\n child = Child()\n hair = child.hair()\n self.assertNotEqual(hair, 'red')\n self.assertNotEqual(hair, 'brown')\n self.assertNotEqual(hair, 'gray')\n self.assertEqual(hair, 'bald')\n", "method_code": " def hair(self):\n return 'red'\n ", "context": "class Maurice(object):\n def hair(self): ...", "repository": "paulrefalo/Python-2---4", "test_name": "test_hair", "smells": [0, 1, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000176.py"} {"focal_file": "workspace/Python3_Lesson06/src/city_search.py", "focal_class": null, "focal_method": "city_search", "tests": "import unittest\n\nclass Test_city_search(unittest.TestCase):\n def test_city_search(self):\n self.assertEqual('Washington, DC 20002', city_search(p2))\n self.assertEqual('Falls Church, VA 20188', city_search(p3))\n\n def test_city_search_failure(self):\n self.assertIsNone(city_search(p1))\n\n def test_city_search(self):\n self.assertEqual('Washington, DC 20002', city_search(p2))\n self.assertEqual('Falls Church, VA 20188', city_search(p3))\n\n def test_city_search_failure(self):\n self.assertIsNone(city_search(p1))\n", "method_code": "def city_search(text):\n regex = '[A-Z][a-z]+(\\\\s[A-Z][a-z]+)*,\\\\s[A-Z]{2}\\\\s\\\\d{5}'\n regex = re.compile('\\n [A-Z][a-z]+ # the first word of a city\\n (\\\\s[A-Z][a-z]+)* # possible additional words of a city\\n ,\\\\s[A-Z]{2}\\\\s # The two-letter abbreviation for a US state\\n \\\\d{5} # five-digit US zip code\\n ', re.VERBOSE)\n search = re.search(regex, text)\n search = regex.search(text)\n if search:\n return search.group()", "context": "def city_search(text): ...\ndef city_search(text): ...\n", "repository": "paulrefalo/Python-2---4", "test_name": "test_city_search", "smells": [0, 1, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000177.py"} {"focal_file": "workspace/Python3_Lesson05/src/phone.py", "focal_class": null, "focal_method": "get_phone", "tests": "import unittest\n\nclass Test_get_phone(unittest.TestCase):\n def test_phone(self):\n numbers = get_phone(text)\n self.assertEqual(len(numbers), 5)\n", "method_code": "def get_phone(text):\n \"\"\"Scan a text, locating telephone numbers.\"\"\"\n return re.findall('\\\\d\\\\d\\\\d-\\\\d\\\\d\\\\d-\\\\d\\\\d\\\\d\\\\d', text)", "context": "def get_phone(text): ...\ndef get_phone(text): ...\n", "repository": "paulrefalo/Python-2---4", "test_name": "test_phone", "smells": [0, 1, 0, 0, 0, 0, 0, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000178.py"} {"focal_file": "workspace/Python3_Lesson07/src/animal_farm.py", "focal_class": null, "focal_method": "sound", "tests": "import unittest\n\nclass Test_sound(unittest.TestCase):\n def test_chicken(self):\n chicken = Chicken('Kulak')\n self.assertEqual(chicken.sound(), 'bok bok!')\n self.assertTrue(chicken.has_wings())\n", "method_code": " def sound(self):\n raise NotImplementedError('Animals need a sound method')\n ", "context": "class Animal(object):\n def sound(self): ...\n def __init__(self, name): ...\n def has_wings(self): ...\n\n self.name = name\n", "repository": "paulrefalo/Python-2---4", "test_name": "test_chicken", "smells": [0, 1, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000179.py"} {"focal_file": "workspace/Python3_Lesson12/src/addressbook.py", "focal_class": null, "focal_method": "email_delete", "tests": "import unittest\n\nclass Test_email_delete(unittest.TestCase):\n def test_email_delete(self):\n addressbook.email_add(self.email)\n self.assertEqual(addressbook.email_delete(self.email)[0], True)\n self.assertEqual(addressbook.email_delete(self.email)[0], False)\n", "method_code": "def email_delete(email):\n validate_email(email)\n shelf = shelve.open(shelf_location)\n if 'emails' not in shelf:\n shelf['emails'] = []\n emails = shelf['emails']\n try:\n emails.remove(email)\n message = (True, 'Email \"%s\" removed from address book' % email)\n except ValueError:\n message = (False, 'Email \"%s\" was not in the address book' % email)\n shelf['emails'] = emails\n shelf.close()\n return message", "context": "def email_delete(email): ...\ndef validate_email(email): ...\ndef email_add(email): ...\ndef email_delete(email): ...\ndef email_display(): ...\ndef main(options): ...\n", "repository": "paulrefalo/Python-2---4", "test_name": "test_email_delete", "smells": [0, 1, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000180.py"} {"focal_file": "workspace/Python3_Lesson12/src/addressbook.py", "focal_class": null, "focal_method": "email_add", "tests": "import unittest\n\nclass Test_email_add(unittest.TestCase):\n def test_email_add(self):\n self.assertEqual(addressbook.email_add(self.email)[0], True)\n self.assertEqual(addressbook.email_add(self.email)[0], False)\n", "method_code": "def email_add(email):\n validate_email(email)\n shelf = shelve.open(shelf_location)\n if 'emails' not in shelf:\n shelf['emails'] = []\n emails = shelf['emails']\n if email in emails:\n message = (False, 'Email \"%s\" already in address book' % email)\n else:\n emails.append(email)\n message = (True, 'Email \"%s\" added to address book' % email)\n shelf['emails'] = emails\n shelf.close()\n return message", "context": "def email_add(email): ...\ndef validate_email(email): ...\ndef email_add(email): ...\ndef email_delete(email): ...\ndef email_display(): ...\ndef main(options): ...\n", "repository": "paulrefalo/Python-2---4", "test_name": "test_email_add", "smells": [0, 1, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000181.py"} {"focal_file": "workspace/Python3_Lesson12/src/addressbook.py", "focal_class": null, "focal_method": "email_display", "tests": "import unittest\n\nclass Test_email_display(unittest.TestCase):\n def test_email_display(self):\n addressbook.email_add(self.email)\n val, display = addressbook.email_display()\n self.assertTrue(self.email in display)\n", "method_code": "def email_display():\n shelf = shelve.open(shelf_location)\n emails = shelf['emails']\n shelf.close()\n text = ''\n for email in emails:\n text += email + '\\n'\n return (True, text)", "context": "def email_display(): ...\ndef validate_email(email): ...\ndef email_add(email): ...\ndef email_delete(email): ...\ndef email_display(): ...\ndef main(options): ...\n", "repository": "paulrefalo/Python-2---4", "test_name": "test_email_display", "smells": [0, 1, 0, 0, 0, 0, 0, 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, 1, 0, 0], "pynose_source_file": "test_000182.py"} {"focal_file": "workspace/Python3_Lesson13/src/birthday.py", "focal_class": null, "focal_method": "birthday_counter", "tests": "import unittest\n\nclass Test_birthday_counter(unittest.TestCase):\n def test_birthday_counter(self):\n self.assertTrue(birthday_counter('10-31-1948') > 0)\n self.assertTrue(birthday_counter('02-01-1999') > 0)\n", "method_code": "def birthday_counter(birthday):\n \"\"\"\n Returns the number of days until your birthday.\n \"\"\"\n now = datetime.now()\n birthday = string_to_date(birthday)\n logging.debug('birthday: %s' % birthday)\n upcoming = datetime(now.year, birthday.month, birthday.day)\n logging.debug('upcoming: %s' % upcoming)\n if upcoming < now:\n upcoming = upcoming + timedelta(365)\n logging.debug('fixed upcoming: %s' % upcoming)\n duration = upcoming - now\n logging.debug('duration: %s' % duration)\n return duration.days", "context": "def birthday_counter(birthday): ...\ndef string_to_date(date): ...\ndef birthday_counter(birthday): ...\n", "repository": "paulrefalo/Python-2---4", "test_name": "test_birthday_counter", "smells": [0, 1, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000183.py"} {"focal_file": "workspace/Python3_Lesson13/src/birthday.py", "focal_class": null, "focal_method": "string_to_date", "tests": "import unittest\n\nclass Test_string_to_date(unittest.TestCase):\n def test_string_to_date(self):\n self.assertRaises(InvalidDateFormat, string_to_date, '10-32-1948')\n datetime_obj = datetime(2012, 10, 31)\n self.assertEqual(datetime_obj, string_to_date('10-31-2012'))\n", "method_code": "def string_to_date(date):\n \"\"\"\n Converts 'MM-DD-YYYY' to a date/time object\n or throws an InvalidDateFormat exception\n \"\"\"\n try:\n formatter_string = '%m-%d-%Y'\n birthday = datetime.strptime(date, formatter_string)\n except ValueError as e:\n logging.error(e)\n raise InvalidDateFormat(e)\n return birthday", "context": "def string_to_date(date): ...\ndef string_to_date(date): ...\ndef birthday_counter(birthday): ...\n", "repository": "paulrefalo/Python-2---4", "test_name": "test_string_to_date", "smells": [0, 1, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000184.py"} {"focal_file": "myvenv/Lib/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 \"\"\"Render a Unicode representation of this PageElement and its\n contents.\n \n :param indent_level: Each line of the rendering will be\n indented this many spaces. Used internally in\n recursive calls while pretty-printing.\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 :param formatter: A Formatter object, or a string naming one of\n the standard formatters.\n \"\"\"\n if not isinstance(formatter, Formatter):\n formatter = self.formatter_for_name(formatter)\n attributes = formatter.attributes(self)\n attrs = []\n for key, val in attributes:\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 = formatter.attribute_value(val)\n decoded = str(key) + '=' + formatter.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 = formatter.void_element_close_prefix or ''\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, sourceline=None, sourcepos=None, can_be_empty_element=None, cdata_list_attributes=None, preserve_whitespace_tags=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 smooth(self): ...\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.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": "MunSeoHee/gachonlikelion8th", "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_000185.py"} {"focal_file": "myvenv/Lib/site-packages/pyppeteer/launcher.py", "focal_class": null, "focal_method": "launch", "tests": "import unittest\n\nclass Test_launch(unittest.TestCase):\n @sync\n async def test_launch(self):\n browser = await launch(DEFAULT_OPTIONS)\n await browser.newPage()\n await browser.close()\n", "method_code": "def launch(options: dict=None, **kwargs: Any) -> Browser: ...", "context": "async def launch(options: dict=None, **kwargs: Any) -> Browser:\n \"\"\"Start chrome process and return :class:`~pyppeteer.browser.Browser`.\n This function is a shortcut to :meth:`Launcher(options, **kwargs).launch`.\n Available options are:\n * ``ignoreHTTPSErrors`` (bool): Whether to ignore HTTPS errors. Defaults to\n ``False``.\n * ``headless`` (bool): Whether to run browser in headless mode. Defaults to\n ``True`` unless ``appMode`` or ``devtools`` options is ``True``.\n * ``executablePath`` (str): Path to a Chromium or Chrome executable to run\n instead of default bundled Chromium.\n * ``slowMo`` (int|float): Slow down pyppeteer operations by the specified\n amount of milliseconds.\n * ``defaultViewport`` (dict): Set a consistent viewport for each page.\n Defaults to an 800x600 viewport. ``None`` disables default viewport.\n * ``width`` (int): page width in pixels.\n * ``height`` (int): page height in pixels.\n * ``deviceScaleFactor`` (int|float): Specify device scale factor (can be\n thought as dpr). Defaults to ``1``.\n * ``isMobile`` (bool): Whether the ``meta viewport`` tag is taken into\n account. Defaults to ``False``.\n * ``hasTouch`` (bool): Specify if viewport supports touch events.\n Defaults to ``False``.\n * ``isLandscape`` (bool): Specify if viewport is in landscape mode.\n Defaults to ``False``.\n * ``args`` (List[str]): Additional arguments (flags) to pass to the browser\n process.\n * ``ignoreDefaultArgs`` (bool or List[str]): If ``True``, do not use\n :func:`~pyppeteer.defaultArgs`. If list is given, then filter out given\n default arguments. Dangerous option; use with care. Defaults to\n ``False``.\n * ``handleSIGINT`` (bool): Close the browser process on Ctrl+C. Defaults to\n ``True``.\n * ``handleSIGTERM`` (bool): Close the browser process on SIGTERM. Defaults\n to ``True``.\n * ``handleSIGHUP`` (bool): Close the browser process on SIGHUP. Defaults to\n ``True``.\n * ``dumpio`` (bool): Whether to pipe the browser process stdout and stderr\n into ``process.stdout`` and ``process.stderr``. Defaults to ``False``.\n * ``userDataDir`` (str): Path to a user data directory.\n * ``env`` (dict): Specify environment variables that will be visible to the\n browser. Defaults to same as python process.\n * ``devtools`` (bool): Whether to auto-open a DevTools panel for each tab.\n If this option is ``True``, the ``headless`` option will be set\n ``False``.\n * ``logLevel`` (int|str): Log level to print logs. Defaults to same as the\n root logger.\n * ``autoClose`` (bool): Automatically close browser process when script\n completed. Defaults to ``True``.\n * ``loop`` (asyncio.AbstractEventLoop): Event loop (**experimental**).\n * ``appMode`` (bool): Deprecated.\n This function combines 3 steps:\n 1. Infer a set of flags to launch chromium with using\n :func:`~pyppeteer.defaultArgs`.\n 2. Launch browser and start managing its process according to the\n ``executablePath``, ``handleSIGINT``, ``dumpio``, and other options.\n 3. Create an instance of :class:`~pyppeteer.browser.Browser` class and\n initialize it with ``defaultViewport``, ``slowMo``, and\n ``ignoreHTTPSErrors``.\n ``ignoreDefaultArgs`` option can be used to customize behavior on the (1)\n step. For example, to filter out ``--mute-audio`` from default arguments:\n .. code::\n browser = await launch(ignoreDefaultArgs=['--mute-audio'])\n .. note::\n Pyppeteer can also be used to control the Chrome browser, but it works\n best with the version of Chromium it is bundled with. There is no\n guarantee it will work with any other version. Use ``executablePath``\n option with extreme caution.\n \"\"\"\n return await Launcher(options, **kwargs).launch()\ndef get_ws_endpoint(url) -> str: ...\ndef launch(options: dict=None, **kwargs: Any) -> Browser: ...: ...\ndef connect(options: dict=None, **kwargs: Any) -> Browser: ...\ndef executablePath() -> str: ...\ndef defaultArgs(options: Dict=None, **kwargs: Any) -> List[str]: ...\n", "repository": "MunSeoHee/gachonlikelion8th", "test_name": "", "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, 1], "pynose_source_file": "test_000186.py"} {"focal_file": "myvenv/Lib/site-packages/pyppeteer/launcher.py", "focal_class": null, "focal_method": "connect", "tests": "import unittest\n\nclass Test_connect(unittest.TestCase):\n @unittest.skipIf(current_platform().startswith('win'), 'error on windows')\n @sync\n async def test_connect_debug(self):\n browser = await launch(args=['--no-sandbox'])\n browser2 = await connect(browserWSEndpoint=browser.wsEndpoint, logLevel=logging.DEBUG)\n page = await browser2.newPage()\n await page.close()\n await browser2.disconnect()\n await browser.close()\n self.assertTrue(self.logger.isEnabledFor(logging.WARN))\n self.assertTrue(self.logger.isEnabledFor(logging.INFO))\n self.assertTrue(self.logger.isEnabledFor(logging.DEBUG))\n self.assertIn('SEND', self.mock.call_args_list[0][0][0])\n self.assertIn('RECV', self.mock.call_args_list[2][0][0])\n\n @sync\n async def test_connect(self):\n browser = await launch(DEFAULT_OPTIONS)\n browser2 = await connect(browserWSEndpoint=browser.wsEndpoint)\n page = await browser2.newPage()\n self.assertEqual(await page.evaluate('() => 7 * 8'), 56)\n await browser2.disconnect()\n page2 = await browser.newPage()\n self.assertEqual(await page2.evaluate('() => 7 * 6'), 42)\n await browser.close()\n\n @sync\n async def test_reconnect(self):\n browser = await launch(DEFAULT_OPTIONS)\n browserWSEndpoint = browser.wsEndpoint\n await browser.disconnect()\n browser2 = await connect(browserWSEndpoint=browserWSEndpoint)\n page = await browser2.newPage()\n self.assertEqual(await page.evaluate('() => 7 * 8'), 56)\n await browser.close()\n", "method_code": "def connect(options: dict=None, **kwargs: Any) -> Browser: ...", "context": "async def connect(options: dict=None, **kwargs: Any) -> Browser:\n \"\"\"Connect to the existing chrome.\n ``browserWSEndpoint`` or ``browserURL`` option is necessary to connect to\n the chrome. The format of ``browserWSEndpoint`` is\n ``ws://${host}:${port}/devtools/browser/`` and format of ``browserURL``\n is ``http://127.0.0.1:9222```.\n The value of ``browserWSEndpoint`` can get by :attr:`~pyppeteer.browser.Browser.wsEndpoint`.\n Available options are:\n * ``browserWSEndpoint`` (str): A browser websocket endpoint to connect to.\n * ``browserURL`` (str): A browser URL to connect to.\n * ``ignoreHTTPSErrors`` (bool): Whether to ignore HTTPS errors. Defaults to\n ``False``.\n * ``defaultViewport`` (dict): Set a consistent viewport for each page.\n Defaults to an 800x600 viewport. ``None`` disables default viewport.\n * ``width`` (int): page width in pixels.\n * ``height`` (int): page height in pixels.\n * ``deviceScaleFactor`` (int|float): Specify device scale factor (can be\n thought as dpr). Defaults to ``1``.\n * ``isMobile`` (bool): Whether the ``meta viewport`` tag is taken into\n account. Defaults to ``False``.\n * ``hasTouch`` (bool): Specify if viewport supports touch events.\n Defaults to ``False``.\n * ``isLandscape`` (bool): Specify if viewport is in landscape mode.\n Defaults to ``False``.\n * ``slowMo`` (int|float): Slow down pyppeteer's by the specified amount of\n milliseconds.\n * ``logLevel`` (int|str): Log level to print logs. Defaults to same as the\n root logger.\n * ``loop`` (asyncio.AbstractEventLoop): Event loop (**experimental**).\n \"\"\"\n options = merge_dict(options, kwargs)\n logLevel = options.get('logLevel')\n if logLevel:\n logging.getLogger('pyppeteer').setLevel(logLevel)\n browserWSEndpoint = options.get('browserWSEndpoint')\n if not browserWSEndpoint:\n browserURL = options.get('browserURL')\n if not browserURL:\n raise BrowserError('Need `browserWSEndpoint` or `browserURL` option.')\n browserWSEndpoint = get_ws_endpoint(browserURL)\n connectionDelay = options.get('slowMo', 0)\n connection = Connection(browserWSEndpoint, options.get('loop', asyncio.get_event_loop()), connectionDelay)\n browserContextIds = (await connection.send('Target.getBrowserContexts')).get('browserContextIds', [])\n ignoreHTTPSErrors = bool(options.get('ignoreHTTPSErrors', False))\n defaultViewport = options.get('defaultViewport', {'width': 800, 'height': 600})\n return await Browser.create(connection, browserContextIds, ignoreHTTPSErrors, defaultViewport, None, lambda: connection.send('Browser.close'))\ndef get_ws_endpoint(url) -> str: ...\ndef launch(options: dict=None, **kwargs: Any) -> Browser: ...\ndef connect(options: dict=None, **kwargs: Any) -> Browser: ...: ...\ndef executablePath() -> str: ...\ndef defaultArgs(options: Dict=None, **kwargs: Any) -> List[str]: ...\n", "repository": "MunSeoHee/gachonlikelion8th", "test_name": "", "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, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000187.py"} {"focal_file": "myvenv/Lib/site-packages/pyppeteer/launcher.py", "focal_class": null, "focal_method": "executablePath", "tests": "import unittest\n\nclass Test_executablePath(unittest.TestCase):\n @sync\n async def test_executable_path(self):\n self.assertTrue(os.path.exists(executablePath()))\n", "method_code": "def executablePath() -> str:\n \"\"\"Get executable path of default chromium.\"\"\"\n return str(chromium_executable())", "context": "def executablePath() -> str: ...\ndef get_ws_endpoint(url) -> str: ...\ndef launch(options: dict=None, **kwargs: Any) -> Browser: ...\ndef connect(options: dict=None, **kwargs: Any) -> Browser: ...\ndef executablePath() -> str: ...\ndef defaultArgs(options: Dict=None, **kwargs: Any) -> List[str]: ...\n", "repository": "MunSeoHee/gachonlikelion8th", "test_name": "", "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_000188.py"} {"focal_file": "nixysa/syntax_tree_unittest.py", "focal_class": null, "focal_method": "LookUpType", "tests": "import unittest\n\nclass Test_LookUpType(unittest.TestCase):\n def testLookUpType(self):\n for t in [self.typedef1, self.typedef2]:\n self.assertEquals(t.LookUpType('Type'), None)\n self.assertEquals(t.LookUpType('NonType'), None)\n self.assertRaises(syntax_tree.TypeNotFoundError, self.typedef3.LookUpType, 'Type')\n for t in [self.typedef4, self.typedef5]:\n self.assertEquals(t.LookUpType('Type'), self.base_type2_t)\n self.assertEquals(t.LookUpType('NonType'), None)\n\n def testLookUpScope(self):\n type1 = MakeType('Type1')\n type2 = MakeType('Type2')\n scope1 = MakeScope('Scope1')\n scope2 = MakeScope('Scope2')\n scope = syntax_tree.LookUpScope([type1, type2, scope1, scope2])\n self.assertEquals(scope.LookUpType('Type1'), type1)\n self.assertEquals(scope.LookUpType('Type2'), type2)\n self.assertEquals(scope.LookUpType('Type3'), None)\n self.assertEquals(scope.LookUpType('Scope1'), None)\n self.assertEquals(scope.LookUpType('Scope2'), None)\n self.assertEquals(scope.LookUpType('Scope3'), None)\n self.assertEquals(scope.FindScopes('Type1'), [])\n self.assertEquals(scope.FindScopes('Type2'), [])\n self.assertEquals(scope.FindScopes('Type3'), [])\n self.assertEquals(scope.FindScopes('Scope1'), [scope1])\n self.assertEquals(scope.FindScopes('Scope2'), [scope2])\n self.assertEquals(scope.FindScopes('Scope3'), [])\n type3 = MakeType('Type3')\n scope3 = MakeScope('Scope3')\n scope3_bis = MakeScope('Scope3')\n scope.list.extend([type3, scope3, scope3_bis])\n scope.ResetCache()\n self.assertEquals(scope.LookUpType('Type1'), type1)\n self.assertEquals(scope.LookUpType('Type2'), type2)\n self.assertEquals(scope.LookUpType('Type3'), type3)\n self.assertEquals(scope.LookUpType('Scope1'), None)\n self.assertEquals(scope.LookUpType('Scope2'), None)\n self.assertEquals(scope.LookUpType('Scope3'), None)\n self.assertEquals(scope.FindScopes('Type1'), [])\n self.assertEquals(scope.FindScopes('Type2'), [])\n self.assertEquals(scope.FindScopes('Type3'), [])\n self.assertEquals(scope.FindScopes('Scope1'), [scope1])\n self.assertEquals(scope.FindScopes('Scope2'), [scope2])\n self.assertEquals(scope.FindScopes('Scope3'), [scope3, scope3_bis])\n", "method_code": " def LookUpType(self, name):\n if name in self.types_dict:\n return self.types_dict[name]\n else:\n return None\n ", "context": "class ContextMock(syntax_tree.Definition):\n def LookUpType(self, name): ...\n def __init__(self, types_list, scopes_list, name, parent): ...\n def FindScopes(self, name): ...\n\n self.is_scope = True\n self.types_dict = dict([(type_defn.name, type_defn) for type_defn in types_list])\n self.scopes_list = scopes_list\n self.parent = parent\n\n defn_type = 'ContextMock'\n", "repository": "BladeSmithJohn/nixysa", "test_name": "testLookUpType", "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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000189.py"} {"focal_file": "nixysa/syntax_tree_unittest.py", "focal_class": null, "focal_method": "FindScopes", "tests": "import unittest\n\nclass Test_FindScopes(unittest.TestCase):\n def testFindScopes(self):\n for t in [self.typedef1, self.typedef2]:\n self.assertEquals(t.FindScopes('Scope'), [])\n self.assertEquals(t.FindScopes('NonScope'), [])\n self.assertRaises(syntax_tree.TypeNotFoundError, self.typedef3.FindScopes, 'Scope')\n for t in [self.typedef4, self.typedef5]:\n self.assertEquals(t.FindScopes('Scope'), [self.base_type2_s])\n self.assertEquals(t.FindScopes('NonScope'), [])\n", "method_code": " def FindScopes(self, name):\n return [scope for scope in self.scopes_list if scope.name == name]\n ", "context": "class ContextMock(syntax_tree.Definition):\n def FindScopes(self, name): ...\n def __init__(self, types_list, scopes_list, name, parent): ...\n def LookUpType(self, name): ...\n\n self.is_scope = True\n self.types_dict = dict([(type_defn.name, type_defn) for type_defn in types_list])\n self.scopes_list = scopes_list\n self.parent = parent\n\n defn_type = 'ContextMock'\n", "repository": "BladeSmithJohn/nixysa", "test_name": "testFindScopes", "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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000190.py"} {"focal_file": "nixysa/syntax_tree_unittest.py", "focal_class": null, "focal_method": "LookUpBindingModel", "tests": "import unittest\n\nclass Test_LookUpBindingModel(unittest.TestCase):\n def testLookUpBindingModel(self):\n self.assertEquals(self.typedef1.LookUpBindingModel(), 'bm1')\n self.assertEquals(self.typedef2.LookUpBindingModel(), 'bm1')\n self.assertRaises(syntax_tree.TypeNotFoundError, self.typedef3.LookUpBindingModel)\n self.assertEquals(self.typedef4.LookUpBindingModel(), 'bm2')\n self.assertEquals(self.typedef5.LookUpBindingModel(), 'bm3')\n", "method_code": " def LookUpBindingModel(self):\n return self.binding_model_name\n ", "context": "class DefinitionMock(syntax_tree.Definition):\n def LookUpBindingModel(self): ...\n def __init__(self, name, binding_model_name): ...\n\n self.binding_model_name = binding_model_name\n self.is_type = True\n\n defn_type = 'DefinitionMock'\n", "repository": "BladeSmithJohn/nixysa", "test_name": "testLookUpBindingModel", "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_000191.py"} {"focal_file": "playingcards.py", "focal_class": null, "focal_method": "suit", "tests": "import unittest\n\nclass Test_suit(unittest.TestCase):\n def test_correct_suit(self):\n c = Card(15, False)\n self.assertEqual(c.suit(), 'Diamonds')\n", "method_code": " def suit(self):\n \"\"\"Return the suit of the card as string\n \n input: none\n return: string\n \"\"\"\n return self.suitname\n ", "context": "class Card():\n def suit(self): ...\n def __init__(self, index, facedown=False): ...\n def name(self): ...\n def indexname(self): ...\n def image(self): ...\n def flip(self): ...\n def isdown(self): ...\n\n self.cardnames = ['Back', 'Ace', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King']\n self.imgdir = os.path.join(modpath, 'img')\n self.imgfile = ''\n self.backimg = ''\n self.facedown = facedown\n self.index = index\n self.cardname = self.cardnames[self.value]\n self.imgfn = '%d.png' % index\n", "repository": "ccdale/playingcards", "test_name": "test_correct_suit", "smells": [1, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000192.py"} {"focal_file": "playingcards.py", "focal_class": null, "focal_method": "isdown", "tests": "import unittest\n\nclass Test_isdown(unittest.TestCase):\n def test_isdown(self):\n c = Card(7, True)\n self.assertEqual(c.isdown(), True)\n", "method_code": " def isdown(self):\n \"\"\"Returns True if card is currently facedown\n \n input: none\n returns: boolean\n \"\"\"\n return self.facedown\n ", "context": "class Card():\n def isdown(self): ...\n def __init__(self, index, facedown=False): ...\n def name(self): ...\n def suit(self): ...\n def indexname(self): ...\n def image(self): ...\n def flip(self): ...\n\n self.cardnames = ['Back', 'Ace', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King']\n self.imgdir = os.path.join(modpath, 'img')\n self.imgfile = ''\n self.backimg = ''\n self.facedown = facedown\n self.index = index\n self.cardname = self.cardnames[self.value]\n self.imgfn = '%d.png' % index\n", "repository": "ccdale/playingcards", "test_name": "test_isdown", "smells": [1, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000193.py"} {"focal_file": "playingcards.py", "focal_class": null, "focal_method": "length", "tests": "import unittest\n\nclass Test_length(unittest.TestCase):\n def test_stacklength(self):\n s = Stack(1)\n self.assertEqual(s.length(), 52)\n", "method_code": " def length(self):\n \"\"\"Returns the number of cards in the stack\n \n input: None\n returns: integer\n \"\"\"\n return len(self.cards)\n ", "context": "class Stack():\n def length(self): ...\n def __init__(self, numberofdecks=0, noaces=0): ...\n def addnewcard(self, index): ...\n def addcard(self, card): ...\n def addtopcard(self, card): ...\n def initfull(self, numberofdecks=1): ...\n def initnoaces(self): ...\n def shuffle(self): ...\n def topcard(self): ...\n def bottomcard(self): ...\n def getbottomcard(self): ...\n def gettopcard(self): ...\n def getcard(self, index): ...\n def getncards(self, n): ...\n def addncards(self, ncards): ...\n def status(self): ...\n\n self.cards = []\n", "repository": "ccdale/playingcards", "test_name": "test_stacklength", "smells": [1, 1, 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": [0, 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": "playingcards.py", "focal_class": null, "focal_method": "getbottomcard", "tests": "import unittest\n\nclass Test_getbottomcard(unittest.TestCase):\n def test_get_bottom_card(self):\n s = Stack(1)\n c = s.getbottomcard()\n l = s.length()\n if l < 52:\n self.assertEqual(c.name(), 'King of Clubs')\n else:\n self.assertEqual(l, 51)\n", "method_code": " def getbottomcard(self):\n \"\"\"Returns the bottom card removing it from the Stack\n \n input: None\n returns: Card\n \"\"\"\n if len(self.cards):\n return self.cards.pop()\n return None\n ", "context": "class Stack():\n def getbottomcard(self): ...\n def __init__(self, numberofdecks=0, noaces=0): ...\n def addnewcard(self, index): ...\n def addcard(self, card): ...\n def addtopcard(self, card): ...\n def initfull(self, numberofdecks=1): ...\n def initnoaces(self): ...\n def length(self): ...\n def shuffle(self): ...\n def topcard(self): ...\n def bottomcard(self): ...\n def gettopcard(self): ...\n def getcard(self, index): ...\n def getncards(self, n): ...\n def addncards(self, ncards): ...\n def status(self): ...\n\n self.cards = []\n", "repository": "ccdale/playingcards", "test_name": "test_get_bottom_card", "smells": [1, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000195.py"} {"focal_file": "playingcards.py", "focal_class": null, "focal_method": "getncards", "tests": "import unittest\n\nclass Test_getncards(unittest.TestCase):\n def test_getncards(self):\n s = Stack(1)\n cs = s.getncards(5)\n l = s.length()\n if l < 48:\n self.assertEqual(len(cs), 5)\n else:\n self.assertEqual(l, 47)\n", "method_code": " def getncards(self, n):\n \"\"\"Returns the top n cards and removes them from the Stack\n If n > len(self.cards) then len(self.cards) cards are\n returned (or None if there are no cards in this Stack)\n \n n: number of cards to remove\n returns: [Cards]\n \"\"\"\n l = len(self.cards)\n if l > n:\n t = self.cards[:n]\n self.cards = self.cards[n:]\n else:\n t = self.cards\n self.cards = []\n return t\n ", "context": "class Stack():\n def getncards(self, n): ...\n def __init__(self, numberofdecks=0, noaces=0): ...\n def addnewcard(self, index): ...\n def addcard(self, card): ...\n def addtopcard(self, card): ...\n def initfull(self, numberofdecks=1): ...\n def initnoaces(self): ...\n def length(self): ...\n def shuffle(self): ...\n def topcard(self): ...\n def bottomcard(self): ...\n def getbottomcard(self): ...\n def gettopcard(self): ...\n def getcard(self, index): ...\n def addncards(self, ncards): ...\n def status(self): ...\n\n self.cards = []\n", "repository": "ccdale/playingcards", "test_name": "test_getncards", "smells": [1, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000196.py"} {"focal_file": "playingcards.py", "focal_class": null, "focal_method": "addncards", "tests": "import unittest\n\nclass Test_addncards(unittest.TestCase):\n def test_addncards(self):\n s = Stack(1)\n cs = s.getncards(5)\n l = s.length()\n if l < 48:\n s.addncards(cs)\n self.assertEqual(s.length(), 52)\n else:\n self.assertEqual(l, 47)\n", "method_code": " def addncards(self, ncards):\n \"\"\"Adds the list of cards to the bottom of this Stack\n \n ncards: [Cards]\n returns: None\n \"\"\"\n if len(ncards) > 0:\n for card in ncards:\n self.addcard(card)\n ", "context": "class Stack():\n def addncards(self, ncards): ...\n def __init__(self, numberofdecks=0, noaces=0): ...\n def addnewcard(self, index): ...\n def addcard(self, card): ...\n def addtopcard(self, card): ...\n def initfull(self, numberofdecks=1): ...\n def initnoaces(self): ...\n def length(self): ...\n def shuffle(self): ...\n def topcard(self): ...\n def bottomcard(self): ...\n def getbottomcard(self): ...\n def gettopcard(self): ...\n def getcard(self, index): ...\n def getncards(self, n): ...\n def status(self): ...\n\n self.cards = []\n", "repository": "ccdale/playingcards", "test_name": "test_addncards", "smells": [1, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000197.py"} {"focal_file": "apnsclient/apns.py", "focal_class": null, "focal_method": "get_json_payload", "tests": "import unittest\n\nclass Test_get_json_payload(unittest.TestCase):\n def test_payload(self):\n payload = self.message.get_json_payload()\n self.assertIsInstance(payload, six.binary_type)\n unicode_src = payload.decode('utf-8')\n payload = json.loads(unicode_src)\n self.assertEqual(payload['aps'], {'alert': self.message.alert, 'badge': self.message.badge, 'sound': self.message.sound, 'content-available': self.message.content_available})\n for k, v in self.message.extra.items():\n self.assertEqual(payload[k], v)\n", "method_code": " def get_json_payload(self):\n \"\"\" Convert message to JSON payload, acceptable by APNs. Must return byte string. \"\"\"\n payload = self.payload\n if not isinstance(payload, six.string_types) and (not isinstance(payload, six.binary_type)):\n payload = json.dumps(payload, **self.json_parameters)\n if not isinstance(payload, six.binary_type):\n payload = payload.encode('utf-8')\n return payload\n ", "context": "class Message(object):\n def get_json_payload(self): ...\n def __init__(self, tokens, alert=None, badge=None, sound=None, content_available=None, expiry=None, payload=None, priority=DEFAULT_PRIORITY, extra=None, **extra_kwargs): ...\n def _get_expiry_timestamp(self, expiry): ...\n def _get_current_datetime(self): ...\n def __getstate__(self): ...\n def __setstate__(self, state): ...\n def tokens(self): ...\n def payload(self): ...\n def batch(self, packet_size): ...\n def retry(self, failed_index, include_failed): ...\n\n self._tokens = tokens\n self._payload = payload\n self.priority = int(priority)\n self.expiry = self._get_expiry_timestamp(expiry)\n\n json_parameters = {'separators': (',', ':'), 'ensure_ascii': False}\n DEFAULT_EXPIRY = datetime.timedelta(days=1)\n DEFAULT_PRIORITY = 10\n", "repository": "brooklynpacket/apns-client", "test_name": "test_payload", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 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_000198.py"} {"focal_file": "apnsclient/apns.py", "focal_class": null, "focal_method": "batch", "tests": "import unittest\n\nclass Test_batch(unittest.TestCase):\n def test_batch(self):\n b_message = list(self.message.batch(10))\n b_raw_message = list(self.raw_message.batch(10))\n self.assertEqual(len(b_message), 1)\n self.assertEqual(len(b_raw_message), 2)\n self.check_message(b_message[0], 0, self.message)\n self.check_message(b_raw_message[0], 0, self.raw_message)\n self.check_message(b_raw_message[1], 1, self.raw_message)\n", "method_code": " def batch(self, packet_size):\n \"\"\" Returns binary serializer. \"\"\"\n payload = self.get_json_payload()\n assert isinstance(payload, six.binary_type), 'Payload must be bytes/binary'\n return Batch(self._tokens, payload, self.expiry, self.priority, packet_size)\n ", "context": "class Message(object):\n def batch(self, packet_size): ...\n def __init__(self, tokens, alert=None, badge=None, sound=None, content_available=None, expiry=None, payload=None, priority=DEFAULT_PRIORITY, extra=None, **extra_kwargs): ...\n def _get_expiry_timestamp(self, expiry): ...\n def _get_current_datetime(self): ...\n def __getstate__(self): ...\n def __setstate__(self, state): ...\n def tokens(self): ...\n def payload(self): ...\n def get_json_payload(self): ...\n def retry(self, failed_index, include_failed): ...\n\n self._tokens = tokens\n self._payload = payload\n self.priority = int(priority)\n self.expiry = self._get_expiry_timestamp(expiry)\n\n json_parameters = {'separators': (',', ':'), 'ensure_ascii': False}\n DEFAULT_EXPIRY = datetime.timedelta(days=1)\n DEFAULT_PRIORITY = 10\n", "repository": "brooklynpacket/apns-client", "test_name": "test_batch", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 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_000199.py"} {"focal_file": "apnsclient/apns.py", "focal_class": null, "focal_method": "retry", "tests": "import unittest\n\nclass Test_retry(unittest.TestCase):\n def test_retry(self):\n r_message = self.message.retry(0, True)\n for key in ('tokens', 'alert', 'badge', 'sound', 'content_available', 'expiry', 'priority', 'extra'):\n self.assertEqual(getattr(self.message, key), getattr(r_message, key))\n self.assertEqual(self.message.retry(0, False), None)\n r_raw_message = self.raw_message.retry(0, True)\n for key in ('tokens', 'alert', 'badge', 'sound', 'content_available', 'expiry', 'priority', 'extra'):\n self.assertEqual(getattr(self.raw_message, key), getattr(r_raw_message, key))\n r_raw_message = self.raw_message.retry(0, False)\n self.assertEqual(self.raw_message.tokens[1:], r_raw_message.tokens)\n for key in ('alert', 'badge', 'sound', 'content_available', 'expiry', 'priority', 'extra'):\n self.assertEqual(getattr(self.raw_message, key), getattr(r_raw_message, key))\n", "method_code": " def retry(self, failed_index, include_failed):\n \"\"\" Create new retry message with tokens from failed index. \"\"\"\n if not include_failed:\n failed_index += 1\n failed = self._tokens[failed_index:]\n if not failed:\n return None\n state = self.__getstate__()\n state['tokens'] = failed\n return Message(**state)\n ", "context": "class Message(object):\n def retry(self, failed_index, include_failed): ...\n def __init__(self, tokens, alert=None, badge=None, sound=None, content_available=None, expiry=None, payload=None, priority=DEFAULT_PRIORITY, extra=None, **extra_kwargs): ...\n def _get_expiry_timestamp(self, expiry): ...\n def _get_current_datetime(self): ...\n def __getstate__(self): ...\n def __setstate__(self, state): ...\n def tokens(self): ...\n def payload(self): ...\n def get_json_payload(self): ...\n def batch(self, packet_size): ...\n\n self._tokens = tokens\n self._payload = payload\n self.priority = int(priority)\n self.expiry = self._get_expiry_timestamp(expiry)\n\n json_parameters = {'separators': (',', ':'), 'ensure_ascii': False}\n DEFAULT_EXPIRY = datetime.timedelta(days=1)\n DEFAULT_PRIORITY = 10\n", "repository": "brooklynpacket/apns-client", "test_name": "test_retry", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000200.py"} {"focal_file": "apnsclient/apns.py", "focal_class": "Message", "focal_method": "send", "tests": "import unittest\n\nclass Test_Message_send(unittest.TestCase):\n def test_send(self):\n backend = DummyBackend(push=(None, 1, 3))\n session = Session(pool=backend)\n msg = Message(['0123456789ABCDEF', 'FEDCBA9876543210'], alert='my alert', badge=10, content_available=1, my_extra=15)\n push_con = session.get_connection('push_production', cert_string='certificate')\n srv = APNs(push_con)\n res = srv.send(msg)\n self.assertEqual(len(res.failed), 0)\n self.assertEqual(len(res.errors), 0)\n self.assertFalse(res.needs_retry())\n push_con2 = session.get_connection('push_production', cert_string='certificate')\n srv = APNs(push_con2)\n self.assertEqual(session.pool.push_result_pos, 0)\n session.pool.push_result_pos += 1\n res = srv.send(msg)\n self.assertEqual(len(res.failed), 0)\n self.assertEqual(len(res.errors), 1)\n self.assertTrue(res.needs_retry())\n self.assertEqual(session.pool.new_connections, 1)\n push_con = session.new_connection('push_production', cert_string='certificate')\n srv = APNs(push_con)\n res = srv.send(msg)\n self.assertEqual(len(res.failed), 0)\n self.assertEqual(len(res.errors), 1)\n self.assertFalse(res.needs_retry())\n self.assertEqual(session.pool.new_connections, 2)\n", "method_code": " def send(self, message):\n \"\"\" Send the message.\n \n The method will block until the whole message is sent. The method\n returns :class:`Result` object, which you can examine for possible\n errors and retry attempts.\n \n .. note::\n If the client fails to connect to APNs, probably because your\n network is down, then this method will raise the related\n exception. However, if connection is successfully established,\n but later on the IO fails, then this method will prepare a\n retry message with the rest of the failed tokens.\n \n Example::\n \n # if you use cached connections, then store this session instance\n # somewhere global, such that it will not be garbage collected\n # after message is sent.\n session = Session()\n # get a cached connection, avoiding unnecessary SSL handshake\n con = session.get_connection(\"push_production\", cert_string=db_certificate)\n message = Message([\"token 1\", \"token 2\"], alert=\"Message\")\n service = APNs(con)\n try:\n result = service.send(message)\n except:\n print \"Check your network, I could not connect to APNs\"\n else:\n for token, (reason, explanation) in result.failed.items():\n delete_token(token) # stop using that token\n \n for reason, explanation in result.errors:\n pass # handle generic errors\n \n if result.needs_retry():\n # extract failed tokens as new message\n message = message.retry()\n # re-schedule task with the new message after some delay\n \n :Returns:\n :class:`Result` object with operation results.\n \"\"\"\n if len(message.tokens) == 0:\n LOG.warning('Message without device tokens is ignored')\n return Result(message)\n status = self._connection.send(message)\n return Result(message, status)\n ", "context": "class APNs(object):\n def send(self, message): ...\n def __init__(self, connection): ...\n def feedback(self): ...\n def _datetime_from_timestamp(self, timestamp): ...\n\n self._connection = connection\n", "repository": "brooklynpacket/apns-client", "test_name": "test_send", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 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, 0, 0, 0], "pynose_source_file": "test_000201.py"} {"focal_file": "apnsclient/apns.py", "focal_class": "APNs", "focal_method": "feedback", "tests": "import unittest\n\nclass Test_APNs_feedback(unittest.TestCase):\n def test_feedback(self):\n backend = DummyBackend(feedback=5)\n session = Session(pool=backend)\n feed_con = session.new_connection('feedback_production', cert_string='certificate')\n srv = APNs(feed_con)\n self.assertEqual(len(list(srv.feedback())), 5)\n", "method_code": " def feedback(self):\n \"\"\" Fetch feedback from APNs.\n \n The method returns generator of ``(token, datetime)`` pairs,\n denoting the timestamp when APNs has detected the device token is\n not available anymore, probably because application was\n uninstalled. You have to stop sending notifications to that device\n token unless it has been re-registered since reported timestamp.\n \n Unlike sending the message, you should fetch the feedback using\n non-cached connection. Once whole feedback has been read, this\n method will automatically close the connection.\n \n .. note::\n If the client fails to connect to APNs, probably because your\n network is down, then this method will raise the related\n exception. However, if connection is successfully established,\n but later on the IO fails, then this method will simply stop\n iterating. The rest of the failed tokens will be delivered\n during the next feedback session.\n \n Example::\n \n session = Session()\n # get non-cached connection, free from possible garbage\n con = session.new_connection(\"feedback_production\", cert_string=db_certificate)\n service = APNs(con)\n try:\n # on any IO failure after successfull connection this generator\n # will simply stop iterating. you will pick the rest of the tokens\n # during next feedback session.\n for token, when in service.feedback():\n # every time a devices sends you a token, you should store\n # {token: given_token, last_update: datetime.datetime.now()}\n last_update = get_last_update_of_token(token)\n \n if last_update < when:\n # the token wasn't updated after the failure has\n # been reported, so the token is invalid and you should\n # stop sending messages to it.\n remove_token(token)\n except:\n print \"Check your network, I could not connect to APNs\"\n \n :Returns:\n generator over ``(binary, datetime)``\n \"\"\"\n for token, timestamp in self._connection.feedback():\n yield (token, self._datetime_from_timestamp(timestamp))\n ", "context": "class APNs(object):\n def feedback(self): ...\n def __init__(self, connection): ...\n def send(self, message): ...\n def _datetime_from_timestamp(self, timestamp): ...\n\n self._connection = connection\n", "repository": "brooklynpacket/apns-client", "test_name": "test_feedback", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 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_000202.py"} {"focal_file": "luqum/check.py", "focal_class": "LuceneCheck", "focal_method": "check", "tests": "import unittest\n\nclass Test_LuceneCheck_check(unittest.TestCase):\n def test_check_ok(self):\n query = AndOperation(SearchField('f', FieldGroup(AndOperation(Boost(Proximity(Phrase('\"foo bar\"'), 4), '4.2'), Prohibit(Range('100', '200'))))), Group(OrOperation(Fuzzy(Word('baz'), '.8'), Plus(Word('fizz')))))\n check = LuceneCheck()\n self.assertTrue(check(query))\n self.assertEqual(check.errors(query), [])\n check = LuceneCheck(zeal=1)\n self.assertTrue(check(query))\n self.assertEqual(check.errors(query), [])\n", "method_code": " def check(self, item, parents=[]):\n for cls in item.__class__.mro():\n meth = getattr(self, 'check_' + camel_to_lower(cls.__name__), None)\n if meth is not None:\n yield from meth(item, parents)\n break\n else:\n yield ('Unknown item type %s : %s' % (item.__class__.__name__, str(item)))\n ", "context": "class LuceneCheck():\n def check(self, item, parents=[]): ...\n def __init__(self, zeal=0): ...\n def _check_field_name(self, fname): ...\n def check_search_field(self, item, parents): ...\n def check_group(self, item, parents): ...\n def check_field_group(self, item, parents): ...\n def check_range(self, item, parents): ...\n def check_word(self, item, parents): ...\n def check_fuzzy(self, item, parents): ...\n def check_proximity(self, item, parents): ...\n def check_boost(self, item, parents): ...\n def check_base_operation(self, item, parents): ...\n def check_plus(self, item, parents): ...\n def _check_not_operator(self, item, parents): ...\n def check_not(self, item, parents): ...\n def check_prohibit(self, item, parents): ...\n def __call__(self, tree): ...\n def errors(self, tree): ...\n\n self.zeal = zeal\n\n field_name_re = re.compile('^\\\\w+$')\n space_re = re.compile('\\\\s')\n invalid_term_chars_re = re.compile('[+/-]')\n SIMPLE_EXPR_FIELDS = (tree.Boost, tree.Proximity, tree.Fuzzy, tree.Word, tree.Phrase)\n FIELD_EXPR_FIELDS = tuple(list(SIMPLE_EXPR_FIELDS) + [tree.FieldGroup])\n", "repository": "jurismarches/luqum", "test_name": "test_check_ok", "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_000203.py"} {"focal_file": "luqum/check.py", "focal_class": "LuceneCheck", "focal_method": "errors", "tests": "import unittest\n\nclass Test_LuceneCheck_errors(unittest.TestCase):\n def test_zealous_or_not(self):\n query = OrOperation(Not(Word('foo')), Word('bar'))\n check_zealous = LuceneCheck(zeal=1)\n self.assertFalse(check_zealous(query))\n self.assertIn('inconsistent', check_zealous.errors(query)[0])\n check_easy_going = LuceneCheck()\n self.assertTrue(check_easy_going(query))\n", "method_code": " def errors(self, tree):\n \"\"\"List all errors\"\"\"\n return list(self.check(tree))\n ", "context": "class LuceneCheck():\n def errors(self, tree): ...\n def __init__(self, zeal=0): ...\n def _check_field_name(self, fname): ...\n def check_search_field(self, item, parents): ...\n def check_group(self, item, parents): ...\n def check_field_group(self, item, parents): ...\n def check_range(self, item, parents): ...\n def check_word(self, item, parents): ...\n def check_fuzzy(self, item, parents): ...\n def check_proximity(self, item, parents): ...\n def check_boost(self, item, parents): ...\n def check_base_operation(self, item, parents): ...\n def check_plus(self, item, parents): ...\n def _check_not_operator(self, item, parents): ...\n def check_not(self, item, parents): ...\n def check_prohibit(self, item, parents): ...\n def check(self, item, parents=[]): ...\n def __call__(self, tree): ...\n\n self.zeal = zeal\n\n field_name_re = re.compile('^\\\\w+$')\n space_re = re.compile('\\\\s')\n invalid_term_chars_re = re.compile('[+/-]')\n SIMPLE_EXPR_FIELDS = (tree.Boost, tree.Proximity, tree.Fuzzy, tree.Word, tree.Phrase)\n FIELD_EXPR_FIELDS = tuple(list(SIMPLE_EXPR_FIELDS) + [tree.FieldGroup])\n", "repository": "jurismarches/luqum", "test_name": "test_zealous_or_not", "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_000204.py"} {"focal_file": "luqum/deprecated_utils.py", "focal_class": "LuceneTreeVisitor", "focal_method": "visit", "tests": "import unittest\n\nclass Test_LuceneTreeVisitor_visit(unittest.TestCase):\n def test_generic_visit(self):\n tree = AndOperation(Word('foo'), Word('bar'))\n visitor = LuceneTreeVisitor()\n nodes = list(visitor.visit(tree))\n self.assertEqual(nodes, [])\n", "method_code": " def visit(self, node, parents=None):\n \"\"\" Basic, recursive traversal of the tree. \"\"\"\n warnings.warn('LuceneTreeVisitor is deprecated in favor of visitor.TreeVisitor', DeprecationWarning)\n parents = parents or []\n method = self._get_method(node)\n yield from method(node, parents)\n for child in node.children:\n yield from self.visit(child, parents + [node])\n ", "context": "class LuceneTreeVisitor():\n def visit(self, node, parents=None): ...\n def _get_method(self, node): ...\n def generic_visit(self, node, parents=None): ...\n\n visitor_method_prefix = 'visit_'\n generic_visitor_method_name = 'generic_visit'\n _get_method_cache = None\n", "repository": "jurismarches/luqum", "test_name": "test_generic_visit", "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_000205.py"} {"focal_file": "luqum/deprecated_utils.py", "focal_class": null, "focal_method": "visit", "tests": "import unittest\n\nclass Test_visit(unittest.TestCase):\n def test_no_transform(self):\n tree = AndOperation()\n transformer = self.BasicTransformer()\n new_tree = transformer.visit(tree)\n self.assertEqual(new_tree, AndOperation())\n", "method_code": " def visit(self, node, parents=None):\n \"\"\" Basic, recursive traversal of the tree. \"\"\"\n warnings.warn('LuceneTreeVisitor is deprecated in favor of visitor.TreeVisitor', DeprecationWarning)\n parents = parents or []\n method = self._get_method(node)\n yield from method(node, parents)\n for child in node.children:\n yield from self.visit(child, parents + [node])\n ", "context": "class LuceneTreeVisitor():\n def visit(self, node, parents=None): ...\n def _get_method(self, node): ...\n def generic_visit(self, node, parents=None): ...\n\n visitor_method_prefix = 'visit_'\n generic_visitor_method_name = 'generic_visit'\n _get_method_cache = None\n", "repository": "jurismarches/luqum", "test_name": "test_no_transform", "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_000206.py"} {"focal_file": "luqum/head_tail.py", "focal_class": null, "focal_method": "pos", "tests": "import unittest\n\nclass Test_pos(unittest.TestCase):\n def test_pos(self):\n p = [Item(), Item(pos=4, size=3)]\n self.headtail.pos(p)\n self.assertEqual(p[0].pos, 4)\n self.assertEqual(p[0].size, 3)\n", "method_code": " def pos(self, p, head_transfer=False, tail_transfer=False):\n \"\"\"Compute pos and size of element 0 based on it's parts (p[1:])\n \n :param list p: the parser expression as in PLY\n :param bool head_transfer: True if head of first child will be transfered to p[0]\n :param bool tail_transfer: True if tail of last child wiil be transfered to p[0]\n \"\"\"\n if p[1].pos is not None:\n p[0].pos = p[1].pos\n if not head_transfer:\n p[0].pos -= len(p[1].head)\n p[0].size = sum(((elt.size or 0) + len(elt.head or '') + len(elt.tail or '') for elt in p[1:]))\n if head_transfer and p[1].head:\n p[0].size -= len(p[1].head)\n last_p = p[len(p) - 1]\n if tail_transfer and last_p.tail:\n p[0].size -= len(last_p.tail)\n ", "context": "class HeadTailManager():\n def pos(self, p, head_transfer=False, tail_transfer=False): ...\n def binary_operation(self, p, op_tail): ...\n def simple_term(self, p): ...\n def unary(self, p): ...\n def post_unary(self, p): ...\n def paren(self, p): ...\n def range(self, p): ...\n def search_field(self, p): ...\n", "repository": "jurismarches/luqum", "test_name": "test_pos", "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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000207.py"} {"focal_file": "luqum/head_tail.py", "focal_class": null, "focal_method": "binary_operation", "tests": "import unittest\n\nclass Test_binary_operation(unittest.TestCase):\n def test_binary_operation(self):\n p = [Item(), Item(pos=1, size=3, head='\\t', tail='\\n'), Item(pos=4, size=4, head='\\r', tail=' ')]\n self.headtail.binary_operation(p, op_tail='')\n self.assertEqual(p[0].pos, 0)\n self.assertEqual(p[0].size, 12)\n self.headtail.binary_operation(p, op_tail=' ')\n self.assertEqual(p[0].pos, 0)\n self.assertEqual(p[0].size, 10)\n", "method_code": " def binary_operation(self, p, op_tail):\n self.pos(p, head_transfer=False, tail_transfer=False)\n p[0].size -= len(op_tail)\n ", "context": "class HeadTailManager():\n def binary_operation(self, p, op_tail): ...\n def pos(self, p, head_transfer=False, tail_transfer=False): ...\n def simple_term(self, p): ...\n def unary(self, p): ...\n def post_unary(self, p): ...\n def paren(self, p): ...\n def range(self, p): ...\n def search_field(self, p): ...\n", "repository": "jurismarches/luqum", "test_name": "test_binary_operation", "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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000208.py"} {"focal_file": "luqum/head_tail.py", "focal_class": null, "focal_method": "simple_term", "tests": "import unittest\n\nclass Test_simple_term(unittest.TestCase):\n def test_simple_term(self):\n p = [Item(), Item(pos=4, size=3, head='\\t', tail='\\r')]\n self.headtail.simple_term(p)\n self.assertEqual(p[0].head, '\\t')\n self.assertEqual(p[0].tail, '\\r')\n self.assertEqual(p[0].pos, 4)\n self.assertEqual(p[0].size, 3)\n", "method_code": " def simple_term(self, p):\n self.pos(p, head_transfer=True, tail_transfer=True)\n p[0].head = p[1].head\n p[0].tail = p[1].tail\n ", "context": "class HeadTailManager():\n def simple_term(self, p): ...\n def pos(self, p, head_transfer=False, tail_transfer=False): ...\n def binary_operation(self, p, op_tail): ...\n def unary(self, p): ...\n def post_unary(self, p): ...\n def paren(self, p): ...\n def range(self, p): ...\n def search_field(self, p): ...\n", "repository": "jurismarches/luqum", "test_name": "test_simple_term", "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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000209.py"} {"focal_file": "luqum/head_tail.py", "focal_class": null, "focal_method": "unary", "tests": "import unittest\n\nclass Test_unary(unittest.TestCase):\n def test_unary(self):\n p = [Item(), Item(head='\\t', tail='\\r', pos=3, size=3), Item(head='\\n', tail=' ', pos=5, size=5)]\n self.headtail.unary(p)\n self.assertEqual(p[0].head, '\\t')\n self.assertEqual(p[0].tail, '')\n self.assertEqual(p[0].pos, 3)\n self.assertEqual(p[0].size, 12)\n self.assertEqual(p[2].head, '\\r\\n')\n self.assertEqual(p[2].tail, ' ')\n self.assertEqual(p[2].pos, 5)\n self.assertEqual(p[2].size, 5)\n", "method_code": " def unary(self, p):\n \"\"\"OP expr\"\"\"\n self.pos(p, head_transfer=True, tail_transfer=False)\n p[0].head = p[1].head\n p[2].head = p[1].tail + p[2].head\n ", "context": "class HeadTailManager():\n def unary(self, p): ...\n def pos(self, p, head_transfer=False, tail_transfer=False): ...\n def binary_operation(self, p, op_tail): ...\n def simple_term(self, p): ...\n def post_unary(self, p): ...\n def paren(self, p): ...\n def range(self, p): ...\n def search_field(self, p): ...\n", "repository": "jurismarches/luqum", "test_name": "test_unary", "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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000210.py"} {"focal_file": "luqum/head_tail.py", "focal_class": null, "focal_method": "post_unary", "tests": "import unittest\n\nclass Test_post_unary(unittest.TestCase):\n def test_post_unary(self):\n p = [Item(), Item(head='\\t', tail='\\r', pos=3, size=3), Item(head='\\n', tail=' ', pos=5, size=5)]\n self.headtail.post_unary(p)\n self.assertEqual(p[0].head, '')\n self.assertEqual(p[0].tail, ' ')\n self.assertEqual(p[0].pos, 2)\n self.assertEqual(p[0].size, 11)\n self.assertEqual(p[1].head, '\\t')\n self.assertEqual(p[1].tail, '\\r\\n')\n self.assertEqual(p[1].pos, 3)\n self.assertEqual(p[1].pos, 3)\n", "method_code": " def post_unary(self, p):\n \"\"\"expr OP\"\"\"\n self.pos(p, head_transfer=False, tail_transfer=True)\n p[1].tail += p[2].head\n p[0].tail = p[2].tail\n ", "context": "class HeadTailManager():\n def post_unary(self, p): ...\n def pos(self, p, head_transfer=False, tail_transfer=False): ...\n def binary_operation(self, p, op_tail): ...\n def simple_term(self, p): ...\n def unary(self, p): ...\n def paren(self, p): ...\n def range(self, p): ...\n def search_field(self, p): ...\n", "repository": "jurismarches/luqum", "test_name": "test_post_unary", "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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000211.py"} {"focal_file": "luqum/head_tail.py", "focal_class": null, "focal_method": "paren", "tests": "import unittest\n\nclass Test_paren(unittest.TestCase):\n def test_paren(self):\n p = [Item(), Item(head='\\t', tail='\\r', pos=3, size=1), Item(head='\\n', tail=' ', pos=5, size=3), Item(head='\\n\\n', tail='\\t\\t', pos=7, size=1)]\n self.headtail.paren(p)\n self.assertEqual(p[0].head, '\\t')\n self.assertEqual(p[0].tail, '\\t\\t')\n self.assertEqual(p[0].pos, 3)\n self.assertEqual(p[0].size, 11)\n self.assertEqual(p[2].head, '\\r\\n')\n self.assertEqual(p[2].tail, ' \\n\\n')\n self.assertEqual(p[2].pos, 5)\n self.assertEqual(p[2].size, 3)\n", "method_code": " def paren(self, p):\n \"\"\"( expr )\"\"\"\n self.pos(p, head_transfer=True, tail_transfer=True)\n p[0].head = p[1].head\n p[2].head = p[1].tail + p[2].head\n p[2].tail += p[3].head\n p[0].tail = p[3].tail\n ", "context": "class HeadTailManager():\n def paren(self, p): ...\n def pos(self, p, head_transfer=False, tail_transfer=False): ...\n def binary_operation(self, p, op_tail): ...\n def simple_term(self, p): ...\n def unary(self, p): ...\n def post_unary(self, p): ...\n def range(self, p): ...\n def search_field(self, p): ...\n", "repository": "jurismarches/luqum", "test_name": "test_paren", "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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000212.py"} {"focal_file": "luqum/head_tail.py", "focal_class": null, "focal_method": "range", "tests": "import unittest\n\nclass Test_range(unittest.TestCase):\n def test_range(self):\n p = [Item(), Item(head='\\t', tail='\\r', pos=3, size=1), Item(head='\\n', tail=' ', pos=5, size=3), Item(head='\\n\\n', tail='\\t\\t', pos=7, size=2), Item(head='\\r\\r', tail=' \\t ', pos=9, size=5), Item(head=' \\r ', tail=' \\n ', pos=12, size=1)]\n self.headtail.range(p)\n self.assertEqual(p[0].head, '\\t')\n self.assertEqual(p[0].tail, ' \\n ')\n self.assertEqual(p[0].pos, 3)\n self.assertEqual(p[0].size, 28)\n self.assertEqual(p[2].head, '\\r\\n')\n self.assertEqual(p[2].tail, ' \\n\\n')\n self.assertEqual(p[2].pos, 5)\n self.assertEqual(p[2].size, 3)\n self.assertEqual(p[4].head, '\\t\\t\\r\\r')\n self.assertEqual(p[4].tail, ' \\t \\r ')\n self.assertEqual(p[4].pos, 9)\n self.assertEqual(p[4].size, 5)\n", "method_code": " def range(self, p):\n \"\"\"[ expr TO expr ]\"\"\"\n self.pos(p, head_transfer=True, tail_transfer=True)\n p[0].head = p[1].head\n p[2].head = p[1].tail + p[2].head\n p[2].tail += p[3].head\n p[4].head = p[3].tail + p[4].head\n p[4].tail += p[5].head\n p[0].tail = p[5].tail\n ", "context": "class HeadTailManager():\n def range(self, p): ...\n def pos(self, p, head_transfer=False, tail_transfer=False): ...\n def binary_operation(self, p, op_tail): ...\n def simple_term(self, p): ...\n def unary(self, p): ...\n def post_unary(self, p): ...\n def paren(self, p): ...\n def search_field(self, p): ...\n", "repository": "jurismarches/luqum", "test_name": "test_range", "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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000213.py"} {"focal_file": "luqum/head_tail.py", "focal_class": null, "focal_method": "search_field", "tests": "import unittest\n\nclass Test_search_field(unittest.TestCase):\n def test_search_field(self):\n p = [Item(), Item(head='\\t', tail='\\r', pos=3, size=3), Item(head='\\n', tail=' ', pos=5, size=1), Item(head='\\n\\n', tail='\\t\\t', pos=7, size=5)]\n self.headtail.search_field(p)\n self.assertEqual(p[0].head, '\\t')\n self.assertEqual(p[0].tail, '')\n self.assertEqual(p[0].pos, 3)\n self.assertEqual(p[0].size, 17)\n self.assertEqual(p[3].head, ' \\n\\n')\n self.assertEqual(p[3].tail, '\\t\\t')\n self.assertEqual(p[3].pos, 7)\n", "method_code": " def search_field(self, p):\n \"\"\"name: expr\"\"\"\n self.pos(p, head_transfer=True, tail_transfer=False)\n p[0].head = p[1].head\n if p[1].tail or p[2].head:\n pass\n p[3].head = p[2].tail + p[3].head\n ", "context": "class HeadTailManager():\n def search_field(self, p): ...\n def pos(self, p, head_transfer=False, tail_transfer=False): ...\n def binary_operation(self, p, op_tail): ...\n def simple_term(self, p): ...\n def unary(self, p): ...\n def post_unary(self, p): ...\n def paren(self, p): ...\n def range(self, p): ...\n", "repository": "jurismarches/luqum", "test_name": "test_search_field", "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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000214.py"} {"focal_file": "luqum/naming.py", "focal_class": null, "focal_method": "auto_name", "tests": "import unittest\n\nclass Test_auto_name(unittest.TestCase):\n def test_auto_name_one_term(self):\n tree = Word('test')\n names = auto_name(tree)\n self.assertEqual(get_name(tree), 'a')\n self.assertEqual(names, {'a': ()})\n tree = Phrase('\"test\"')\n names = auto_name(tree)\n self.assertEqual(get_name(tree), 'a')\n self.assertEqual(names, {'a': ()})\n tree = Range(Word('test'), Word('*'))\n names = auto_name(tree)\n self.assertEqual(get_name(tree), 'a')\n self.assertEqual(names, {'a': ()})\n tree = Regex('/test/')\n names = auto_name(tree)\n self.assertEqual(get_name(tree), 'a')\n self.assertEqual(names, {'a': ()})\n\n def test_auto_name_simple_op(self):\n for OpCls in (AndOperation, OrOperation, UnknownOperation):\n with self.subTest('operation %r' % OpCls):\n tree = OpCls(Word('test'), Phrase('\"test\"'))\n names = auto_name(tree)\n self.assertEqual(get_name(tree), None)\n self.assertEqual(get_name(tree.children[0]), 'a')\n self.assertEqual(get_name(tree.children[1]), 'b')\n self.assertEqual(names, {'a': (0,), 'b': (1,)})\n\n def test_auto_name_nested(self):\n tree = AndOperation(OrOperation(SearchField('bar', Word('test')), AndOperation(Proximity(Phrase('\"test\"'), 2), SearchField('baz', Word('test')))), Group(UnknownOperation(Fuzzy(Word('test')), Phrase('\"test\"'))))\n names = auto_name(tree)\n self.assertEqual(sorted(names.keys()), list('abcdefgh'))\n and1 = tree\n self.assertEqual(get_name(and1), None)\n or1 = and1.children[0]\n self.assertEqual(get_name(or1), 'a')\n self.assertEqual(names['a'], (0,))\n sfield1 = or1.children[0]\n self.assertEqual(get_name(sfield1), 'c')\n self.assertEqual(names['c'], (0, 0))\n self.assertEqual(get_name(sfield1.expr), None)\n and2 = or1.children[1]\n self.assertEqual(get_name(and2), 'd')\n self.assertEqual(names['d'], (0, 1))\n self.assertEqual(get_name(and2.children[0]), 'e')\n self.assertEqual(names['e'], (0, 1, 0))\n self.assertEqual(get_name(and2.children[0].term), None)\n sfield2 = and2.children[1]\n self.assertEqual(get_name(sfield2), 'f')\n self.assertEqual(names['f'], (0, 1, 1))\n self.assertEqual(get_name(sfield2.expr), None)\n group1 = and1.children[1]\n self.assertEqual(get_name(group1), 'b')\n self.assertEqual(names['b'], (1,))\n unknownop1 = group1.children[0]\n self.assertEqual(get_name(unknownop1), None)\n self.assertEqual(get_name(unknownop1.children[0]), 'g')\n self.assertEqual(names['g'], (1, 0, 0))\n self.assertEqual(get_name(unknownop1.children[0].term), None)\n self.assertEqual(get_name(unknownop1.children[1]), 'h')\n self.assertEqual(names['h'], (1, 0, 1))\n\n def test_auto_name_integration(self):\n tree = AndOperation(SearchField('text', Phrase('\"foo bar\"')), Group(OrOperation(Word('bar'), SearchField('spam', Word('baz')))))\n auto_name(tree)\n expected = {'bool': {'must': [{'term': {'text': {'_name': 'a', 'value': 'foo bar'}}}, {'bool': {'should': [{'term': {'text': {'_name': 'c', 'value': 'bar'}}}, {'match': {'spam': {'_name': 'd', 'query': 'baz', 'zero_terms_query': 'none'}}}]}}]}}\n result = self.transformer(tree)\n self.assertEqual(result, expected)\n", "method_code": "def auto_name(tree, targets=None, all_names=False):\n \"\"\"Automatically add names to nodes of a parse tree, in order to be able to track matching.\n\n We add them to top nodes under operations as this is where it is useful for ES named queries\n\n :return dict: association of name with the path (as a tuple) to a the corresponding children\n \"\"\"\n return TreeAutoNamer().visit(tree)", "context": "def auto_name(tree, targets=None, all_names=False): ...\ndef set_name(node, value): ...\ndef get_name(node): ...\ndef auto_name(tree, targets=None, all_names=False): ...\ndef matching_from_names(names, name_to_path): ...\ndef element_from_path(tree, path): ...\ndef element_from_name(tree, name, name_to_path): ...\n", "repository": "jurismarches/luqum", "test_name": "test_auto_name_one_term", "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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000215.py"} {"focal_file": "luqum/naming.py", "focal_class": null, "focal_method": "matching_from_names", "tests": "import unittest\n\nclass Test_matching_from_names(unittest.TestCase):\n def test_matching_from_name(self):\n names = {'a': (0,), 'b': (1,), 'c': (0, 0), 'd': (0, 1), 'e': (1, 0, 1)}\n self.assertEqual(matching_from_names([], names), (set(), {(0,), (1,), (0, 0), (0, 1), (1, 0, 1)}))\n self.assertEqual(matching_from_names(['a', 'b'], names), ({(0,), (1,)}, {(0, 0), (0, 1), (1, 0, 1)}))\n self.assertEqual(matching_from_names(['a', 'e'], names), ({(0,), (1, 0, 1)}, {(1,), (0, 0), (0, 1)}))\n self.assertEqual(matching_from_names(['c'], names), ({(0, 0)}, {(0,), (1,), (0, 1), (1, 0, 1)}))\n with self.assertRaises(KeyError):\n matching_from_names(['x'], names)\n", "method_code": "def matching_from_names(names, name_to_path):\n \"\"\"Utility to convert a list of name and the result of auto_name\n to the matching parameter for :py:class:`MatchingPropagator`\n\n :param list names: list of names\n :param dict name_to_path: association of names with path to children\n :return tuple: (set of matching paths, set of other known paths)\n \"\"\"\n matching = {name_to_path[name] for name in names}\n return (matching, set(name_to_path.values()) - matching)", "context": "def matching_from_names(names, name_to_path): ...\ndef set_name(node, value): ...\ndef get_name(node): ...\ndef auto_name(tree, targets=None, all_names=False): ...\ndef matching_from_names(names, name_to_path): ...\ndef element_from_path(tree, path): ...\ndef element_from_name(tree, name, name_to_path): ...\n", "repository": "jurismarches/luqum", "test_name": "test_matching_from_name", "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_000216.py"} {"focal_file": "luqum/naming.py", "focal_class": null, "focal_method": "element_from_path", "tests": "import unittest\n\nclass Test_element_from_path(unittest.TestCase):\n def test_element_from_path(self):\n tree = AndOperation(OrOperation(SearchField('bar', Word('test')), Group(AndOperation(Proximity(Phrase('\"test\"'), 2), SearchField('baz', Word('test')), Fuzzy(Word('test')), Phrase('\"test\"')))))\n names = {'a': (), 'b': (0, 1), 'c': (0, 1, 0, 2), 'd': (0, 1, 0, 2, 0), 'e': (0, 1, 0, 3)}\n self.assertEqual(element_from_path(tree, ()), tree)\n self.assertEqual(element_from_name(tree, 'a', names), tree)\n self.assertEqual(element_from_path(tree, (0, 1)), tree.children[0].children[1])\n self.assertEqual(element_from_name(tree, 'b', names), tree.children[0].children[1])\n self.assertEqual(element_from_path(tree, (0, 1, 0, 2)), Fuzzy(Word('test')))\n self.assertEqual(element_from_name(tree, 'c', names), Fuzzy(Word('test')))\n self.assertEqual(element_from_path(tree, (0, 1, 0, 2, 0)), Word('test'))\n self.assertEqual(element_from_name(tree, 'd', names), Word('test'))\n self.assertEqual(element_from_path(tree, (0, 1, 0, 3)), Phrase('\"test\"'))\n self.assertEqual(element_from_name(tree, 'e', names), Phrase('\"test\"'))\n with self.assertRaises(IndexError):\n element_from_path(tree, (1,))\n", "method_code": "def element_from_path(tree, path):\n \"\"\"Given a tree, retrieve element corresponding to path\n\n :param luqum.tree.Item tree: luqum expression tree\n :param tuple path: tuple representing top down access to a child\n :return luqum.tree.Item: target item\n \"\"\"\n node = tree\n path = list(path)\n while path:\n node = node.children[path.pop(0)]\n return node", "context": "def element_from_path(tree, path): ...\ndef set_name(node, value): ...\ndef get_name(node): ...\ndef auto_name(tree, targets=None, all_names=False): ...\ndef matching_from_names(names, name_to_path): ...\ndef element_from_path(tree, path): ...\ndef element_from_name(tree, name, name_to_path): ...\n", "repository": "jurismarches/luqum", "test_name": "test_element_from_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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000217.py"} {"focal_file": "luqum/tree.py", "focal_class": "Term", "focal_method": "has_wildcard", "tests": "import unittest\n\nclass Test_Term_has_wildcard(unittest.TestCase):\n def test_term_wildcard_true(self):\n self.assertTrue(Term('ba*').has_wildcard())\n self.assertTrue(Term('b*r').has_wildcard())\n self.assertTrue(Term('*ar').has_wildcard())\n self.assertTrue(Term('ba?').has_wildcard())\n self.assertTrue(Term('b?r').has_wildcard())\n self.assertTrue(Term('?ar').has_wildcard())\n self.assertTrue(Term('?a*').has_wildcard())\n self.assertTrue(Term('\\\\?a*').has_wildcard())\n self.assertTrue(Term('?a\\\\*').has_wildcard())\n self.assertTrue(Term('*').has_wildcard())\n self.assertTrue(Term('?').has_wildcard())\n", "method_code": " def has_wildcard(self):\n \"\"\":return bool: True if value contains a wildcards\n \"\"\"\n return any(self.iter_wildcards())\n ", "context": "class Term(Item):\n def has_wildcard(self): ...\n def __init__(self, value, **kwargs): ...\n def unescaped_value(self): ...\n def is_wildcard(self): ...\n def iter_wildcards(self): ...\n def split_wildcards(self): ...\n def __str__(self, head_tail=False): ...\n def __repr__(self): ...\n\n self.value = value\n\n WILDCARDS_PATTERN = re.compile('((?<=[^\\\\\\\\])[?*]|^[?*])')\n WORD_ESCAPED_CHARS = re.compile('\\\\\\\\([+\\\\-&|!(){}[\\\\]^\"~*?:\\\\\\\\])')\n _equality_attrs = ['value']\n", "repository": "jurismarches/luqum", "test_name": "test_term_wildcard_true", "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_000218.py"} {"focal_file": "luqum/tree.py", "focal_class": "Term", "focal_method": "is_wildcard", "tests": "import unittest\n\nclass Test_Term_is_wildcard(unittest.TestCase):\n def test_term_is_only_a_wildcard(self):\n self.assertTrue(Term('*').is_wildcard())\n self.assertFalse(Term('*o').is_wildcard())\n self.assertFalse(Term('b*').is_wildcard())\n self.assertFalse(Term('b*o').is_wildcard())\n self.assertFalse(Term('?').is_wildcard())\n", "method_code": " def is_wildcard(self):\n \"\"\":return bool: True if value is the wildcard ``*``\n \"\"\"\n return self.value == '*'\n ", "context": "class Term(Item):\n def is_wildcard(self): ...\n def __init__(self, value, **kwargs): ...\n def unescaped_value(self): ...\n def iter_wildcards(self): ...\n def split_wildcards(self): ...\n def has_wildcard(self): ...\n def __str__(self, head_tail=False): ...\n def __repr__(self): ...\n\n self.value = value\n\n WILDCARDS_PATTERN = re.compile('((?<=[^\\\\\\\\])[?*]|^[?*])')\n WORD_ESCAPED_CHARS = re.compile('\\\\\\\\([+\\\\-&|!(){}[\\\\]^\"~*?:\\\\\\\\])')\n _equality_attrs = ['value']\n", "repository": "jurismarches/luqum", "test_name": "test_term_is_only_a_wildcard", "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_000219.py"} {"focal_file": "luqum/tree.py", "focal_class": "Term", "focal_method": "iter_wildcards", "tests": "import unittest\n\nclass Test_Term_iter_wildcards(unittest.TestCase):\n def test_term_iter_wildcard(self):\n self.assertListEqual(list(Term('a?b\\\\*or*and\\\\?').iter_wildcards()), [((1, 2), '?'), ((7, 8), '*')])\n self.assertListEqual(list(Term('\\\\**\\\\**').iter_wildcards()), [((2, 3), '*'), ((5, 6), '*')])\n", "method_code": " def iter_wildcards(self):\n \"\"\"list wildcards contained in value and their positions\n \"\"\"\n for matched in self.WILDCARDS_PATTERN.finditer(self.value):\n yield (matched.span(), matched.group())\n ", "context": "class Term(Item):\n def iter_wildcards(self): ...\n def __init__(self, value, **kwargs): ...\n def unescaped_value(self): ...\n def is_wildcard(self): ...\n def split_wildcards(self): ...\n def has_wildcard(self): ...\n def __str__(self, head_tail=False): ...\n def __repr__(self): ...\n\n self.value = value\n\n WILDCARDS_PATTERN = re.compile('((?<=[^\\\\\\\\])[?*]|^[?*])')\n WORD_ESCAPED_CHARS = re.compile('\\\\\\\\([+\\\\-&|!(){}[\\\\]^\"~*?:\\\\\\\\])')\n _equality_attrs = ['value']\n", "repository": "jurismarches/luqum", "test_name": "test_term_iter_wildcard", "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_000220.py"} {"focal_file": "luqum/tree.py", "focal_class": "Term", "focal_method": "split_wildcards", "tests": "import unittest\n\nclass Test_Term_split_wildcards(unittest.TestCase):\n def test_term_split_wildcard(self):\n self.assertListEqual(Term('a??b\\\\*or*and\\\\?').split_wildcards(), ['a', '?', '', '?', 'b\\\\*or', '*', 'and\\\\?'])\n self.assertListEqual(Term('\\\\**\\\\**').split_wildcards(), ['\\\\*', '*', '\\\\*', '*', ''])\n", "method_code": " def split_wildcards(self):\n \"\"\"split term on wildcards\n \"\"\"\n return self.WILDCARDS_PATTERN.split(self.value)\n ", "context": "class Term(Item):\n def split_wildcards(self): ...\n def __init__(self, value, **kwargs): ...\n def unescaped_value(self): ...\n def is_wildcard(self): ...\n def iter_wildcards(self): ...\n def has_wildcard(self): ...\n def __str__(self, head_tail=False): ...\n def __repr__(self): ...\n\n self.value = value\n\n WILDCARDS_PATTERN = re.compile('((?<=[^\\\\\\\\])[?*]|^[?*])')\n WORD_ESCAPED_CHARS = re.compile('\\\\\\\\([+\\\\-&|!(){}[\\\\]^\"~*?:\\\\\\\\])')\n _equality_attrs = ['value']\n", "repository": "jurismarches/luqum", "test_name": "test_term_split_wildcard", "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_000221.py"} {"focal_file": "luqum/visitor.py", "focal_class": "TreeVisitor", "focal_method": "visit", "tests": "import unittest\n\nclass Test_TreeVisitor_visit(unittest.TestCase):\n def test_generic_visit(self):\n tree = AndOperation(Word('foo'), Word('bar'))\n visitor = TreeVisitor()\n nodes = visitor.visit(tree)\n self.assertEqual(nodes, [])\n nodes = visitor.visit(tree, context={})\n self.assertEqual(nodes, [])\n", "method_code": " def visit(self, tree, context=None):\n \"\"\"Traversal of tree\n \n :param luqum.tree.Item tree: a tree representing a lucene expression\n :param dict context: a dict with initial values for context\n \n .. note:: the values in context, are not guaranteed to move up the hierachy,\n because we do copy of context for children to have specific values.\n \n A trick you can use if you need values to move up the hierachy\n is to set a `\"global\"` key containing a dict, where you can store values.\n \"\"\"\n if context is None:\n context = {}\n return list(self.visit_iter(tree, context=context))\n ", "context": "class TreeVisitor():\n def visit(self, tree, context=None): ...\n def __init__(self, track_parents=False): ...\n def _get_method(self, node): ...\n def visit_iter(self, node, context): ...\n def child_context(self, node, child, context, **kwargs): ...\n def generic_visit(self, node, context): ...\n\n self.track_parents = track_parents\n\n visitor_method_prefix = 'visit_'\n generic_visitor_method_name = 'generic_visit'\n _get_method_cache = None\n", "repository": "jurismarches/luqum", "test_name": "test_generic_visit", "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_000222.py"} {"focal_file": "luqum/visitor.py", "focal_class": null, "focal_method": "visit", "tests": "import unittest\n\nclass Test_visit(unittest.TestCase):\n def test_no_transform(self):\n tree = AndOperation(NONE_ITEM, NONE_ITEM)\n transformer = self.BasicTransformer()\n new_tree = transformer.visit(tree)\n self.assertEqual(new_tree, tree)\n", "method_code": " def visit(self, tree, context=None):\n \"\"\"Traversal of tree\n \n :param luqum.tree.Item tree: a tree representing a lucene expression\n :param dict context: a dict with initial values for context\n \n .. note:: the values in context, are not guaranteed to move up the hierachy,\n because we do copy of context for children to have specific values.\n \n A trick you can use if you need values to move up the hierachy\n is to set a `\"global\"` key containing a dict, where you can store values.\n \"\"\"\n if context is None:\n context = {}\n return list(self.visit_iter(tree, context=context))\n ", "context": "class TreeVisitor():\n def visit(self, tree, context=None): ...\n def __init__(self, track_parents=False): ...\n def _get_method(self, node): ...\n def visit_iter(self, node, context): ...\n def child_context(self, node, child, context, **kwargs): ...\n def generic_visit(self, node, context): ...\n\n self.track_parents = track_parents\n\n visitor_method_prefix = 'visit_'\n generic_visitor_method_name = 'generic_visit'\n _get_method_cache = None\n", "repository": "jurismarches/luqum", "test_name": "test_no_transform", "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_000223.py"} {"focal_file": "luqum/elasticsearch/nested.py", "focal_class": null, "focal_method": "extract_nested_queries", "tests": "import unittest\n\nclass Test_extract_nested_queries(unittest.TestCase):\n def test_nested_bool_inside(self):\n term1 = {'term': {'text': {'value': 'spam', '_name': 'spam'}}}\n term2 = {'term': {'text': {'value': 'ham', '_name': 'ham'}}}\n bool_query = {'bool': {'must': [term1, term2]}}\n queries = extract_nested_queries({'nested': {'path': 'my', 'query': bool_query}})\n self.assertEqual(queries, [{'nested': {'path': 'my', 'query': term1, '_name': 'spam'}}, {'nested': {'path': 'my', 'query': term2, '_name': 'ham'}}])\n\n def test_nested_inside_nested(self):\n term1 = {'term': {'text': {'value': 'bar', '_name': 'bar'}}}\n term2 = {'term': {'text': {'value': 'baz', '_name': 'baz'}}}\n term3 = {'term': {'text': {'value': 'spam', '_name': 'spam'}}}\n bool_query1 = {'bool': {'should': [term1, term2]}}\n inner_nested = {'nested': {'path': 'my.your', 'query': bool_query1}}\n bool_query2 = {'bool': {'must': [term3, inner_nested]}}\n queries = extract_nested_queries({'nested': {'path': 'my', 'query': bool_query2}})\n self.assertEqual(queries, [{'nested': {'path': 'my', 'query': term3, '_name': 'spam'}}, {'nested': {'path': 'my', 'query': inner_nested}}, {'nested': {'path': 'my', '_name': 'bar', 'query': {'nested': {'path': 'my.your', 'query': term1}}}}, {'nested': {'path': 'my', '_name': 'baz', 'query': {'nested': {'path': 'my.your', 'query': term2}}}}])\n", "method_code": "def extract_nested_queries(query, query_nester=None):\n \"\"\"given a query,\n extract all queries that are under a nested query and boolean operations,\n returning an atomic nested version of them.\n Those nested queries, also take care of changing the name to the nearest inner name,\n\n This is useful for Elasticsearch won't go down explaining why a nested query is matching.\n\n :param dict query: elasticsearch query to analyze\n :param callable query_nester: this is the function called to nest sub queries, leave it default\n :return list: queries that you should run to get all matching\n\n .. note:: because we re-nest part of bool queries, results might not be accurate\n for::\n {\"bool\": \"must\" : [\n {\"nested\": {\"path\": \"a\", \"match\": {\"x\": \"y\"}}},\n {\"nested\": {\"path\": \"a\", \"match\": {\"x\": \"z\"}}}\n ]}\n is not the same as::\n {\"nested\": {\"path\": \"a\", \"bool\": \"must\": [{\"match\": {\"x\": \"y\"}}, {\"match\": {\"x\": \"z\"}}]}}\n\n if x is multivalued.\n The first would match `{\"a\": [{\"x\": \"y\"}, {\"x\": \"z\"}]}`\n While the second would only match if `x` contains `\"y z\"` or `\"z y\"`\n \"\"\"\n queries = []\n in_nested = query_nester is not None\n sub_query_nester = query_nester\n if isinstance(query, dict):\n if 'nested' in query:\n params = {k: v for k, v in query['nested'].items() if k not in ('query', 'name')}\n\n def sub_query_nester(req, name):\n nested = {'nested': {'query': req, **params}}\n if query_nester is not None:\n nested = query_nester(nested, name)\n if name is not None:\n nested['nested']['_name'] = name\n return nested\n bool_param = {'must', 'should', 'must_not'} & set(query.keys())\n if bool_param and in_nested:\n op, = bool_param\n sub_queries = query[op] if isinstance(query[op], list) else [query[op]]\n nested_sub_queries = [query_nester(sub_query, get_first_name(sub_query)) for sub_query in sub_queries]\n queries.extend(nested_sub_queries)\n children = sub_queries\n else:\n children = query.values()\n elif isinstance(query, list):\n children = query\n else:\n children = []\n for child_query in children:\n queries.extend(extract_nested_queries(child_query, query_nester=sub_query_nester))\n return queries", "context": "def extract_nested_queries(query, query_nester=None): ...\ndef get_first_name(query): ...\ndef extract_nested_queries(query, query_nester=None): ...\n", "repository": "jurismarches/luqum", "test_name": "test_nested_bool_inside", "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_000224.py"} {"focal_file": "luqum/elasticsearch/nested.py", "focal_class": null, "focal_method": "get_first_name", "tests": "import unittest\n\nclass Test_get_first_name(unittest.TestCase):\n def test_get_first_name(self):\n term = {'term': {'text': {'value': 'bar', '_name': 'bar'}}}\n query = [{'query': term, '_name': 'spam'}, {'query': term, '_name': 'beurre'}]\n name = get_first_name(query)\n self.assertEqual(name, 'spam')\n", "method_code": "def get_first_name(query):\n if isinstance(query, dict):\n if '_name' in query:\n return query['_name']\n elif 'bool' in query:\n return None\n else:\n children = query.values()\n elif isinstance(query, list):\n children = query\n else:\n return None\n iter_candidates = (get_first_name(child) for child in children)\n candidates = [candidate for candidate in iter_candidates if candidate is not None]\n return candidates[0] if candidates else None", "context": "def get_first_name(query): ...\ndef get_first_name(query): ...\ndef extract_nested_queries(query, query_nester=None): ...\n", "repository": "jurismarches/luqum", "test_name": "test_get_first_name", "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_000225.py"} {"focal_file": "luqum/elasticsearch/schema.py", "focal_class": "SchemaAnalyzer", "focal_method": "default_field", "tests": "import unittest\n\nclass Test_SchemaAnalyzer_default_field(unittest.TestCase):\n def test_default_field(self):\n s = SchemaAnalyzer(self.INDEX_SETTINGS)\n self.assertEqual(s.default_field(), 'text')\n", "method_code": " def default_field(self):\n try:\n return self.settings['query']['default_field']\n except KeyError:\n return '*'\n ", "context": "class SchemaAnalyzer():\n def default_field(self): ...\n def __init__(self, schema): ...\n def _dot_name(self, fname, parents): ...\n def _walk_properties(self, properties, parents=None, subfields=False): ...\n def iter_fields(self, subfields=False): ...\n def not_analyzed_fields(self): ...\n def nested_fields(self): ...\n def object_fields(self): ...\n def sub_fields(self): ...\n def query_builder_options(self): ...\n\n self.settings = schema.get('settings', {})\n", "repository": "jurismarches/luqum", "test_name": "test_default_field", "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_000226.py"} {"focal_file": "luqum/elasticsearch/schema.py", "focal_class": "SchemaAnalyzer", "focal_method": "not_analyzed_fields", "tests": "import unittest\n\nclass Test_SchemaAnalyzer_not_analyzed_fields(unittest.TestCase):\n def test_not_analyzed_fields(self):\n s = SchemaAnalyzer(self.INDEX_SETTINGS)\n self.assertEqual(sorted(s.not_analyzed_fields()), ['author.book.format.ftype', 'author.book.isbn.ref', 'author.firstname.raw', 'manager.address.zipcode', 'manager.subteams.supervisor.name.raw', 'publish.idnum', 'publish.site'])\n", "method_code": " def not_analyzed_fields(self):\n for fname, fdef, parents in self.iter_fields(subfields=True):\n not_analyzed = fdef.get('type') == 'string' and fdef.get('index', '') == 'not_analyzed' or fdef.get('type') not in ('text', 'string', 'nested', 'object')\n if not_analyzed:\n yield self._dot_name(fname, parents)\n ", "context": "class SchemaAnalyzer():\n def not_analyzed_fields(self): ...\n def __init__(self, schema): ...\n def _dot_name(self, fname, parents): ...\n def default_field(self): ...\n def _walk_properties(self, properties, parents=None, subfields=False): ...\n def iter_fields(self, subfields=False): ...\n def nested_fields(self): ...\n def object_fields(self): ...\n def sub_fields(self): ...\n def query_builder_options(self): ...\n\n self.settings = schema.get('settings', {})\n", "repository": "jurismarches/luqum", "test_name": "test_not_analyzed_fields", "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_000227.py"} {"focal_file": "luqum/elasticsearch/schema.py", "focal_class": "SchemaAnalyzer", "focal_method": "nested_fields", "tests": "import unittest\n\nclass Test_SchemaAnalyzer_nested_fields(unittest.TestCase):\n def test_nested_fields(self):\n s = SchemaAnalyzer(self.INDEX_SETTINGS)\n self.assertEqual(s.nested_fields(), {'author': {'firstname': {}, 'lastname': {}, 'book': {'format': {'ftype': {}}, 'title': {}, 'isbn': {}}}, 'publish': {'site': {}, 'idnum': {}}, 'manager.subteams': {'supervisor': {}}})\n", "method_code": " def nested_fields(self):\n result = {}\n for fname, fdef, parents in self.iter_fields():\n pdef = parents[-1][1] if parents else {}\n if pdef.get('type') == 'nested':\n target = result\n cumulated = []\n for n, _ in parents:\n cumulated.append(n)\n key = '.'.join(cumulated)\n if key in target:\n target = target[key]\n cumulated = []\n if cumulated:\n key = '.'.join(cumulated)\n target = target.setdefault(key, {})\n target[fname] = {}\n return result\n ", "context": "class SchemaAnalyzer():\n def nested_fields(self): ...\n def __init__(self, schema): ...\n def _dot_name(self, fname, parents): ...\n def default_field(self): ...\n def _walk_properties(self, properties, parents=None, subfields=False): ...\n def iter_fields(self, subfields=False): ...\n def not_analyzed_fields(self): ...\n def object_fields(self): ...\n def sub_fields(self): ...\n def query_builder_options(self): ...\n\n self.settings = schema.get('settings', {})\n", "repository": "jurismarches/luqum", "test_name": "test_nested_fields", "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_000228.py"} {"focal_file": "luqum/elasticsearch/schema.py", "focal_class": "SchemaAnalyzer", "focal_method": "object_fields", "tests": "import unittest\n\nclass Test_SchemaAnalyzer_object_fields(unittest.TestCase):\n def test_object_fields(self):\n s = SchemaAnalyzer(self.INDEX_SETTINGS)\n self.assertEqual(sorted(s.object_fields()), ['author.book.isbn.ref', 'manager.address.zipcode', 'manager.firstname', 'manager.subteams.supervisor.name'])\n", "method_code": " def object_fields(self):\n for fname, fdef, parents in self.iter_fields():\n pdef = parents[-1][1] if parents else {}\n if pdef.get('type') == 'object' and fdef.get('type') not in ('object', 'nested'):\n yield self._dot_name(fname, parents)\n ", "context": "class SchemaAnalyzer():\n def object_fields(self): ...\n def __init__(self, schema): ...\n def _dot_name(self, fname, parents): ...\n def default_field(self): ...\n def _walk_properties(self, properties, parents=None, subfields=False): ...\n def iter_fields(self, subfields=False): ...\n def not_analyzed_fields(self): ...\n def nested_fields(self): ...\n def sub_fields(self): ...\n def query_builder_options(self): ...\n\n self.settings = schema.get('settings', {})\n", "repository": "jurismarches/luqum", "test_name": "test_object_fields", "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_000229.py"} {"focal_file": "luqum/elasticsearch/schema.py", "focal_class": "SchemaAnalyzer", "focal_method": "sub_fields", "tests": "import unittest\n\nclass Test_SchemaAnalyzer_sub_fields(unittest.TestCase):\n def test_sub_fields(self):\n s = SchemaAnalyzer(self.INDEX_SETTINGS)\n self.assertEqual(sorted(s.sub_fields()), ['author.firstname.english', 'author.firstname.raw', 'manager.subteams.supervisor.name.raw'])\n", "method_code": " def sub_fields(self):\n \"\"\"return all known subfields\n \"\"\"\n for fname, fdef, parents in self.iter_fields():\n subfields = fdef.get('fields')\n if subfields:\n subfield_parents = parents + [(fname, fdef)]\n for subname in subfields:\n yield self._dot_name(subname, subfield_parents)\n ", "context": "class SchemaAnalyzer():\n def sub_fields(self): ...\n def __init__(self, schema): ...\n def _dot_name(self, fname, parents): ...\n def default_field(self): ...\n def _walk_properties(self, properties, parents=None, subfields=False): ...\n def iter_fields(self, subfields=False): ...\n def not_analyzed_fields(self): ...\n def nested_fields(self): ...\n def object_fields(self): ...\n def query_builder_options(self): ...\n\n self.settings = schema.get('settings', {})\n", "repository": "jurismarches/luqum", "test_name": "test_sub_fields", "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_000230.py"} {"focal_file": "comm_utils/logs/hooks_helper_test.py", "focal_class": null, "focal_method": "validate_train_hook_name", "tests": "import unittest\n\nclass Test_validate_train_hook_name(unittest.TestCase):\n def test_get_train_hooks_profiler_hook(self):\n self.validate_train_hook_name('ProfilerHook', 'profilerhook')\n", "method_code": " def validate_train_hook_name(self, test_hook_name, expected_hook_name, **kwargs):\n returned_hook = hooks_helper.get_train_hooks([test_hook_name], model_dir='', **kwargs)\n self.assertEqual(len(returned_hook), 1)\n self.assertIsInstance(returned_hook[0], tf.train.SessionRunHook)\n self.assertEqual(returned_hook[0].__class__.__name__.lower(), expected_hook_name)\n ", "context": "class BaseTest(unittest.TestCase):\n def validate_train_hook_name(self, test_hook_name, expected_hook_name, **kwargs): ...\n def test_raise_in_non_list_names(self): ...\n def test_raise_in_invalid_names(self): ...\n def test_get_train_hooks_logging_tensor_hook(self): ...\n def test_get_train_hooks_profiler_hook(self): ...\n def test_get_train_hooks_examples_per_second_hook(self): ...\n def test_get_logging_metric_hook(self): ...\n", "repository": "hkhpub/nmt-transformer", "test_name": "test_get_train_hooks_profiler_hook", "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_000231.py"} {"focal_file": "web_api/bearings/apis/test.py", "focal_class": null, "focal_method": "test_get_inventory_qty", "tests": "import unittest\n\nclass Test_test_get_inventory_qty(unittest.TestCase):\n def test_with_for_update(self):\n \"\"\"\n 测试排他锁\n :return:\n \"\"\"\n urls = [self.url_with_lock] * 2\n rs = [grequests.post(u, auth=self.base_auth) for u in urls]\n grequests.map(rs)\n status_code_set = set([rs_item.response.status_code for rs_item in rs])\n self.assertEqual(status_code_set, {202, 400})\n qty = test_get_inventory_qty(self.inventory_id)\n self.assertEqual(qty, 0)\n", "method_code": "def test_get_inventory_qty(inventory_id):\n return db.session.query(Inventory).get(inventory_id).stock_qty", "context": "def test_get_inventory_qty(inventory_id): ...\ndef test_get_inventory_qty(inventory_id): ...\ndef test_update_inventory_qty(inventory_id, qty=1): ...\ndef test_decrease_inventory(inventory_id, num=1, lock=False): ...\n", "repository": "zhanghe06/flask_restful", "test_name": "test_with_for_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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000232.py"} {"focal_file": "tools/date_time.py", "focal_class": null, "focal_method": "time_local_to_utc", "tests": "import unittest\n\nclass Test_time_local_to_utc(unittest.TestCase):\n def test_local_to_utc(self):\n \"\"\"\n 测试\n :return:\n \"\"\"\n local_time_obj = datetime.datetime.strptime(self.local_time, '%Y-%m-%d %H:%M:%S')\n utc_time_obj = time_local_to_utc(self.local_time)\n self.assertEqual(utc_time_obj, local_time_obj + datetime.timedelta(seconds=self.time_offset))\n self.assertEqual(self.utc_time, utc_time_obj.strftime('%Y-%m-%d %H:%M:%S'))\n", "method_code": "def time_local_to_utc(local_time):\n \"\"\"\n 本地时间转UTC时间\n :param local_time:\n :return:\n \"\"\"\n if isinstance(local_time, six.string_types) and len(local_time) == 10:\n local_time = datetime.strptime(local_time, '%Y-%m-%d')\n elif isinstance(local_time, six.string_types) and len(local_time) >= 19:\n local_time = datetime.strptime(local_time[:19], '%Y-%m-%d %H:%M:%S')\n elif not (isinstance(local_time, datetime) or isinstance(local_time, date)):\n local_time = datetime.now()\n utc_time = local_time + timedelta(seconds=time.timezone)\n return utc_time", "context": "def time_local_to_utc(local_time): ...\ndef get_tc(): ...\ndef get_current_day_time_ends(): ...\ndef get_current_month_time_ends(): ...\ndef get_current_year_time_ends(): ...\ndef get_hours(zerofill=True): ...\ndef get_days(year=1970, month=1, zerofill=True): ...\ndef get_weeks(): ...\ndef get_months(zerofill=True): ...\ndef time_local_to_utc(local_time): ...\ndef time_utc_to_local(utc_time): ...\n", "repository": "zhanghe06/news_spider", "test_name": "test_local_to_utc", "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_000233.py"} {"focal_file": "tools/date_time.py", "focal_class": null, "focal_method": "time_utc_to_local", "tests": "import unittest\n\nclass Test_time_utc_to_local(unittest.TestCase):\n def test_utc_to_local(self):\n \"\"\"\n 测试\n :return:\n \"\"\"\n utc_time_obj = datetime.datetime.strptime(self.utc_time, '%Y-%m-%d %H:%M:%S')\n local_time_obj = time_utc_to_local(self.utc_time)\n self.assertEqual(utc_time_obj, local_time_obj + datetime.timedelta(seconds=self.time_offset))\n self.assertEqual(self.local_time, local_time_obj.strftime('%Y-%m-%d %H:%M:%S'))\n", "method_code": "def time_utc_to_local(utc_time):\n \"\"\"\n UTC时间转本地时间\n :param utc_time:\n :return:\n \"\"\"\n if isinstance(utc_time, six.string_types) and len(utc_time) == 10:\n utc_time = datetime.strptime(utc_time, '%Y-%m-%d')\n elif isinstance(utc_time, six.string_types) and len(utc_time) >= 19:\n utc_time = datetime.strptime(utc_time[:19], '%Y-%m-%d %H:%M:%S')\n elif not (isinstance(utc_time, datetime) or isinstance(utc_time, date)):\n utc_time = datetime.utcnow()\n local_time = utc_time - timedelta(seconds=time.timezone)\n return local_time", "context": "def time_utc_to_local(utc_time): ...\ndef get_tc(): ...\ndef get_current_day_time_ends(): ...\ndef get_current_month_time_ends(): ...\ndef get_current_year_time_ends(): ...\ndef get_hours(zerofill=True): ...\ndef get_days(year=1970, month=1, zerofill=True): ...\ndef get_weeks(): ...\ndef get_months(zerofill=True): ...\ndef time_local_to_utc(local_time): ...\ndef time_utc_to_local(utc_time): ...\n", "repository": "zhanghe06/news_spider", "test_name": "test_utc_to_local", "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": "parse.py", "focal_class": null, "focal_method": "cutoff_msg20", "tests": "import unittest\n\nclass Test_cutoff_msg20(unittest.TestCase):\n def test_cutoff_msg20_with_japanese_msg(self):\n msg = 'あの花'\n eq_(cutoff_msg20(msg), msg)\n\n def test_cutoff_msg20_with_english_msg(self):\n msg = 'anohana'\n eq_(cutoff_msg20(msg), msg)\n\n def test_cutoff_msg20_with_long_msg(self):\n msg = 'あの花の名前を僕はまだ知らないを見たんだけど、君どう思う?'\n eq_(cutoff_msg20(msg), '20文字以内の単語でしらべてほしいにゃー')\n\n def test_cutoff_msg20_with_blank_msg(self):\n msg = ''\n eq_(cutoff_msg20(msg), '')\n\n def test_cutoff_msg20_with_none(self):\n msg = None\n eq_(cutoff_msg20(msg), '')\n", "method_code": "def cutoff_msg20(input):\n try:\n msg_length = len(input)\n except TypeError:\n return ''\n if msg_length > 20:\n return '20文字以内の単語でしらべてほしいにゃー'\n return input", "context": "def cutoff_msg20(input): ...\ndef cutoff_msg20(input): ...\n", "repository": "miokato/BookConcierge", "test_name": "test_cutoff_msg20_with_japanese_msg", "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_000235.py"} {"focal_file": "search.py", "focal_class": null, "focal_method": "fetch_books", "tests": "import unittest\n\nclass Test_fetch_books(unittest.TestCase):\n def test_fetch_books_size(self):\n books = fetch_books('ねこ', number_of_books=2)\n eq_(len(books), 3)\n\n def test_fetch_books_type(self):\n books = fetch_books('ねこ', number_of_books=2)\n eq_(type(books), tuple)\n\n def test_fetch_books_none_type(self):\n books = fetch_books('', number_of_books=2)\n eq_(type(books), type(None))\n", "method_code": "def fetch_books(keyword, number_of_books=1):\n \"\"\"\n Honya Clubから本のタイトル、詳細リンク、画像リンクを取得する\n :param keyword: str (book title what you want search) \n :param number_of_books: int ( 1 <= books <= 5 )\n :return: 3 list's tuple (title, image_link, detail_link) \n \"\"\"\n search_url = 'http://www.honyaclub.com/shop/goods/search.aspx?'\n main_url = 'https://www.honyaclub.com'\n encode_word = keyword.encode('Shift-JIS')\n payload = {'search': 'x', 'keyw': encode_word}\n if number_of_books <= 0 or number_of_books > 5:\n return None\n r = requests.get(search_url, params=payload)\n soup = bs(r.content, 'html.parser')\n try:\n books_data = soup.find('div', class_='result-item')\n books_detail = books_data.find_all('div', class_='item-img', limit=number_of_books)\n books_title = [book.img.get('alt') for book in books_detail]\n books_image_elements = [book.img.get('src') for book in books_detail]\n books_image_url = [urljoin(main_url, path) for path in books_image_elements]\n books_detail_elements = [book.a.get('href') for book in books_detail]\n books_detail_url = [urljoin(main_url, path) for path in books_detail_elements]\n books_info = books_data.find_all('dl', class_='item-txt')\n books_author = [book.find('dd').find('a') for book in books_info]\n except AttributeError:\n return None\n return (books_title, books_image_url, books_detail_url)", "context": "def fetch_books(keyword, number_of_books=1): ...\ndef fetch_books(keyword, number_of_books=1): ...\n", "repository": "miokato/BookConcierge", "test_name": "test_fetch_books_size", "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_000236.py"} {"focal_file": "source/emis_dataset_manager/manage_dataset/scan.py", "focal_class": "Property", "focal_method": "rewrite_pathnames", "tests": "import unittest\n\nclass Test_Property_rewrite_pathnames(unittest.TestCase):\n def test_rewrite_1(self):\n properties1 = [Property('/data/property/NOx.lue', '/blah/nox'), Property('/data/property/NO2.lue', '/blah/no2')]\n rewrite_path = None\n properties2 = rewrite_pathnames(copy.deepcopy(properties1), rewrite_path)\n self.assertEqual(len(properties2), len(properties1))\n self.assertEqual(properties2[0], properties1[0])\n self.assertEqual(properties2[1], properties1[1])\n\n def test_rewrite_2(self):\n properties1 = [Property('/data/property/NOx.lue', '/blah/nox'), Property('/data/property/NO2.lue', '/blah/no2')]\n rewrite_path = []\n properties2 = rewrite_pathnames(copy.deepcopy(properties1), rewrite_path)\n self.assertEqual(len(properties2), len(properties1))\n self.assertEqual(properties2[0], properties1[0])\n self.assertEqual(properties2[1], properties1[1])\n\n def test_rewrite_3(self):\n properties1 = [Property('/data/property/NOx.lue', '/blah/nox'), Property('/data/property/NO2.lue', '/blah/no2')]\n rewrite_path = ['/data/property', '/data/property']\n properties2 = rewrite_pathnames(copy.deepcopy(properties1), rewrite_path)\n self.assertEqual(len(properties2), len(properties1))\n self.assertEqual(properties2[0], properties1[0])\n self.assertEqual(properties2[1], properties1[1])\n\n def test_rewrite_4(self):\n properties1 = [Property('/data/property/NOx.lue', '/blah/nox'), Property('/data/property/NO2.lue', '/blah/no2')]\n rewrite_path = ['/data/property', '/some_other_path']\n properties2 = rewrite_pathnames(copy.deepcopy(properties1), rewrite_path)\n self.assertEqual(len(properties2), len(properties1))\n self.assertEqual(properties2[0].dataset_pathname, rewrite_path[1] + '/NOx.lue')\n self.assertEqual(properties2[1].dataset_pathname, rewrite_path[1] + '/NO2.lue')\n", "method_code": "def rewrite_pathnames(properties, rewrite_path):\n \"\"\"\n Rewrite pathnames *in-place*\n \"\"\"\n if rewrite_path is not None and rewrite_path:\n assert len(rewrite_path) == 2, rewrite_path\n for property in properties:\n if property.dataset_pathname.startswith(rewrite_path[0]):\n property.dataset_pathname = property.dataset_pathname.replace(rewrite_path[0], rewrite_path[1])\n return properties", "context": "def rewrite_pathnames(properties, rewrite_path): ...\ndef scan_for_regular_files(directory_pathname): ...\ndef scan_phenomena_for_properties(phenomena): ...\ndef scan_universes_for_properties(universes): ...\ndef scan_for_properties(pathname): ...\ndef property_equals(available_property, property): ...\ndef property_already_available(available_properties, property): ...\ndef add_property(uri, property): ...\ndef rewrite_pathnames(properties, rewrite_path): ...\ndef scan(uri, pathnames, rewrite_path=None): ...\n", "repository": "pcraster/emis_dataset_manager", "test_name": "test_rewrite_1", "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_000237.py"} {"focal_file": "pydme/utils.py", "focal_class": null, "focal_method": "readOnlyTree", "tests": "import unittest\n\nclass Test_readOnlyTree(unittest.TestCase):\n def testReadOnlyTree():\n n = Node('')\n tree = n.mit\n tree.ReadOnlyTree.should.be.false\n with readOnlyTree(tree) as r:\n tree.ReadOnlyTree.should.be.true\n r.ReadOnlyTree.should.be.true\n tree.ReadOnlyTree.should.be.false\n", "method_code": "def readOnlyTree(mo):\n \"\"\"Make the given MO tree read-only.\n\n The MO tree (starting from topRoot) remains read-only until the\n enclosing with statement returns.\n\n \"\"\"\n readOnlyTreeOldValue = mo.ReadOnlyTree\n mo.ReadOnlyTree = True\n try:\n yield mo\n finally:\n mo.ReadOnlyTree = readOnlyTreeOldValue", "context": "@contextmanager\ndef readOnlyTree(mo): ...\ndef getParentDn(dn): ...\ndef splitIntoRns(dn): ...\ndef readOnlyTree(mo): ...\ndef digestConfigExport(path, topRoot, format='xml'): ...\ndef distributeConfig(root, result=None): ...\ndef mergeRoot(accumulator, root): ...\n", "repository": "CiscoDevNet/pydme", "test_name": "testReadOnlyTree", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 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_000238.py"} {"focal_file": "pydme/utils.py", "focal_class": null, "focal_method": "distributeConfig", "tests": "import unittest\n\nclass Test_distributeConfig(unittest.TestCase):\n def testDistributeConfig():\n n = Node('')\n mit = n.mit\n mit.polUni().fvTenant('cisco')\n mit.polUni().fvTenant('insieme')\n mits = distributeConfig(mit)\n mits.should.have.length_of(2)\n mits[0].ReadOnlyTree = True\n mits[0].polUni().fvTenant('cisco').name.should.equal('cisco')\n mits[1].ReadOnlyTree = True\n mits[1].polUni().fvTenant('insieme').name.should.equal('insieme')\n", "method_code": "def distributeConfig(root, result=None):\n \"\"\"Distribute configuration from the given root MO into multiple\n roots.\n\n In order for an MO tree to be posted to APIC in a single\n operation, all MOs in that tree should belong to the same\n shard. APIC will reject if any of the MOs is not in the same\n shard. This function splits the given tree to multiple subtrees,\n ensuring that all the MOs in the subtre belong to the same context\n root. One can later post the individual subtrees without worrying\n about the context root implications.\n\n :param root: MO at the top of the tree to be processed.\n :param result: optional list of subtrees to append the result to.\n\n \"\"\"\n if result is None:\n result = []\n for child in root.Children:\n if child._dmeClassMeta['isContextRoot']:\n topRoot = root.TopRoot\n newRoot = topRoot._parentApi.mit\n newChild = newRoot.FromDn(child.Dn)\n newChild.Xml = child.Xml\n result.append(newRoot)\n else:\n distributeConfig(child, result)\n return result", "context": "def distributeConfig(root, result=None): ...\ndef getParentDn(dn): ...\ndef splitIntoRns(dn): ...\ndef readOnlyTree(mo): ...\ndef digestConfigExport(path, topRoot, format='xml'): ...\ndef distributeConfig(root, result=None): ...\ndef mergeRoot(accumulator, root): ...\n", "repository": "CiscoDevNet/pydme", "test_name": "testDistributeConfig", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 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_000239.py"} {"focal_file": "pydme/utils.py", "focal_class": null, "focal_method": "mergeRoot", "tests": "import unittest\n\nclass Test_mergeRoot(unittest.TestCase):\n def testMergeRoot():\n n = Node('')\n t1 = n.mit\n t1.polUni().fvTenant('cisco')\n t2 = n.mit\n t2.polUni().fvTenant('insieme')\n mit = n.mit\n mergeRoot(mit, t1)\n mergeRoot(mit, t2)\n mit.ReadOnlyTree = True\n mit.polUni().fvTenant('cisco').name.should.equal('cisco')\n mit.polUni().fvTenant('insieme').name.should.equal('insieme')\n", "method_code": "def mergeRoot(accumulator, root):\n \"\"\"Merge the given root MO into the given acculumulator.\"\"\"\n accumulator.Xml = root.Xml\n return accumulator", "context": "def mergeRoot(accumulator, root): ...\ndef getParentDn(dn): ...\ndef splitIntoRns(dn): ...\ndef readOnlyTree(mo): ...\ndef digestConfigExport(path, topRoot, format='xml'): ...\ndef distributeConfig(root, result=None): ...\ndef mergeRoot(accumulator, root): ...\n", "repository": "CiscoDevNet/pydme", "test_name": "testMergeRoot", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 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_000240.py"} {"focal_file": "pydme/utils.py", "focal_class": null, "focal_method": "getParentDn", "tests": "import unittest\n\nclass Test_getParentDn(unittest.TestCase):\n @staticmethod\n def testNestedDn():\n getParentDn('uni/epp/fv-[uni/tn-infra/ap-access/epg-default]').should.equal('uni/epp')\n", "method_code": "def getParentDn(dn):\n \"\"\"Get the parent DN of the given DN string.\"\"\"\n if dn == '':\n return dn\n position = len(dn)\n nestingLevel = 0\n for ch in reversed(dn):\n position -= 1\n if ch == '/' and nestingLevel == 0:\n break\n elif ch == ']':\n nestingLevel += 1\n elif ch == '[':\n nestingLevel -= 1\n return dn[:position]", "context": "def getParentDn(dn): ...\ndef getParentDn(dn): ...\ndef splitIntoRns(dn): ...\ndef readOnlyTree(mo): ...\ndef digestConfigExport(path, topRoot, format='xml'): ...\ndef distributeConfig(root, result=None): ...\ndef mergeRoot(accumulator, root): ...\n", "repository": "CiscoDevNet/pydme", "test_name": "", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 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_000241.py"} {"focal_file": "py/colorsegmentation/image/ColorSpaceService.py", "focal_class": null, "focal_method": "convertRGBtoHSV", "tests": "import unittest\n\nclass Test_convertRGBtoHSV(unittest.TestCase):\n def testConvertRGBtoHSV(self):\n g = np.array([[[0], [0], [0], [120], [240], [60], [180], [300], [0], [0], [0], [60], [120], [300], [180], [240]], [[0], [0], [65535], [65535], [65535], [65535], [65535], [65535], [0], [0], [65535], [65535], [65535], [65535], [65535], [65535]], [[0], [65535], [65535], [65535], [65535], [65535], [65535], [65535], [49344], [32896], [32896], [32896], [32896], [32896], [32896], [32896]]], dtype=np.uint16)\n self.assertEquals(np.sum(convertRGBtoHSV(self.f) == g), 3 * 16)\n", "method_code": "def convertRGBtoHSV(f):\n g = np.empty(f.shape, dtype=np.float)\n R = f[0].astype(np.float) / 255\n G = f[1].astype(np.float) / 255\n B = f[2].astype(np.float) / 255\n M = np.max(f.astype(np.float) / 255, axis=0)\n m = np.min(f.astype(np.float) / 255, axis=0)\n C = M - m\n g[0][C == 0] = 0\n mask = (M == R) == (C != 0)\n g[0][mask] = (G[mask] - B[mask]) / C[mask] % 6\n mask = (M == G) == (C != 0)\n g[0][mask] = (B[mask] - R[mask]) / C[mask] + 2\n mask = (M == B) == (C != 0)\n g[0][mask] = (R[mask] - G[mask]) / C[mask] + 4\n g[0] = 60 * g[0]\n mask = g[0] < 0\n g[0][mask] = g[0][mask] + 360\n mask = M != 0\n g[1][mask] = C[mask] / M[mask]\n g[1][M == 0] = 0\n g[2] = M\n g[0] = g[0]\n g[1] = g[1] * 65535\n g[2] = g[2] * 65535\n return np.clip(np.round(g), 0, 65535).astype(np.uint16)", "context": "def convertRGBtoHSV(f): ...\ndef convertrgbtoxyz(f): ...\ndef convertxyztorgb(f): ...\ndef convertrgbtolab(f): ...\ndef convertlabtorgb(f): ...\ndef convertrgbtoluv(f): ...\ndef convertluvtorgb(f): ...\ndef convertRGBtoHSV(f): ...\n", "repository": "filaboia/colorattributefiltering", "test_name": "testConvertRGBtoHSV", "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_000242.py"} {"focal_file": "py/colorsegmentation/image/CompressionService.py", "focal_class": null, "focal_method": "descondensa", "tests": "import unittest\n\nclass Test_descondensa(unittest.TestCase):\n def testuncondensedivisible(self):\n a = descondensa(self.c1, 2, 4)\n self.assertEquals(np.sum(a == self.a1), 4)\n\n def testuncondenserightzeros(self):\n a = descondensa(self.c3, 2, 4)\n self.assertEquals(np.sum(a == self.a3), 4)\n", "method_code": "def descondensa(f, bits, size):\n total = size * bits\n return np.packbits(np.pad(np.unpackbits(f[:, np.newaxis], axis=1).ravel()[:total].reshape(size, bits), ((0, 0), (8 - bits, 0)), 'constant'), axis=1).ravel()", "context": "def descondensa(f, bits, size): ...\ndef complementomodulo(dividendo, divisor): ...\ndef condensa(f, bits): ...\ndef descondensa(f, bits, size): ...\n", "repository": "filaboia/colorattributefiltering", "test_name": "testuncondensedivisible", "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_000243.py"} {"focal_file": "py/colorsegmentation/maxtree/MaxTree.py", "focal_class": null, "focal_method": "computeRegAtt", "tests": "import unittest\n\nclass Test_computeRegAtt(unittest.TestCase):\n def testTreeRegAtt(self):\n ft = self.ft.computeRegAtt(Entropy, codifica(self.f))\n mins = (ft.getRegMax(False) * 255 / 24).astype(np.uint8)\n gabMins = adread('../images/test/circulo2gradentropiaregMamba.png')\n self.assertEquals(np.sum(mins == gabMins), 12)\n", "method_code": " def computeRegAtt(self, ImageFunction, orig):\n ft = self.simplify()\n igrad = ft.getImage()\n grad = ianeg(igrad)\n ws = iacwatershed(grad, ft.getRegMax(), iasecross(), 'REGIONS')\n preorder = [ft]\n postorder = []\n regdict = {}\n while preorder:\n node = preorder.pop()\n preorder += node.children\n postorder.append(node)\n while postorder:\n node = postorder.pop()\n if node.children:\n mask = Points(np.uint16)\n for child in node.children:\n mask.merge(regdict[child.getKey()])\n del regdict[child.getKey()]\n else:\n mask = Points(np.uint16, ws[node.mask()][0] == ws)\n regdict[node.getKey()] = mask\n node.att = ImageFunction(np.vstack((orig[..., mask.getX(), mask.getY()], mask.getX(), mask.getY())))\n return ft\n ", "context": "class MaxTree(object):\n def computeRegAtt(self, ImageFunction, orig): ...\n def __init__(self, f=None): ...\n def getKey(self): ...\n def simplify(self): ...\n def getOffset(self): ...\n def getImage(self): ...\n def getNodes(self, level, index=None): ...\n def getRegMax(self, binary=True): ...\n def computeAtt(self, ImageFunction, orig=None): ...\n def getPoints(self, function): ...\n def open(self, value, inclusive=True): ...\n def upperOpen(self, value): ...\n def openReg(self, n_reg): ...\n def getRegions(self, n_reg): ...\n def equalizeChildAtt(self): ...\n def status(self): ...\n\n self.children = []\n self.level = None\n self.index = None\n self.att = None\n self.mask = Points(np.uint16, f >= 0)\n", "repository": "filaboia/colorattributefiltering", "test_name": "testTreeRegAtt", "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_000244.py"} {"focal_file": "py/colorsegmentation/image/StatisticsService.py", "focal_class": null, "focal_method": "weightedHueHistogram", "tests": "import unittest\n\nclass Test_weightedHueHistogram(unittest.TestCase):\n def testWeightedHueHistogram(self):\n g = np.arange(360, dtype=np.float)\n g = g / np.sum(g)\n self.assertAlmostEquals(np.sum(np.round(weightedHueHistogram(self.f), 1) == np.round(g, 1)), 360)\n", "method_code": "def weightedHueHistogram(f):\n f = f.astype(np.float)\n H = f[0].astype(np.float)\n SV = f[1].astype(np.float) * f[2].astype(np.float)\n if np.sum(SV) == 0:\n return np.zeros(360, np.uint8)\n return np.sum(np.sum((np.tile(H, (360, 1, 1)) == np.arange(360)[:, np.newaxis, np.newaxis]) * SV[np.newaxis], axis=2), axis=1) / np.sum(SV)", "context": "def weightedHueHistogram(f): ...\ndef weightedHueHistogram(f): ...\ndef kullbackLieblerDivergence(h1, h2): ...\ndef isInAngularInterval(i, a, w): ...\ndef angularDifference(a, b): ...\ndef rotate(template, a): ...\ndef iType(a): ...\ndef VType(a): ...\ndef LType(a): ...\ndef JType(a): ...\ndef IType(a): ...\ndef TType(a): ...\ndef YType(a): ...\ndef XType(a): ...\ndef templatesDistribution(templateFunctions): ...\ndef templateRecognition(h, distribution): ...\n", "repository": "filaboia/colorattributefiltering", "test_name": "testWeightedHueHistogram", "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_000245.py"} {"focal_file": "py/colorsegmentation/image/StatisticsService.py", "focal_class": null, "focal_method": "templateRecognition", "tests": "import unittest\n\nclass Test_templateRecognition(unittest.TestCase):\n def testTemplateRecognition(self):\n templateFunctions = [iType, VType, LType, JType, IType, TType, YType, XType]\n distribution = templatesDistribution(templateFunctions)\n index = templateRecognition(templatesDistribution([XType])[47], distribution)\n self.assertEquals(index[0], 7)\n self.assertEquals(index[1], 47)\n", "method_code": "def templateRecognition(h, distribution):\n\n def decodeTemplate(index):\n return (index // 360, index % 360)\n return decodeTemplate(np.argmin(kullbackLieblerDivergence(h[np.newaxis], distribution)))", "context": "def templateRecognition(h, distribution): ...\ndef weightedHueHistogram(f): ...\ndef kullbackLieblerDivergence(h1, h2): ...\ndef isInAngularInterval(i, a, w): ...\ndef angularDifference(a, b): ...\ndef rotate(template, a): ...\ndef iType(a): ...\ndef VType(a): ...\ndef LType(a): ...\ndef JType(a): ...\ndef IType(a): ...\ndef TType(a): ...\ndef YType(a): ...\ndef XType(a): ...\ndef templatesDistribution(templateFunctions): ...\ndef templateRecognition(h, distribution): ...\n", "repository": "filaboia/colorattributefiltering", "test_name": "testTemplateRecognition", "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_000246.py"} {"focal_file": "tests/expected_steering_calculator_test.py", "focal_class": null, "focal_method": "__getAbsoluteDistanceDifferenceAsProportionOfMaxSteeringErrorDistance", "tests": "import unittest\n\nclass Test_getAbsoluteDistanceDifferenceAsProportionOfMaxSteeringErrorDistance(unittest.TestCase):\n def test_shouldReturnNegativeDifferenceBetweenRightAndLeftDistancesAsProportionOfMaxSteeringErrorWhenLeftIsBiggerThanRight(self):\n distance_left = 85\n distance_right = 45\n actual_expected_steering = self.expected_steering_calculator.calculate_expected_steering(distance_left, distance_right)\n expected_expected_steering = -self.__getAbsoluteDistanceDifferenceAsProportionOfMaxSteeringErrorDistance(distance_right, distance_left)\n self.assertEqual(expected_expected_steering, actual_expected_steering)\n\n def test_shouldReturnPositiveDifferenceBetweenRightAndLeftDistancesAsProportionOfMaxSteeringErrorWhenRightIsBiggerThanLeft(self):\n distance_left = 50\n distance_right = 75\n actual_expected_steering = self.expected_steering_calculator.calculate_expected_steering(distance_left, distance_right)\n expected_expected_steering = self.__getAbsoluteDistanceDifferenceAsProportionOfMaxSteeringErrorDistance(distance_right, distance_left)\n self.assertEqual(expected_expected_steering, actual_expected_steering)\n", "method_code": " def __getAbsoluteDistanceDifferenceAsProportionOfMaxSteeringErrorDistance(self, first_distance, second_distance):\n return int(abs(first_distance - second_distance) * 100 / self.max_steering_error_distance)\n ", "context": "class ExpectedSteeringCalculatorUnitTest(unittest.TestCase):\n def __getAbsoluteDistanceDifferenceAsProportionOfMaxSteeringErrorDistance(self, first_distance, second_distance): ...\n def setUp(self): ...\n def test_shouldReturnZeroWhenBothDistancesAreEqual(self): ...\n def test_shouldReturnNegativeProportionalDifferenceBetweenActualLeftDistanceAndNormalSideDistanceWhenRightDistanceIsAboveMaxAndLeftDistanceIsAboveNormal(self): ...\n def test_shouldReturnPositiveProportionalDifferenceBetweenActualLeftDistanceAndNormalSideDistanceWhenRightDistanceIsAboveMaxAndLeftDistanceIsBelowNormal(self): ...\n def test_shouldReturnNegativeProportionalDifferenceBetweenActualRightDistanceAndNormalSideDistanceWhenLeftDistanceIsAboveMaxAndRightDistanceIsBelowNormal(self): ...\n def test_shouldReturnPositiveProportionalDifferenceBetweenActualRightDistanceAndNormalSideDistanceWhenLeftDistanceIsAboveMaxAndRightDistanceIsAboveNormal(self): ...\n def test_shouldReturnZeroWhenBothDistancesAreAboveMax(self): ...\n def test_shouldReturnNegativeMaxSteeringErrorWhenRightDistanceIsBelowMinimumSideDistanceAndLeftDistanceIsAboveMinimum(self): ...\n def test_shouldReturnPositiveMaxSteeringErrorWhenLeftDistanceIsBelowMinimumSideDistanceAndRightDistanceIsAboveMinimum(self): ...\n def test_shouldReturnNegativeDifferenceBetweenRightAndLeftDistancesAsProportionOfMaxSteeringErrorWhenLeftIsBiggerThanRight(self): ...\n def test_shouldReturnPositiveDifferenceBetweenRightAndLeftDistancesAsProportionOfMaxSteeringErrorWhenRightIsBiggerThanLeft(self): ...\n", "repository": "k6ps/ev3-folkrace-p6rrap6rra", "test_name": "test_shouldReturnNegativeDifferenceBetweenRightAndLeftDistancesAsProportionOfMaxSteeringErrorWhenLeftIsBiggerThanRight", "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_000247.py"} {"focal_file": "bs4/tests/test_builder_registry.py", "focal_class": null, "focal_method": "builder_for_features", "tests": "import unittest\n\nclass Test_builder_for_features(unittest.TestCase):\n def test_register_with_no_features(self):\n builder = self.builder_for_features()\n self.assertEqual(self.registry.lookup('foo'), None)\n self.assertEqual(self.registry.lookup(), builder)\n", "method_code": " def builder_for_features(self, *feature_list):\n cls = type('Builder_' + '_'.join(feature_list), (object,), {'features': feature_list})\n self.registry.register(cls)\n return cls\n ", "context": "class RegistryTest(unittest.TestCase):\n def builder_for_features(self, *feature_list): ...\n def setUp(self): ...\n def test_register_with_no_features(self): ...\n def test_register_with_features_makes_lookup_succeed(self): ...\n def test_lookup_fails_when_no_builder_implements_feature(self): ...\n def test_lookup_gets_most_recent_registration_when_no_feature_specified(self): ...\n def test_lookup_fails_when_no_tree_builders_registered(self): ...\n def test_lookup_gets_most_recent_builder_supporting_all_features(self): ...\n def test_lookup_fails_when_cannot_reconcile_requested_features(self): ...\n", "repository": "jroweboy/LoL-Tournament", "test_name": "test_register_with_no_features", "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_000248.py"} {"focal_file": "katas/game_of_life/python/game.py", "focal_class": null, "focal_method": "neighbourhood_locations", "tests": "import unittest\n\nclass Test_neighbourhood_locations(unittest.TestCase):\n def test_cell_neighbourhood(self):\n expected_neighbourhood = set([(6, 7), (5, 5), (5, 6), (7, 6), (5, 7), (7, 7), (7, 5), (6, 5)])\n self.assertEqual(expected_neighbourhood, self.fst_cell.neighbourhood_locations())\n", "method_code": " def neighbourhood_locations(self):\n x_coordinates = [self.x - 1, self.x, self.x + 1]\n y_coordinates = [self.y - 1, self.y, self.y + 1]\n positions = set(list(product(x_coordinates, y_coordinates)))\n positions.remove((self.x, self.y))\n return positions\n ", "context": "class Cell(namedtuple('Cell', 'x y alive')):\n def neighbourhood_locations(self): ...\n def __new__(cls, x, y, alive=True): ...\n def is_alive_with(self, num_neighbours): ...\n\n __slots__ = ()\n", "repository": "gvallarelli/CodingDojo", "test_name": "test_cell_neighbourhood", "smells": [1, 0, 0, 0, 1, 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_000249.py"} {"focal_file": "katas/game_of_life/python/game.py", "focal_class": null, "focal_method": "tick", "tests": "import unittest\n\nclass Test_tick(unittest.TestCase):\n def test_a_cell_without_neighbours_dies_after_tick(self):\n dying_cell = Cell(4, 4)\n my_board = Board([self.fst_cell, self.snd_cell, self.trd_cell, dying_cell])\n my_board.tick()\n self.assertFalse(my_board.cell_alive_at(4, 4))\n self.assertTrue(my_board.cell_alive_at(6, 6))\n self.assertTrue(my_board.cell_alive_at(5, 6))\n self.assertTrue(my_board.cell_alive_at(5, 7))\n\n def test_a_cell_with_2or3_neighbours_stays_alive_after_tick(self):\n my_board = Board([self.fst_cell, self.snd_cell, self.trd_cell, self.fourth_cell])\n my_board.tick()\n self.assertTrue(my_board.cell_alive_at(6, 6))\n self.assertTrue(my_board.cell_alive_at(5, 6))\n self.assertTrue(my_board.cell_alive_at(5, 7))\n self.assertTrue(my_board.cell_alive_at(6, 7))\n", "method_code": " def tick(self):\n cells = {}\n for cell in self.cells.values():\n alive_neighbours = self.alive_neighbours(cell)\n if cell.is_alive_with(alive_neighbours):\n cells[cell.x, cell.y] = Cell(cell.x, cell.y)\n self.cells = cells\n self.add_surrounding_dead_cells()\n self.renderer.update_board()\n ", "context": "class Board(object):\n def tick(self): ...\n def __init__(self, cells, renderer=gui.NullRenderer()): ...\n def add_surrounding_dead_cells(self): ...\n def cell_alive_at(self, x, y): ...\n def all_cells(self): ...\n def alive_neighbours(self, cell): ...\n\n self.cells = {(cell.x, cell.y): cell for cell in cells}\n self.renderer = renderer\n\n X, Y = (0, 1)\n", "repository": "gvallarelli/CodingDojo", "test_name": "test_a_cell_without_neighbours_dies_after_tick", "smells": [1, 0, 0, 0, 1, 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_000250.py"} {"focal_file": "eqcatalogue/models.py", "focal_class": null, "focal_method": "get_agencies", "tests": "import unittest\n\nclass Test_get_agencies(unittest.TestCase):\n def test_available_measures_agencies(self):\n self.create_test_fixture()\n self.assertEqual(set(['Tatooine', 'Alderaan', 'DeathStar']), self.catalogue.get_agencies())\n", "method_code": " def get_agencies(self):\n \"\"\"\n Returns a set containing the measure agencies.\n \"\"\"\n available_agencies = [agency.name for agency in self.session.query(Agency).all()]\n return set(available_agencies)\n ", "context": "class CatalogueDatabase(object):\n def get_agencies(self): ...\n def __init__(self, drop=False, engine=DEFAULT_ENGINE, **engine_params): ...\n def recreate(self): ...\n def close(self): ...\n def get_engine(cls, module_name): ...\n def session(self): ...\n def load_file(self, filename, importer_module_name, **kwargs): ...\n def position_from_latlng(self, latitude, longitude): ...\n def get_or_create(self, class_object, query_args, creation_args=None): ...\n def get_measure_scales(self): ...\n def get_summary(self): ...\n\n self._engine_class = self.__class__.get_engine(engine)\n self._engine = self._engine_class(**engine_params)\n\n __metaclass__ = Workspace\n MEASURE_AGENCIES = 'available_measure_agencies'\n MEASURE_SCALES = 'available_measure_scales'\n", "repository": "gvallarelli/oq-eqcatalogue-tool", "test_name": "test_available_measures_agencies", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 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_000251.py"} {"focal_file": "eqcatalogue/models.py", "focal_class": null, "focal_method": "get_measure_scales", "tests": "import unittest\n\nclass Test_get_measure_scales(unittest.TestCase):\n def test_available_measures_scales(self):\n self.create_test_fixture()\n self.assertEqual(set(['mL', 'mb']), self.catalogue.get_measure_scales())\n", "method_code": " def get_measure_scales(self):\n \"\"\"\n Returns a set containing the measure scales.\n \"\"\"\n available_scales = [magnitude_measure.scale for magnitude_measure in self.session.query(MagnitudeMeasure).all()]\n return set(available_scales)\n ", "context": "class CatalogueDatabase(object):\n def get_measure_scales(self): ...\n def __init__(self, drop=False, engine=DEFAULT_ENGINE, **engine_params): ...\n def recreate(self): ...\n def close(self): ...\n def get_engine(cls, module_name): ...\n def session(self): ...\n def load_file(self, filename, importer_module_name, **kwargs): ...\n def position_from_latlng(self, latitude, longitude): ...\n def get_or_create(self, class_object, query_args, creation_args=None): ...\n def get_agencies(self): ...\n def get_summary(self): ...\n\n self._engine_class = self.__class__.get_engine(engine)\n self._engine = self._engine_class(**engine_params)\n\n __metaclass__ = Workspace\n MEASURE_AGENCIES = 'available_measure_agencies'\n MEASURE_SCALES = 'available_measure_scales'\n", "repository": "gvallarelli/oq-eqcatalogue-tool", "test_name": "test_available_measures_scales", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 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_000252.py"} {"focal_file": "eqcatalogue/models.py", "focal_class": null, "focal_method": "get_summary", "tests": "import unittest\n\nclass Test_get_summary(unittest.TestCase):\n def test_get_summary(self):\n self.create_test_fixture()\n self.assertEqual({catalogue.CatalogueDatabase.MEASURE_AGENCIES: set(['Tatooine', 'Alderaan', 'DeathStar']), catalogue.CatalogueDatabase.MEASURE_SCALES: set(['mL', 'mb'])}, self.catalogue.get_summary())\n", "method_code": " def get_summary(self):\n \"\"\"\n Returns a summary dict with informations related\n to the available measure agencies and scales.\n \"\"\"\n return {self.__class__.MEASURE_AGENCIES: self.get_agencies(), self.__class__.MEASURE_SCALES: self.get_measure_scales()}\n ", "context": "class CatalogueDatabase(object):\n def get_summary(self): ...\n def __init__(self, drop=False, engine=DEFAULT_ENGINE, **engine_params): ...\n def recreate(self): ...\n def close(self): ...\n def get_engine(cls, module_name): ...\n def session(self): ...\n def load_file(self, filename, importer_module_name, **kwargs): ...\n def position_from_latlng(self, latitude, longitude): ...\n def get_or_create(self, class_object, query_args, creation_args=None): ...\n def get_agencies(self): ...\n def get_measure_scales(self): ...\n\n self._engine_class = self.__class__.get_engine(engine)\n self._engine = self._engine_class(**engine_params)\n\n __metaclass__ = Workspace\n MEASURE_AGENCIES = 'available_measure_agencies'\n MEASURE_SCALES = 'available_measure_scales'\n", "repository": "gvallarelli/oq-eqcatalogue-tool", "test_name": "test_get_summary", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 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_000253.py"} {"focal_file": "eqcatalogue/filtering.py", "focal_class": "eqcatalogue.filtering.Criteria", "focal_method": "events", "tests": "import unittest\n\nclass Test_eqcatalogue_filtering_Criteria_events(unittest.TestCase):\n def test_return_events(self):\n self.assertEqual(5, len(filtering.Criteria().events()))\n", "method_code": " def events(self):\n \"\"\"\n Returns all the distinct events associated with all the\n measures that satisfies the criteria\n \"\"\"\n subquery = self.filter().subquery()\n return self._session.query(db.Event).join(subquery).all()\n ", "context": "class Criteria(object):\n def events(self): ...\n def __init__(self): ...\n def filter(self, queryset=None): ...\n def all(self, order_field='catalogue_magnitudemeasure.id'): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __contains__(self, el): ...\n def count(self): ...\n def predicate(self, measure): ...\n def __and__(self, criteria): ...\n def __getitem__(self, item): ...\n def __or__(self, criteria): ...\n def group_measures(self, grouping_strategy=None): ...\n\n self._cat = db.CatalogueDatabase()\n self._session = self._cat.session\n self.default_queryset = self._session.query(db.MagnitudeMeasure).join(db.Origin).join(db.Agency)\n", "repository": "gvallarelli/oq-eqcatalogue-tool", "test_name": "test_return_events", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 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_000254.py"} {"focal_file": "eqcatalogue/filtering.py", "focal_class": "eqcatalogue.filtering.Criteria", "focal_method": "group_measures", "tests": "import unittest\n\nclass Test_eqcatalogue_filtering_Criteria_group_measures(unittest.TestCase):\n def test_group_measures(self):\n self.assertTrue(filtering.Criteria().group_measures())\n", "method_code": " def group_measures(self, grouping_strategy=None):\n \"\"\"\n Returns a dictionary where the key identifies an event,\n and the value stores a list of associated measures\n \n :grouping_strategy: an instance of\n :class:`~eqcatalogue.grouping.GroupMeasuresByHierarchicalClustering`\n or :class:`~eqcatalogue.grouping.GroupMeasuresByEventSourceKey`.\n \"\"\"\n if not grouping_strategy:\n from eqcatalogue.grouping import GroupMeasuresByEventSourceKey\n grouping_strategy = GroupMeasuresByEventSourceKey()\n return grouping_strategy.group_measures(self)\n ", "context": "class Criteria(object):\n def group_measures(self, grouping_strategy=None): ...\n def __init__(self): ...\n def filter(self, queryset=None): ...\n def all(self, order_field='catalogue_magnitudemeasure.id'): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __contains__(self, el): ...\n def events(self): ...\n def count(self): ...\n def predicate(self, measure): ...\n def __and__(self, criteria): ...\n def __getitem__(self, item): ...\n def __or__(self, criteria): ...\n\n self._cat = db.CatalogueDatabase()\n self._session = self._cat.session\n self.default_queryset = self._session.query(db.MagnitudeMeasure).join(db.Origin).join(db.Agency)\n", "repository": "gvallarelli/oq-eqcatalogue-tool", "test_name": "test_group_measures", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 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_000255.py"} {"focal_file": "eqcatalogue/filtering.py", "focal_class": null, "focal_method": "predicate", "tests": "import unittest\n\nclass Test_predicate(unittest.TestCase):\n def test_default_predicate(self):\n measure = random.choice(filtering.C())\n self.assertTrue(filtering.C().predicate(measure))\n", "method_code": " def predicate(self, measure):\n \"\"\"\n Returns true if the criteria fulfills for the specified\n `measure`. It should be implemented by derived classes,\n otherwise a query is performed for check the existance\n \"\"\"\n return measure in self.filter()\n ", "context": "class Criteria(object):\n def predicate(self, measure): ...\n def __init__(self): ...\n def filter(self, queryset=None): ...\n def all(self, order_field='catalogue_magnitudemeasure.id'): ...\n def __iter__(self): ...\n def __len__(self): ...\n def __contains__(self, el): ...\n def events(self): ...\n def count(self): ...\n def __and__(self, criteria): ...\n def __getitem__(self, item): ...\n def __or__(self, criteria): ...\n def group_measures(self, grouping_strategy=None): ...\n\n self._cat = db.CatalogueDatabase()\n self._session = self._cat.session\n self.default_queryset = self._session.query(db.MagnitudeMeasure).join(db.Origin).join(db.Agency)\n", "repository": "gvallarelli/oq-eqcatalogue-tool", "test_name": "test_default_predicate", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 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_000256.py"} {"focal_file": "eqcatalogue/grouping.py", "focal_class": null, "focal_method": "group_measures", "tests": "import unittest\n\nclass Test_group_measures(unittest.TestCase):\n def test_allows_grouping_of_measures(self):\n all_events = self.measures\n groups = all_events.group_measures()\n self.assertEqual(5, len(groups.keys()))\n self.assertEqual(['1008566', '1008567', '1008568', '1008569', '1008570'], sorted(groups.keys()))\n", "method_code": " def group_measures(self, measures):\n \"\"\"\n Groups the measures by event source key\n \"\"\"\n return self.__class__.group(measures)\n ", "context": "class GroupMeasuresByEventSourceKey(object):\n def group_measures(self, measures): ...\n def group(cls, measures): ...\n", "repository": "gvallarelli/oq-eqcatalogue-tool", "test_name": "test_allows_grouping_of_measures", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 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_000257.py"} {"focal_file": "eqcatalogue/grouping.py", "focal_class": null, "focal_method": "build_graph", "tests": "import unittest\n\nclass Test_build_graph(unittest.TestCase):\n def test_build_graph(self):\n graph = grouping.GroupMeasuresBySequentialClustering.build_graph(self.measures, models.MagnitudeMeasure.time_distance, 0.5)\n for m1, related in graph.items():\n for m2 in related:\n self.assertTrue(abs(m1.origin.time - m2.origin.time).total_seconds() < 0.5)\n self.assertTrue(m1 != m2)\n", "method_code": " def build_graph(measures, fn, threshold):\n \"\"\"\n Build a graph where the nodes represents measures and two\n nodes n1 and n2 are linked iff fn(n1, n2) < threshold\n \"\"\"\n return dict([(m1, [m2 for m2 in measures if m1 != m2 and fn(m1, m2) < threshold]) for m1 in measures])\n ", "context": "class GroupMeasuresBySequentialClustering(object):\n @staticmethod\n def build_graph(measures, fn, threshold): ...\n def __init__(self, time_window, space_window, time_distance_fn=None, space_distance_fn=None, magnitude_window=None, magnitude_distance_fn=None): ...\n def group_measures(self, measures): ...\n def group_measures_by_time(self, measures): ...\n def group_measures_by_magnitude_value(self, measures): ...\n def group_measures_by_space(self, measures): ...\n def group_measures_by_var(self, measures, distance_fn, window): ...\n def find_connected_components(graph): ...\n\n self.time_window = time_window\n self.space_window = space_window\n self.time_distance_fn = time_distance_fn or MagnitudeMeasure.time_distance\n self.space_distance_fn = space_distance_fn or MagnitudeMeasure.space_distance\n self.magnitude_window = magnitude_window\n self.magnitude_distance_fn = magnitude_distance_fn\n", "repository": "gvallarelli/oq-eqcatalogue-tool", "test_name": "test_build_graph", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 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_000258.py"} {"focal_file": "eqcatalogue/grouping.py", "focal_class": null, "focal_method": "find_connected_components", "tests": "import unittest\n\nclass Test_find_connected_components(unittest.TestCase):\n def test_find_connected_components(self):\n cls = grouping.GroupMeasuresBySequentialClustering\n graph = cls.build_graph([1, 2, 3, 9, 10, 11], lambda x, y: abs(x - y), 2)\n comps = cls.find_connected_components(graph)\n for comp1 in comps:\n for comp2 in comps:\n if comp1 == comp2:\n continue\n self.assertTrue(not set(comp1).intersection(set(comp2)))\n", "method_code": " def find_connected_components(graph):\n \"\"\"\n Find the connected components of graph. The algorithm is based\n on multiple BFS search, so it is O(n^3) with n is the number\n of nodes.\n \"\"\"\n connected_components = defaultdict(lambda: [])\n for measure in graph.keys():\n if not any([measure in component for component in connected_components.values()]):\n to_visit = [measure]\n visited = {}\n while to_visit:\n m = to_visit.pop()\n if not m in connected_components[measure]:\n connected_components[measure].append(m)\n visited[m] = True\n to_visit.extend([m for m in graph[m] if not visited.get(m)])\n return connected_components.values()\n ", "context": "class GroupMeasuresBySequentialClustering(object):\n @staticmethod\n def find_connected_components(graph): ...\n def __init__(self, time_window, space_window, time_distance_fn=None, space_distance_fn=None, magnitude_window=None, magnitude_distance_fn=None): ...\n def group_measures(self, measures): ...\n def group_measures_by_time(self, measures): ...\n def group_measures_by_magnitude_value(self, measures): ...\n def group_measures_by_space(self, measures): ...\n def group_measures_by_var(self, measures, distance_fn, window): ...\n def build_graph(measures, fn, threshold): ...\n\n self.time_window = time_window\n self.space_window = space_window\n self.time_distance_fn = time_distance_fn or MagnitudeMeasure.time_distance\n self.space_distance_fn = space_distance_fn or MagnitudeMeasure.space_distance\n self.magnitude_window = magnitude_window\n self.magnitude_distance_fn = magnitude_distance_fn\n", "repository": "gvallarelli/oq-eqcatalogue-tool", "test_name": "test_find_connected_components", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 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_000259.py"} {"focal_file": "eqcatalogue/grouping.py", "focal_class": null, "focal_method": "group_measures_by_time", "tests": "import unittest\n\nclass Test_group_measures_by_time(unittest.TestCase):\n def test_group_measures_by_time(self):\n groups = self.grouper.group_measures_by_time(self.measures)\n self.assertEqual(2, len(groups))\n for measures in groups:\n self.assertTrue(self.m == len(measures) or 2 * self.m == len(measures))\n", "method_code": " def group_measures_by_time(self, measures):\n \"\"\"\n Group `measures` in time by using the time_window and the\n time_distance_fn\n \"\"\"\n groups = self.group_measures_by_var(measures, self.time_distance_fn, self.time_window)\n log.logger(__name__).debug('grouping by time returned %d groups', len(groups))\n return groups\n ", "context": "class GroupMeasuresBySequentialClustering(object):\n def group_measures_by_time(self, measures): ...\n def __init__(self, time_window, space_window, time_distance_fn=None, space_distance_fn=None, magnitude_window=None, magnitude_distance_fn=None): ...\n def group_measures(self, measures): ...\n def group_measures_by_magnitude_value(self, measures): ...\n def group_measures_by_space(self, measures): ...\n def group_measures_by_var(self, measures, distance_fn, window): ...\n def build_graph(measures, fn, threshold): ...\n def find_connected_components(graph): ...\n\n self.time_window = time_window\n self.space_window = space_window\n self.time_distance_fn = time_distance_fn or MagnitudeMeasure.time_distance\n self.space_distance_fn = space_distance_fn or MagnitudeMeasure.space_distance\n self.magnitude_window = magnitude_window\n self.magnitude_distance_fn = magnitude_distance_fn\n", "repository": "gvallarelli/oq-eqcatalogue-tool", "test_name": "test_group_measures_by_time", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 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, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000260.py"} {"focal_file": "eqcatalogue/grouping.py", "focal_class": null, "focal_method": "group_measures_by_space", "tests": "import unittest\n\nclass Test_group_measures_by_space(unittest.TestCase):\n def test_group_measures_by_space(self):\n groups = self.grouper.group_measures_by_space(self.measures)\n self.assertEqual(2, len(groups))\n for measures in groups:\n self.assertTrue(self.m == len(measures) or 2 * self.m == len(measures))\n", "method_code": " def group_measures_by_space(self, measures):\n \"\"\"\n Group `measures` in space by using the space_window and the\n space_distance_fn\n \"\"\"\n groups = self.group_measures_by_var(measures, self.space_distance_fn, self.space_window)\n log.logger(__name__).debug('grouping by space returned %d groups', len(groups))\n return groups\n ", "context": "class GroupMeasuresBySequentialClustering(object):\n def group_measures_by_space(self, measures): ...\n def __init__(self, time_window, space_window, time_distance_fn=None, space_distance_fn=None, magnitude_window=None, magnitude_distance_fn=None): ...\n def group_measures(self, measures): ...\n def group_measures_by_time(self, measures): ...\n def group_measures_by_magnitude_value(self, measures): ...\n def group_measures_by_var(self, measures, distance_fn, window): ...\n def build_graph(measures, fn, threshold): ...\n def find_connected_components(graph): ...\n\n self.time_window = time_window\n self.space_window = space_window\n self.time_distance_fn = time_distance_fn or MagnitudeMeasure.time_distance\n self.space_distance_fn = space_distance_fn or MagnitudeMeasure.space_distance\n self.magnitude_window = magnitude_window\n self.magnitude_distance_fn = magnitude_distance_fn\n", "repository": "gvallarelli/oq-eqcatalogue-tool", "test_name": "test_group_measures_by_space", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 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, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000261.py"} {"focal_file": "eqcatalogue/harmoniser.py", "focal_class": "Harmoniser", "focal_method": "add_conversion_formula", "tests": "import unittest\n\nclass Test_Harmoniser_add_conversion_formula(unittest.TestCase):\n def test_one_conversion(self):\n \"\"\"\n Test with one conversion. Given a target scale, a list of measures\n (in a single magnitude scales), and an empirical magnitude\n scaling relationship (between a native scale mb and the\n considered target scale), an Harmoniser should convert to the\n target scale only the measure in that native scale\n \"\"\"\n mismatches = self.number_of_measures / 3\n h = Harmoniser(target_scale=self.target_scale)\n h.add_conversion_formula(**self.a_conversion)\n result = h.harmonise(self.measures)\n self.assertConversion(result, self.number_of_measures - mismatches, mismatches)\n\n def test_conversion(self):\n h = Harmoniser(target_scale=self.target_scale)\n h.add_conversion_formula(formula=lambda x: x * 2.0, model_error=0.2, domain=C(scale=self.a_native_scale), target_scale='M2')\n h.add_conversion_formula(formula=lambda x: x * 3.0, model_error=0.1, domain=C(scale=self.ya_native_scale), target_scale='M3')\n h.add_conversion_formula(formula=lambda x: x * 3.0, model_error=0.2, domain=C(scale='M3'), target_scale='M2')\n h.add_conversion_formula(formula=lambda x: x * 4.0, model_error=0.3, domain=C(scale='M2'), target_scale=self.target_scale)\n h.add_conversion_formula(formula=lambda x: x * 4.0, model_error=0.4, domain=C(scale='M2'), target_scale='M4')\n h.add_conversion_formula(formula=lambda x: x * 4.0, model_error=0.2, domain=C(scale='M2'), target_scale='M5')\n result = h.harmonise(self.measures)\n self.assertEqual(30, len(result.converted))\n self.assertEqual(0, len(result.unconverted))\n for measure in self.measures:\n converted_measure = result.converted[measure]\n if measure.scale == self.a_native_scale:\n self.assertAlmostEqual(converted_measure.value, measure.value * 8)\n elif measure.scale == self.target_scale:\n self.assertAlmostEqual(converted_measure.value, measure.value)\n elif measure.scale == self.ya_native_scale:\n self.assertEqual(3, len(converted_measure.formulas))\n self.assertAlmostEqual(converted_measure.value, measure.value * 36)\n", "method_code": " def add_conversion_formula(self, formula, model_error, domain, target_scale, name=None):\n \"\"\"\n Create a conversion formula from a `function` and make\n it available for the harmoniser.\n \n E.g.\n an_harmoniser.add_conversion_formula(\n lambda measure: measure * 1.2 + 0.1,\n 0.2, domain=C(scale=\"mb\") & C(agency__in=[\"ISC\"]),\n target_scale=\"Mw\")\n \n :param formula:\n A callable that requires in input the value to be converted\n \n :param model_error:\n The error associated with the formula.\n \n :param domain:\n The domain of measures mapped by conversion formula (an\n object, e.g. a list/set that can be queried with the in\n operator)\n \n :param target_scale:\n The target scale\n \n :param name: the name of the formula (used during export)\n \"\"\"\n formula = ConversionFormula(formula, model_error, domain, target_scale, name)\n self._add_formula(formula)\n ", "context": "class Harmoniser(object):\n def add_conversion_formula(self, formula, model_error, domain, target_scale, name=None): ...\n def __init__(self, target_scale): ...\n def add_conversion_formula_from_model(self, model, domain, name=None): ...\n def _add_formula(self, formula): ...\n def harmonise(self, measures, path_finder_cls=FormulaPathFinder, measure_uncertainty=0.0, allow_trivial_conversion=True): ...\n\n self.target_scale = target_scale\n self._formulas = {}\n", "repository": "gvallarelli/oq-eqcatalogue-tool", "test_name": "test_one_conversion", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 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, 1, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000262.py"} {"focal_file": "eqcatalogue/homogeniser.py", "focal_class": null, "focal_method": "add_model", "tests": "import unittest\n\nclass Test_add_model(unittest.TestCase):\n def test_homogenise_easily(self):\n self.homogeniser.add_model(LinearModel)\n self.homogeniser.add_model(PolynomialModel, order=2)\n self._write_and_check()\n", "method_code": " def add_model(self, model_class, **model_kwargs):\n \"\"\"\n Add a regression model to be calculated to homogenise\n magnitude values\n \n :param model_class:\n A class that implements the RegressionModel protocol.\n See :py:class:`eqcatalogue.regression` for the current\n admitted values\n \n Any other parameter is given as input to the constructor of\n `model_class`. E.g.::\n \n from eqcatalogue.regression import PolynomialModel\n an_homogeniser.add_model(PolynomialModel, order=3)\n \n \"\"\"\n self._models.append((model_class, model_kwargs))\n ", "context": "class Homogeniser(object):\n def add_model(self, model_class, **model_kwargs): ...\n def __init__(self, native_scale=None, target_scale=None, criteria=None, grouper=None, selector=None, missing_uncertainty_strategy=None, serializer=None): ...\n def reset_models(self): ...\n def set_scales(self, native, target): ...\n def set_grouper(self, grouper_class, **grouper_args): ...\n def set_selector(self, selector_class, **selector_args): ...\n def set_missing_uncertainty_strategy(self, mu_strategy_class, **mu_strategy_args): ...\n def set_criteria(self, criteria=None): ...\n def events(self): ...\n def measures(self): ...\n def grouped_measures(self): ...\n def _selected_measures(self): ...\n def selected_native_measures(self): ...\n def selected_target_measures(self): ...\n def perform_regression(self): ...\n def serialize(self, *serializer_args, **serializer_kwargs): ...\n def plot(self, *args, **kwargs): ...\n\n self._criteria = criteria or Criteria()\n self._grouper = grouper or grouping.GroupMeasuresByEventSourceKey()\n self._selector = selector or selection.Random()\n self._mu_strategy = missing_uncertainty_strategy or selection.MUSDiscard()\n self.serializer = serializer or mpl\n self._native_scale = native_scale\n self._target_scale = target_scale\n self._models = []\n self._emsr = None\n", "repository": "gvallarelli/oq-eqcatalogue-tool", "test_name": "test_homogenise_easily", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 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_000263.py"} {"focal_file": "eqcatalogue/homogeniser.py", "focal_class": null, "focal_method": "set_scales", "tests": "import unittest\n\nclass Test_set_scales(unittest.TestCase):\n def test_homogenise_different_scales(self):\n self.homogeniser.set_criteria()\n self.homogeniser.set_scales(native='mb', target='MS')\n self.homogeniser.set_missing_uncertainty_strategy(selection.MUSSetDefault, default=0.2)\n self.homogeniser.add_model(LinearModel)\n self._write_and_check()\n\n def test_homogenise_after_different_setup_sequences_1(self):\n self.homogeniser.set_scales(native='MS', target='MW')\n self.homogeniser.set_criteria(C(magnitude__gt=4))\n self.homogeniser.set_grouper(grouping.GroupMeasuresByHierarchicalClustering, args={'t': 100})\n self.homogeniser.set_selector(selection.Precise)\n self.homogeniser.set_missing_uncertainty_strategy(selection.MUSSetDefault, default=1)\n self.assertTrue(len(self.homogeniser.selected_native_measures()) > 1)\n self.assertTrue(len(self.homogeniser.selected_target_measures()) > 1)\n self.homogeniser.add_model(LinearModel)\n self._write_and_check()\n\n def test_homogenise_after_different_setup_sequences_2(self):\n self.homogeniser.set_scales(native='MS', target='MW')\n self.homogeniser.set_grouper(grouping.GroupMeasuresByHierarchicalClustering, args={'t': 100})\n self.homogeniser.set_criteria(C(magnitude__gt=4))\n self.homogeniser.set_selector(selection.Precise)\n self.homogeniser.set_missing_uncertainty_strategy(selection.MUSSetDefault, default=1)\n self.assertTrue(len(self.homogeniser.selected_native_measures()) > 1)\n self.assertTrue(len(self.homogeniser.selected_target_measures()) > 1)\n self.homogeniser.add_model(LinearModel)\n self._write_and_check()\n", "method_code": " def set_scales(self, native, target):\n \"\"\"\n Set Native and Target Scale\n \n :param native:\n The native magnitude scale (e.g. ML). Case Sensitive\n :param target:\n The target magnitude scale (e.g. MW). Case Sensitive\n \"\"\"\n self._native_scale = native\n self._target_scale = target\n ", "context": "class Homogeniser(object):\n def set_scales(self, native, target): ...\n def __init__(self, native_scale=None, target_scale=None, criteria=None, grouper=None, selector=None, missing_uncertainty_strategy=None, serializer=None): ...\n def reset_models(self): ...\n def add_model(self, model_class, **model_kwargs): ...\n def set_grouper(self, grouper_class, **grouper_args): ...\n def set_selector(self, selector_class, **selector_args): ...\n def set_missing_uncertainty_strategy(self, mu_strategy_class, **mu_strategy_args): ...\n def set_criteria(self, criteria=None): ...\n def events(self): ...\n def measures(self): ...\n def grouped_measures(self): ...\n def _selected_measures(self): ...\n def selected_native_measures(self): ...\n def selected_target_measures(self): ...\n def perform_regression(self): ...\n def serialize(self, *serializer_args, **serializer_kwargs): ...\n def plot(self, *args, **kwargs): ...\n\n self._criteria = criteria or Criteria()\n self._grouper = grouper or grouping.GroupMeasuresByEventSourceKey()\n self._selector = selector or selection.Random()\n self._mu_strategy = missing_uncertainty_strategy or selection.MUSDiscard()\n self.serializer = serializer or mpl\n self._native_scale = native_scale\n self._target_scale = target_scale\n self._models = []\n self._emsr = None\n", "repository": "gvallarelli/oq-eqcatalogue-tool", "test_name": "test_homogenise_different_scales", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 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, 1], "pynose_source_file": "test_000264.py"} {"focal_file": "eqcatalogue/regression.py", "focal_class": "EmpiricalMagnitudeScalingRelationship", "focal_method": "apply_regression_model", "tests": "import unittest\n\nclass Test_EmpiricalMagnitudeScalingRelationship_apply_regression_model(unittest.TestCase):\n def test_linear_regression(self):\n A = 0.85\n B = 1.03\n native_measures = catalogue.MagnitudeMeasure.make_from_lists('mb', np.random.uniform(3.0, 8.5, 1000), np.random.uniform(0.02, 0.2, 1000))\n target_measures = catalogue.MagnitudeMeasure.make_from_lists('Mw', A + B * np.array([m.value for m in native_measures]), np.random.uniform(0.025, 0.2, 1000))\n emsr = EmpiricalMagnitudeScalingRelationship(native_measures, target_measures)\n _, output = emsr.apply_regression_model(LinearModel)\n self.assertTrue(allclose(np.array([A, B]), output.beta))\n self.assertTrue(output.res_var < 1e-20)\n\n def test_polynomial_regression(self):\n A = 0.046\n B = 0.556\n C = 0.673\n native_measures = catalogue.MagnitudeMeasure.make_from_lists('mb', np.random.uniform(3.0, 8.5, 1000), np.random.uniform(0.02, 0.2, 1000))\n target_measures = catalogue.MagnitudeMeasure.make_from_lists('Mw', C + B * np.array([m.value for m in native_measures]) + A * np.array([m.value for m in native_measures]) ** 2.0, np.random.uniform(0.025, 0.2, 1000))\n emsr = EmpiricalMagnitudeScalingRelationship(native_measures, target_measures)\n _, output = emsr.apply_regression_model(PolynomialModel, order=2)\n self.assertTrue(allclose(np.array([C, B, A]), output.beta))\n self.assertTrue(output.res_var < 1e-20)\n", "method_code": " def apply_regression_model(self, model_type=DEFAULT_MODEL_TYPE, **regression_params):\n \"\"\"\n Apply a regression model to the measures\n :param model_type:\n an instance of :class:`~eqcatalgue.regression.RegressionModel`.\n \n :param regression_params:\n Arguments passed to the RegressionModel being constructed. See\n RegressionModel#__init__ documentation for details.\n \n :return:\n a tuple with a RegressionModel instance and its output\n \"\"\"\n if not hasattr(model_type, 'is_regression_model'):\n raise TypeError('Invalid Model type selected (%s). It should be a subclass of RegressionModel' % model_type)\n if len(self.native_measures) < 2:\n raise exceptions.NotEnoughSamples('Not enough measures to perform regression. Please relax your query or selection criteria')\n regression_model = model_type(self.native_measures, self.target_measures, **regression_params)\n output = regression_model.run()\n self.regression_models.append(regression_model)\n return (regression_model, output)\n ", "context": "class EmpiricalMagnitudeScalingRelationship(object):\n def apply_regression_model(self, model_type=DEFAULT_MODEL_TYPE, **regression_params): ...\n def make_from_events(cls, native_scale, target_scale, events, selection_strategy, missing_uncertainty_strategy=None): ...\n def make_from_measures(cls, native_scale, target_scale, grouped_measures, selection_strategy, missing_uncertainty_strategy=None): ...\n def __init__(self, native_measures=None, target_measures=None): ...\n\n self.native_measures = native_measures\n self.target_measures = target_measures\n self.regression_models = []\n\n DEFAULT_MODEL_TYPE = LinearModel\n", "repository": "gvallarelli/oq-eqcatalogue-tool", "test_name": "test_linear_regression", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 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_000265.py"} {"focal_file": "newton.py", "focal_class": null, "focal_method": "interpolation_polynomial", "tests": "import unittest\n\nclass Test_interpolation_polynomial(unittest.TestCase):\n def test_zero_degree_polynomial(self):\n \"\"\"Are zero degree (constant) polynomials handled correctly?\"\"\"\n p, p_str = newton.interpolation_polynomial([(0, 2)], get_string=True)\n self.assertEqual(p(-3.14), 2)\n self.assertEqual(p_str, 'p(x) = 2')\n", "method_code": "def interpolation_polynomial(known_points, get_string=False):\n \"\"\"Create an interpolation polynomial of upto n degree passing through all \n of the supplied n+1 points.\n Inputs: known_points - a table of known points on your function supplied \n as a list of (x,y) tuples, where each x value is unique.\n get_string - flag to get the poynomial's string representation.\n Returns: p - an approximation polynomial for your function.\n p_string - a string representation of newton basis polynomial.\n \"\"\"\n x_knots = sorted((point[0] for point in known_points))\n n = len(x_knots) - 1\n div_diffs = div_diff_function(known_points)\n coeffs = [div_diffs(x_knots[:i + 1]) for i in range(len(x_knots))]\n\n def p(x):\n \"\"\"Interpolation polynomial p(x) = c0 + c1(x - x0) + c2(x - x0)(x - x1) + ...\n Inputs: x - real value x in [x0,xn]\n Returns: real valued approximation\"\"\"\n total = coeffs[0]\n basis = 1\n for i in range(n):\n basis = basis * (x - x_knots[i])\n total = total + coeffs[i + 1] * basis\n return total\n return (p, _str_newton_poly(coeffs, x_knots)) if get_string else p", "context": "def interpolation_polynomial(known_points, get_string=False): ...\ndef div_diff_function(known_points): ...\ndef interpolation_polynomial(known_points, get_string=False): ...\ndef _str_newton_poly(coeffs, x_knots): ...\n", "repository": "ccatlin/newton", "test_name": "test_zero_degree_polynomial", "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_000266.py"} {"focal_file": "newton.py", "focal_class": null, "focal_method": "f", "tests": "import unittest\n\nclass Test_f(unittest.TestCase):\n def test_polynomial_interpolates_to_itself(self):\n\n def f(x):\n return 4 * x ** 3 + 2 * x + 1\n x_knots = [x for x in range(-2, 2)]\n p = newton.interpolation_polynomial([(x, f(x)) for x in x_knots])\n self.assertEqual(p(0.5), f(0.5))\n", "method_code": "def f(xs):\n \"\"\"Divided difference function, a linear approximation of the i-j \n derivative from (xi,f(xi)) to (xi+j,f(xi+j)).\n Inputs: xs - tuple of (xi, xi+1, ..., xi+j) sequential, known x values. \n Returns: a real value represnting the forward divided difference.\"\"\"\n xi_tuple = tuple(sorted(xs))\n if xi_tuple not in f_cache:\n f_cache[xi_tuple] = (f(xi_tuple[1:]) - f(xi_tuple[:-1])) / float(xi_tuple[-1] - xi_tuple[0])\n return f_cache[xi_tuple]", "context": "def f(xs): ...\ndef div_diff_function(known_points): ...\ndef interpolation_polynomial(known_points, get_string=False): ...\ndef _str_newton_poly(coeffs, x_knots): ...\n", "repository": "ccatlin/newton", "test_name": "test_polynomial_interpolates_to_itself", "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_000267.py"} {"focal_file": "newton.py", "focal_class": null, "focal_method": "_str_newton_poly", "tests": "import unittest\n\nclass Test_str_newton_poly(unittest.TestCase):\n def test_str_newton_poly(self):\n exp_str = 'p(x) = -1 + 2(x + 3) - 4(x + 3)(x - 5)x'\n p_str = newton._str_newton_poly([-1, 2, 0, -4], [-3, 5, 0, 100])\n self.assertEqual(exp_str, p_str)\n", "method_code": "def _str_newton_poly(coeffs, x_knots):\n \"\"\"Create a string representation of the polynomial with the supplied\n coefficients and a newton basis based on the x_knots. \n 'p(x) = c0 + c1(x - x0) + c2(x - x0)(x - x1) + ...'\n Inputs: coeffs - ordered coefficients\n x_knots - sequential xi values used in the newton basis\n Returns: a string representation of newton basis polynomial.\n \"\"\"\n basis, poly_string = ('', str(coeffs[0]))\n for ci, xi in zip(coeffs[1:], x_knots[:-1]):\n if xi < 0:\n basis += '(x + ' + str(-xi) + ')'\n elif xi == 0:\n basis += 'x'\n else:\n basis += '(x - ' + str(xi) + ')'\n add = ' + ' if ci >= 0 else ' - '\n if ci == 0:\n next\n elif abs(ci) == 1:\n poly_string += add + basis\n else:\n poly_string += add + str(abs(ci)) + basis\n return 'p(x) = ' + poly_string", "context": "def _str_newton_poly(coeffs, x_knots): ...\ndef div_diff_function(known_points): ...\ndef interpolation_polynomial(known_points, get_string=False): ...\ndef _str_newton_poly(coeffs, x_knots): ...\n", "repository": "ccatlin/newton", "test_name": "test_str_newton_poly", "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_000268.py"} {"focal_file": "stylesite/django/contrib/gis/geometry/test_data.py", "focal_class": null, "focal_method": "get_ds_file", "tests": "import unittest\n\nclass Test_get_ds_file(unittest.TestCase):\n def test06_spatial_filter(self):\n \"\"\"Testing the Layer.spatial_filter property.\"\"\"\n ds = DataSource(get_ds_file('cities', 'shp'))\n lyr = ds[0]\n self.assertEqual(None, lyr.spatial_filter)\n self.assertRaises(TypeError, lyr._set_spatial_filter, 'foo')\n self.assertRaises(ValueError, lyr._set_spatial_filter, list(range(5)))\n filter_extent = (-105.609252, 37.255001, -103.609252, 39.255001)\n lyr.spatial_filter = (-105.609252, 37.255001, -103.609252, 39.255001)\n self.assertEqual(OGRGeometry.from_bbox(filter_extent), lyr.spatial_filter)\n feats = [feat for feat in lyr]\n self.assertEqual(1, len(feats))\n self.assertEqual('Pueblo', feats[0].get('Name'))\n filter_geom = OGRGeometry('POLYGON((-96.363151 28.763374,-94.363151 28.763374,-94.363151 30.763374,-96.363151 30.763374,-96.363151 28.763374))')\n lyr.spatial_filter = filter_geom\n self.assertEqual(filter_geom, lyr.spatial_filter)\n feats = [feat for feat in lyr]\n self.assertEqual(1, len(feats))\n self.assertEqual('Houston', feats[0].get('Name'))\n lyr.spatial_filter = None\n self.assertEqual(3, len(lyr))\n", "method_code": "def get_ds_file(name, ext):\n return os.path.join(TEST_DATA, name, name + '.%s' % ext)", "context": "def get_ds_file(name, ext): ...\ndef tuplize(seq): ...\ndef strconvert(d): ...\ndef get_ds_file(name, ext): ...\n", "repository": "melissapnyc/insphairation", "test_name": "test06_spatial_filter", "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, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000269.py"} {"focal_file": "stylesite/django/utils/six.py", "focal_class": null, "focal_method": "write", "tests": "import unittest\n\nclass Test_write(unittest.TestCase):\n def test02_wktwriter(self):\n wkt_w = WKTWriter()\n self.assertRaises(TypeError, wkt_w._set_ptr, WKTReader.ptr_type())\n ref = GEOSGeometry('POINT (5 23)')\n ref_wkt = 'POINT (5.0000000000000000 23.0000000000000000)'\n self.assertEqual(ref_wkt, wkt_w.write(ref).decode())\n\n def test04_wkbwriter(self):\n wkb_w = WKBWriter()\n g = GEOSGeometry('POINT (5 23)')\n hex1 = b'010100000000000000000014400000000000003740'\n wkb1 = memoryview(binascii.a2b_hex(hex1))\n hex2 = b'000000000140140000000000004037000000000000'\n wkb2 = memoryview(binascii.a2b_hex(hex2))\n self.assertEqual(hex1, wkb_w.write_hex(g))\n self.assertEqual(wkb1, wkb_w.write(g))\n for bad_byteorder in (-1, 2, 523, 'foo', None):\n self.assertRaises(ValueError, wkb_w._set_byteorder, bad_byteorder)\n wkb_w.byteorder = 0\n self.assertEqual(hex2, wkb_w.write_hex(g))\n self.assertEqual(wkb2, wkb_w.write(g))\n wkb_w.byteorder = 1\n g = GEOSGeometry('POINT (5 23 17)')\n g.srid = 4326\n hex3d = b'0101000080000000000000144000000000000037400000000000003140'\n wkb3d = memoryview(binascii.a2b_hex(hex3d))\n hex3d_srid = b'01010000A0E6100000000000000000144000000000000037400000000000003140'\n wkb3d_srid = memoryview(binascii.a2b_hex(hex3d_srid))\n for bad_outdim in (-1, 0, 1, 4, 423, 'foo', None):\n self.assertRaises(ValueError, wkb_w._set_outdim, bad_outdim)\n if not geos_version_info()['version'].startswith('3.0.'):\n wkb_w.outdim = 3\n self.assertEqual(hex3d, wkb_w.write_hex(g))\n self.assertEqual(wkb3d, wkb_w.write(g))\n wkb_w.srid = True\n self.assertEqual(hex3d_srid, wkb_w.write_hex(g))\n self.assertEqual(wkb3d_srid, wkb_w.write(g))\n", "method_code": "def write(data):\n if not isinstance(data, basestring):\n data = str(data)\n fp.write(data)", "context": "def write(data): ...\ndef _add_doc(func, doc): ...\ndef _import_module(name): ...\ndef add_move(move): ...\ndef remove_move(name): ...\ndef iterkeys(d, **kw): ...\ndef itervalues(d, **kw): ...\ndef iteritems(d, **kw): ...\ndef iterlists(d, **kw): ...\ndef with_metaclass(meta, *bases): ...\ndef add_metaclass(metaclass): ...\ndef assertRaisesRegex(self, *args, **kwargs): ...\n", "repository": "melissapnyc/insphairation", "test_name": "test02_wktwriter", "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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000270.py"} {"focal_file": "flashproxy-client-test.py", "focal_class": null, "focal_method": "default_req", "tests": "import unittest\n\nclass Test_default_req(unittest.TestCase):\n def test_default(self):\n req = self.default_req()\n self.assert_ok(req)\n", "method_code": " def default_req():\n req = HTTPRequest()\n req.method = 'GET'\n req.path = '/'\n req.headers['Upgrade'] = 'websocket'\n req.headers['Connection'] = 'Upgrade'\n req.headers['Sec-WebSocket-Key'] = TestHandleWebSocketRequest.DEFAULT_KEY_BASE64\n req.headers['Sec-WebSocket-Version'] = '13'\n return req\n ", "context": "class TestHandleWebSocketRequest(unittest.TestCase):\n @staticmethod\n def default_req(): ...\n def assert_ok(self, req): ...\n def assert_not_ok(self, req): ...\n def test_default(self): ...\n def test_missing_upgrade(self): ...\n def test_missing_connection(self): ...\n def test_case_insensitivity(self): ...\n def test_bogus_key(self): ...\n def test_versions(self): ...\n def test_protocols(self): ...\n\n DEFAULT_KEY = '0123456789ABCDEF'\n DEFAULT_KEY_BASE64 = base64.b64encode(DEFAULT_KEY)\n MAGIC_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'\n", "repository": "glamrock/flashproxy", "test_name": "test_default", "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_000271.py"} {"focal_file": "flashproxy-client-test.py", "focal_class": null, "focal_method": "read_frames", "tests": "import unittest\n\nclass Test_read_frames(unittest.TestCase):\n def test_empty_frame(self):\n \"\"\"Test that a frame may contain a zero-byte payload.\"\"\"\n dec = WebSocketDecoder()\n dec.feed('\\x81\\x00')\n self.assertEqual(read_frames(dec), [(True, 1, u'')])\n dec.feed('\\x82\\x00')\n self.assertEqual(read_frames(dec), [(True, 2, '')])\n", "method_code": "def read_frames(dec):\n frames = []\n while True:\n frame = dec.read_frame()\n if frame is None:\n break\n frames.append((frame.fin, frame.opcode, frame.payload))\n return frames", "context": "def read_frames(dec): ...\ndef dummy_socketpair(): ...\ndef transact_http(req): ...\ndef read_frames(dec): ...\ndef read_messages(dec): ...\ndef format_address(addr): ...\n", "repository": "glamrock/flashproxy", "test_name": "test_empty_frame", "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_000272.py"} {"focal_file": "flashproxy-client-test.py", "focal_class": null, "focal_method": "read_messages", "tests": "import unittest\n\nclass Test_read_messages(unittest.TestCase):\n def test_empty_message(self):\n \"\"\"Test that a message may have a zero-byte payload.\"\"\"\n dec = WebSocketDecoder()\n dec.feed('\\x01\\x00\\x00\\x00\\x80\\x00')\n self.assertEqual(read_messages(dec), [(1, u'')])\n dec.feed('\\x02\\x00\\x00\\x00\\x80\\x00')\n self.assertEqual(read_messages(dec), [(2, '')])\n", "method_code": "def read_messages(dec):\n messages = []\n while True:\n message = dec.read_message()\n if message is None:\n break\n messages.append((message.opcode, message.payload))\n return messages", "context": "def read_messages(dec): ...\ndef dummy_socketpair(): ...\ndef transact_http(req): ...\ndef read_frames(dec): ...\ndef read_messages(dec): ...\ndef format_address(addr): ...\n", "repository": "glamrock/flashproxy", "test_name": "test_empty_message", "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_000273.py"} {"focal_file": "flashproxy/reg.py", "focal_class": "Transport", "focal_method": "parse", "tests": "import unittest\n\nclass Test_Transport_parse(unittest.TestCase):\n def test_transport_parse(self):\n self.assertEquals(Transport.parse('a'), Transport('', 'a'))\n self.assertEquals(Transport.parse('|a'), Transport('', 'a'))\n self.assertEquals(Transport.parse('a|b|c'), Transport('a|b', 'c'))\n self.assertEquals(Transport.parse(Transport('a|b', 'c')), Transport('a|b', 'c'))\n self.assertRaises(ValueError, Transport, '', '')\n self.assertRaises(ValueError, Transport, 'a', '')\n self.assertRaises(ValueError, Transport.parse, '')\n self.assertRaises(ValueError, Transport.parse, '|')\n self.assertRaises(ValueError, Transport.parse, 'a|')\n self.assertRaises(ValueError, Transport.parse, ['a'])\n self.assertRaises(ValueError, Transport.parse, [Transport('a', 'b')])\n", "method_code": " def parse(cls, transport):\n if isinstance(transport, cls):\n return transport\n elif type(transport) == str:\n if '|' in transport:\n inner, outer = transport.rsplit('|', 1)\n else:\n inner, outer = ('', transport)\n return cls(inner, outer)\n else:\n raise ValueError('could not parse transport: %s' % transport)\n ", "context": "class Transport(namedtuple('Transport', 'inner outer')):\n @classmethod\n def parse(cls, transport): ...\n def __init__(self, inner, outer): ...\n def __str__(self): ...\n", "repository": "glamrock/flashproxy", "test_name": "test_transport_parse", "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_000274.py"} {"focal_file": "paramiko-1.16.0/paramiko/file.py", "focal_class": null, "focal_method": "readline", "tests": "import unittest\n\nclass Test_readline(unittest.TestCase):\n def test_2_readline(self):\n f = LoopbackFile('r+U')\n f.write(b'First line.\\nSecond line.\\r\\nThird line.\\n' + b'Fourth line.\\nFinal line non-terminated.')\n self.assertEqual(f.readline(), 'First line.\\n')\n self.assertEqual(f.readline(), 'Second line.\\n')\n self.assertEqual(f.readline(7), 'Third l')\n self.assertEqual(f.readline(), 'ine.\\n')\n self.assertEqual(f.readline(39), 'Fourth line.\\n')\n self.assertEqual(f.readline(), 'Final line non-terminated.')\n self.assertEqual(f.readline(), '')\n f.close()\n try:\n f.readline()\n self.assertTrue(False, 'no exception on readline of closed file')\n except IOError:\n pass\n self.assertTrue(linefeed_byte in f.newlines)\n self.assertTrue(crlf in f.newlines)\n self.assertTrue(cr_byte not in f.newlines)\n", "method_code": " def readline(self, size=None):\n \"\"\"\n Read one entire line from the file. A trailing newline character is\n kept in the string (but may be absent when a file ends with an\n incomplete line). If the size argument is present and non-negative, it\n is a maximum byte count (including the trailing newline) and an\n incomplete line may be returned. An empty string is returned only when\n EOF is encountered immediately.\n \n .. note::\n Unlike stdio's ``fgets``, the returned string contains null\n characters (``'\\\\0'``) if they occurred in the input.\n \n :param int size: maximum length of returned string.\n :return:\n next line of the file, or an empty string if the end of the\n file has been reached.\n \n If the file was opened in binary (``'b'``) mode: bytes are returned\n Else: the encoding of the file is assumed to be UTF-8 and character\n strings (`str`) are returned\n \"\"\"\n if self._closed:\n raise IOError('File is closed')\n if not self._flags & self.FLAG_READ:\n raise IOError('File not open for reading')\n line = self._rbuffer\n truncated = False\n while True:\n if self._at_trailing_cr and self._flags & self.FLAG_UNIVERSAL_NEWLINE and (len(line) > 0):\n if line[0] == linefeed_byte_value:\n line = line[1:]\n self._record_newline(crlf)\n else:\n self._record_newline(cr_byte)\n self._at_trailing_cr = False\n if size is not None and size >= 0:\n if len(line) >= size:\n self._rbuffer = line[size:]\n line = line[:size]\n truncated = True\n break\n n = size - len(line)\n else:\n n = self._bufsize\n if linefeed_byte in line or (self._flags & self.FLAG_UNIVERSAL_NEWLINE and cr_byte in line):\n break\n try:\n new_data = self._read(n)\n except EOFError:\n new_data = None\n if new_data is None or len(new_data) == 0:\n self._rbuffer = bytes()\n self._pos += len(line)\n return line if self._flags & self.FLAG_BINARY else u(line)\n line += new_data\n self._realpos += len(new_data)\n pos = line.find(linefeed_byte)\n if self._flags & self.FLAG_UNIVERSAL_NEWLINE:\n rpos = line.find(cr_byte)\n if rpos >= 0 and (rpos < pos or pos < 0):\n pos = rpos\n if pos == -1:\n self._pos += len(line)\n return line if self._flags & self.FLAG_BINARY else u(line)\n xpos = pos + 1\n if line[pos] == cr_byte_value and xpos < len(line) and (line[xpos] == linefeed_byte_value):\n xpos += 1\n self._rbuffer = line[xpos:] + self._rbuffer if truncated else line[xpos:]\n lf = line[pos:xpos]\n line = line[:pos] + linefeed_byte\n if len(self._rbuffer) == 0 and lf == cr_byte:\n self._at_trailing_cr = True\n else:\n self._record_newline(lf)\n self._pos += len(line)\n return line if self._flags & self.FLAG_BINARY else u(line)\n ", "context": "class BufferedFile(ClosingContextManager):\n def readline(self, size=None): ...\n def __init__(self): ...\n def __del__(self): ...\n def __iter__(self): ...\n def close(self): ...\n def flush(self): ...\n def read(self, size=None): ...\n def readlines(self, sizehint=None): ...\n def seek(self, offset, whence=0): ...\n def tell(self): ...\n def write(self, data): ...\n def writelines(self, sequence): ...\n def xreadlines(self): ...\n def closed(self): ...\n def _read(self, size): ...\n def _write(self, data): ...\n def _get_size(self): ...\n def _set_mode(self, mode='r', bufsize=-1): ...\n def _write_all(self, data): ...\n def _record_newline(self, newline): ...\n\n self.newlines = None\n self._flags = 0\n self._bufsize = self._DEFAULT_BUFSIZE\n self._wbuffer = BytesIO()\n self._rbuffer = bytes()\n self._at_trailing_cr = False\n self._closed = False\n self._pos = self._realpos = 0\n self._size = 0\n\n _DEFAULT_BUFSIZE = 8192\n SEEK_SET = 0\n SEEK_CUR = 1\n SEEK_END = 2\n FLAG_READ = 1\n FLAG_WRITE = 2\n FLAG_APPEND = 4\n FLAG_BINARY = 16\n FLAG_BUFFERED = 32\n FLAG_LINE_BUFFERED = 64\n FLAG_UNIVERSAL_NEWLINE = 128\n", "repository": "87170360/pythonConfig", "test_name": "test_2_readline", "smells": [1, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000275.py"} {"focal_file": "paramiko-1.16.0/paramiko/file.py", "focal_class": null, "focal_method": "write", "tests": "import unittest\n\nclass Test_write(unittest.TestCase):\n def test_4_write(self):\n \"\"\"\n verify that write buffering is on.\n \"\"\"\n f = LoopbackFile('r+', 1)\n f.write(b'Complete line.\\nIncomplete line.')\n self.assertEqual(f.readline(), 'Complete line.\\n')\n self.assertEqual(f.readline(), '')\n f.write('..\\n')\n self.assertEqual(f.readline(), 'Incomplete line...\\n')\n f.close()\n", "method_code": " def write(self, data):\n \"\"\"\n Write data to the file. If write buffering is on (``bufsize`` was\n specified and non-zero), some or all of the data may not actually be\n written yet. (Use `flush` or `close` to force buffered data to be\n written out.)\n \n :param str data: data to write\n \"\"\"\n data = b(data)\n if self._closed:\n raise IOError('File is closed')\n if not self._flags & self.FLAG_WRITE:\n raise IOError('File not open for writing')\n if not self._flags & self.FLAG_BUFFERED:\n self._write_all(data)\n return\n self._wbuffer.write(data)\n if self._flags & self.FLAG_LINE_BUFFERED:\n last_newline_pos = data.rfind(linefeed_byte)\n if last_newline_pos >= 0:\n wbuf = self._wbuffer.getvalue()\n last_newline_pos += len(wbuf) - len(data)\n self._write_all(wbuf[:last_newline_pos + 1])\n self._wbuffer = BytesIO()\n self._wbuffer.write(wbuf[last_newline_pos + 1:])\n return\n if self._wbuffer.tell() >= self._bufsize:\n self.flush()\n return\n ", "context": "class BufferedFile(ClosingContextManager):\n def write(self, data): ...\n def __init__(self): ...\n def __del__(self): ...\n def __iter__(self): ...\n def close(self): ...\n def flush(self): ...\n def read(self, size=None): ...\n def readline(self, size=None): ...\n def readlines(self, sizehint=None): ...\n def seek(self, offset, whence=0): ...\n def tell(self): ...\n def writelines(self, sequence): ...\n def xreadlines(self): ...\n def closed(self): ...\n def _read(self, size): ...\n def _write(self, data): ...\n def _get_size(self): ...\n def _set_mode(self, mode='r', bufsize=-1): ...\n def _write_all(self, data): ...\n def _record_newline(self, newline): ...\n\n self.newlines = None\n self._flags = 0\n self._bufsize = self._DEFAULT_BUFSIZE\n self._wbuffer = BytesIO()\n self._rbuffer = bytes()\n self._at_trailing_cr = False\n self._closed = False\n self._pos = self._realpos = 0\n self._size = 0\n\n _DEFAULT_BUFSIZE = 8192\n SEEK_SET = 0\n SEEK_CUR = 1\n SEEK_END = 2\n FLAG_READ = 1\n FLAG_WRITE = 2\n FLAG_APPEND = 4\n FLAG_BINARY = 16\n FLAG_BUFFERED = 32\n FLAG_LINE_BUFFERED = 64\n FLAG_UNIVERSAL_NEWLINE = 128\n", "repository": "87170360/pythonConfig", "test_name": "test_4_write", "smells": [1, 0, 0, 0, 1, 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_000276.py"} {"focal_file": "paramiko-1.16.0/paramiko/file.py", "focal_class": null, "focal_method": "flush", "tests": "import unittest\n\nclass Test_flush(unittest.TestCase):\n def test_5_flush(self):\n \"\"\"\n verify that flush will force a write.\n \"\"\"\n f = LoopbackFile('r+', 512)\n f.write('Not\\nquite\\n512 bytes.\\n')\n self.assertEqual(f.read(1), b'')\n f.flush()\n self.assertEqual(f.read(5), b'Not\\nq')\n self.assertEqual(f.read(10), b'uite\\n512 b')\n self.assertEqual(f.read(9), b'ytes.\\n')\n self.assertEqual(f.read(3), b'')\n f.close()\n", "method_code": " def flush(self):\n \"\"\"\n Write out any data in the write buffer. This may do nothing if write\n buffering is not turned on.\n \"\"\"\n self._write_all(self._wbuffer.getvalue())\n self._wbuffer = BytesIO()\n return\n ", "context": "class BufferedFile(ClosingContextManager):\n def flush(self): ...\n def __init__(self): ...\n def __del__(self): ...\n def __iter__(self): ...\n def close(self): ...\n def read(self, size=None): ...\n def readline(self, size=None): ...\n def readlines(self, sizehint=None): ...\n def seek(self, offset, whence=0): ...\n def tell(self): ...\n def write(self, data): ...\n def writelines(self, sequence): ...\n def xreadlines(self): ...\n def closed(self): ...\n def _read(self, size): ...\n def _write(self, data): ...\n def _get_size(self): ...\n def _set_mode(self, mode='r', bufsize=-1): ...\n def _write_all(self, data): ...\n def _record_newline(self, newline): ...\n\n self.newlines = None\n self._flags = 0\n self._bufsize = self._DEFAULT_BUFSIZE\n self._wbuffer = BytesIO()\n self._rbuffer = bytes()\n self._at_trailing_cr = False\n self._closed = False\n self._pos = self._realpos = 0\n self._size = 0\n\n _DEFAULT_BUFSIZE = 8192\n SEEK_SET = 0\n SEEK_CUR = 1\n SEEK_END = 2\n FLAG_READ = 1\n FLAG_WRITE = 2\n FLAG_APPEND = 4\n FLAG_BINARY = 16\n FLAG_BUFFERED = 32\n FLAG_LINE_BUFFERED = 64\n FLAG_UNIVERSAL_NEWLINE = 128\n", "repository": "87170360/pythonConfig", "test_name": "test_5_flush", "smells": [1, 0, 0, 0, 1, 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_000277.py"} {"focal_file": "paramiko-1.16.0/paramiko/message.py", "focal_class": "Message", "focal_method": "add", "tests": "import unittest\n\nclass Test_Message_add(unittest.TestCase):\n def test_3_add(self):\n msg = Message()\n msg.add(5)\n msg.add(73588229205)\n msg.add(4427218577690292387840)\n msg.add(True)\n msg.add('cat')\n msg.add(['a', 'b'])\n self.assertEqual(msg.asbytes(), self.__d)\n", "method_code": " def add(self, *seq):\n \"\"\"\n Add a sequence of items to the stream. The values are encoded based\n on their type: str, int, bool, list, or long.\n \n .. warning::\n Longs are encoded non-deterministically. Don't use this method.\n \n :param seq: the sequence of items\n \"\"\"\n for item in seq:\n self._add(item)\n ", "context": "class Message(object):\n def add(self, *seq): ...\n def __init__(self, content=None): ...\n def __str__(self): ...\n def __repr__(self): ...\n def asbytes(self): ...\n def rewind(self): ...\n def get_remainder(self): ...\n def get_so_far(self): ...\n def get_bytes(self, n): ...\n def get_byte(self): ...\n def get_boolean(self): ...\n def get_adaptive_int(self): ...\n def get_int(self): ...\n def get_int64(self): ...\n def get_mpint(self): ...\n def get_string(self): ...\n def get_text(self): ...\n def get_binary(self): ...\n def get_list(self): ...\n def add_bytes(self, b): ...\n def add_byte(self, b): ...\n def add_boolean(self, b): ...\n def add_int(self, n): ...\n def add_adaptive_int(self, n): ...\n def add_int64(self, n): ...\n def add_mpint(self, z): ...\n def add_string(self, s): ...\n def add_list(self, l): ...\n def _add(self, i): ...\n\n big_int = long(4278190080)\n", "repository": "87170360/pythonConfig", "test_name": "test_3_add", "smells": [1, 0, 0, 0, 1, 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_000278.py"} {"focal_file": "paramiko-1.16.0/paramiko/util.py", "focal_class": null, "focal_method": "parse_ssh_config", "tests": "import unittest\n\nclass Test_parse_ssh_config(unittest.TestCase):\n def test_2_parse_config(self):\n global test_config_file\n f = StringIO(test_config_file)\n config = paramiko.util.parse_ssh_config(f)\n self.assertEqual(config._config, [{'host': ['*'], 'config': {}}, {'host': ['*'], 'config': {'identityfile': ['~/.ssh/id_rsa'], 'user': 'robey'}}, {'host': ['*.example.com'], 'config': {'user': 'bjork', 'port': '3333'}}, {'host': ['*'], 'config': {'crazy': 'something dumb '}}, {'host': ['spoo.example.com'], 'config': {'crazy': 'something else'}}])\n", "method_code": "def parse_ssh_config(file_obj):\n \"\"\"\n Provided only as a backward-compatible wrapper around `.SSHConfig`.\n \"\"\"\n config = SSHConfig()\n config.parse(file_obj)\n return config", "context": "def parse_ssh_config(file_obj): ...\ndef inflate_long(s, always_positive=False): ...\ndef deflate_long(n, add_sign_padding=True): ...\ndef format_binary(data, prefix=''): ...\ndef format_binary_line(data): ...\ndef safe_string(s): ...\ndef bit_length(n): ...\ndef tb_strings(): ...\ndef generate_key_bytes(hash_alg, salt, key, nbytes): ...\ndef load_host_keys(filename): ...\ndef parse_ssh_config(file_obj): ...\ndef lookup_ssh_host_config(hostname, config): ...\ndef mod_inverse(x, m): ...\ndef get_thread_id(): ...\ndef log_to_file(filename, level=DEBUG): ...\ndef get_logger(name): ...\ndef retry_on_signal(function): ...\ndef constant_time_bytes_eq(a, b): ...\ndef clamp_value(minimum, val, maximum): ...\n", "repository": "87170360/pythonConfig", "test_name": "test_2_parse_config", "smells": [1, 0, 0, 0, 1, 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_000279.py"} {"focal_file": "paramiko-1.16.0/paramiko/util.py", "focal_class": null, "focal_method": "lookup_ssh_host_config", "tests": "import unittest\n\nclass Test_lookup_ssh_host_config(unittest.TestCase):\n def test_3_host_config(self):\n global test_config_file\n f = StringIO(test_config_file)\n config = paramiko.util.parse_ssh_config(f)\n for host, values in {'irc.danger.com': {'crazy': 'something dumb ', 'hostname': 'irc.danger.com', 'user': 'robey'}, 'irc.example.com': {'crazy': 'something dumb ', 'hostname': 'irc.example.com', 'user': 'robey', 'port': '3333'}, 'spoo.example.com': {'crazy': 'something dumb ', 'hostname': 'spoo.example.com', 'user': 'robey', 'port': '3333'}}.items():\n values = dict(values, hostname=host, identityfile=[os.path.expanduser('~/.ssh/id_rsa')])\n self.assertEqual(paramiko.util.lookup_ssh_host_config(host, config), values)\n", "method_code": "def lookup_ssh_host_config(hostname, config):\n \"\"\"\n Provided only as a backward-compatible wrapper around `.SSHConfig`.\n \"\"\"\n return config.lookup(hostname)", "context": "def lookup_ssh_host_config(hostname, config): ...\ndef inflate_long(s, always_positive=False): ...\ndef deflate_long(n, add_sign_padding=True): ...\ndef format_binary(data, prefix=''): ...\ndef format_binary_line(data): ...\ndef safe_string(s): ...\ndef bit_length(n): ...\ndef tb_strings(): ...\ndef generate_key_bytes(hash_alg, salt, key, nbytes): ...\ndef load_host_keys(filename): ...\ndef parse_ssh_config(file_obj): ...\ndef lookup_ssh_host_config(hostname, config): ...\ndef mod_inverse(x, m): ...\ndef get_thread_id(): ...\ndef log_to_file(filename, level=DEBUG): ...\ndef get_logger(name): ...\ndef retry_on_signal(function): ...\ndef constant_time_bytes_eq(a, b): ...\ndef clamp_value(minimum, val, maximum): ...\n", "repository": "87170360/pythonConfig", "test_name": "test_3_host_config", "smells": [1, 0, 0, 0, 1, 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_000280.py"} {"focal_file": "paramiko-1.16.0/paramiko/util.py", "focal_class": null, "focal_method": "generate_key_bytes", "tests": "import unittest\n\nclass Test_generate_key_bytes(unittest.TestCase):\n def test_4_generate_key_bytes(self):\n x = paramiko.util.generate_key_bytes(sha1, b'ABCDEFGH', 'This is my secret passphrase.', 64)\n hex = ''.join(['%02x' % byte_ord(c) for c in x])\n self.assertEqual(hex, '9110e2f6793b69363e58173e9436b13a5a4b339005741d5c680e505f57d871347b4239f14fb5c46e857d5e100424873ba849ac699cea98d729e57b3e84378e8b')\n", "method_code": "def generate_key_bytes(hash_alg, salt, key, nbytes):\n \"\"\"\n Given a password, passphrase, or other human-source key, scramble it\n through a secure hash into some keyworthy bytes. This specific algorithm\n is used for encrypting/decrypting private key files.\n\n :param function hash_alg: A function which creates a new hash object, such\n as ``hashlib.sha256``.\n :param salt: data to salt the hash with.\n :type salt: byte string\n :param str key: human-entered password or passphrase.\n :param int nbytes: number of bytes to generate.\n :return: Key data `str`\n \"\"\"\n keydata = bytes()\n digest = bytes()\n if len(salt) > 8:\n salt = salt[:8]\n while nbytes > 0:\n hash_obj = hash_alg()\n if len(digest) > 0:\n hash_obj.update(digest)\n hash_obj.update(b(key))\n hash_obj.update(salt)\n digest = hash_obj.digest()\n size = min(nbytes, len(digest))\n keydata += digest[:size]\n nbytes -= size\n return keydata", "context": "def generate_key_bytes(hash_alg, salt, key, nbytes): ...\ndef inflate_long(s, always_positive=False): ...\ndef deflate_long(n, add_sign_padding=True): ...\ndef format_binary(data, prefix=''): ...\ndef format_binary_line(data): ...\ndef safe_string(s): ...\ndef bit_length(n): ...\ndef tb_strings(): ...\ndef generate_key_bytes(hash_alg, salt, key, nbytes): ...\ndef load_host_keys(filename): ...\ndef parse_ssh_config(file_obj): ...\ndef lookup_ssh_host_config(hostname, config): ...\ndef mod_inverse(x, m): ...\ndef get_thread_id(): ...\ndef log_to_file(filename, level=DEBUG): ...\ndef get_logger(name): ...\ndef retry_on_signal(function): ...\ndef constant_time_bytes_eq(a, b): ...\ndef clamp_value(minimum, val, maximum): ...\n", "repository": "87170360/pythonConfig", "test_name": "test_4_generate_key_bytes", "smells": [1, 0, 0, 0, 1, 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_000281.py"} {"focal_file": "paramiko-1.16.0/paramiko/util.py", "focal_class": null, "focal_method": "clamp_value", "tests": "import unittest\n\nclass Test_clamp_value(unittest.TestCase):\n def test_clamp_value(self):\n self.assertEqual(32768, paramiko.util.clamp_value(32767, 32768, 32769))\n self.assertEqual(32767, paramiko.util.clamp_value(32767, 32765, 32769))\n self.assertEqual(32769, paramiko.util.clamp_value(32767, 32770, 32769))\n", "method_code": "def clamp_value(minimum, val, maximum):\n return max(minimum, min(val, maximum))", "context": "def clamp_value(minimum, val, maximum): ...\ndef inflate_long(s, always_positive=False): ...\ndef deflate_long(n, add_sign_padding=True): ...\ndef format_binary(data, prefix=''): ...\ndef format_binary_line(data): ...\ndef safe_string(s): ...\ndef bit_length(n): ...\ndef tb_strings(): ...\ndef generate_key_bytes(hash_alg, salt, key, nbytes): ...\ndef load_host_keys(filename): ...\ndef parse_ssh_config(file_obj): ...\ndef lookup_ssh_host_config(hostname, config): ...\ndef mod_inverse(x, m): ...\ndef get_thread_id(): ...\ndef log_to_file(filename, level=DEBUG): ...\ndef get_logger(name): ...\ndef retry_on_signal(function): ...\ndef constant_time_bytes_eq(a, b): ...\ndef clamp_value(minimum, val, maximum): ...\n", "repository": "87170360/pythonConfig", "test_name": "test_clamp_value", "smells": [1, 0, 0, 0, 1, 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_000282.py"} {"focal_file": "paramiko-1.16.0/paramiko/util.py", "focal_class": null, "focal_method": "safe_string", "tests": "import unittest\n\nclass Test_safe_string(unittest.TestCase):\n def test_safe_string(self):\n vanilla = b('vanilla')\n has_bytes = b('has \\x07\\x03 bytes')\n safe_vanilla = safe_string(vanilla)\n safe_has_bytes = safe_string(has_bytes)\n expected_bytes = b('has %07%03 bytes')\n err = '{0!r} != {1!r}'\n assert safe_vanilla == vanilla, err.format(safe_vanilla, vanilla)\n assert safe_has_bytes == expected_bytes, err.format(safe_has_bytes, expected_bytes)\n", "method_code": "def safe_string(s):\n out = b('')\n for c in s:\n i = byte_ord(c)\n if 32 <= i <= 127:\n out += byte_chr(i)\n else:\n out += b('%%%02X' % i)\n return out", "context": "def safe_string(s): ...\ndef inflate_long(s, always_positive=False): ...\ndef deflate_long(n, add_sign_padding=True): ...\ndef format_binary(data, prefix=''): ...\ndef format_binary_line(data): ...\ndef safe_string(s): ...\ndef bit_length(n): ...\ndef tb_strings(): ...\ndef generate_key_bytes(hash_alg, salt, key, nbytes): ...\ndef load_host_keys(filename): ...\ndef parse_ssh_config(file_obj): ...\ndef lookup_ssh_host_config(hostname, config): ...\ndef mod_inverse(x, m): ...\ndef get_thread_id(): ...\ndef log_to_file(filename, level=DEBUG): ...\ndef get_logger(name): ...\ndef retry_on_signal(function): ...\ndef constant_time_bytes_eq(a, b): ...\ndef clamp_value(minimum, val, maximum): ...\n", "repository": "87170360/pythonConfig", "test_name": "test_safe_string", "smells": [1, 0, 0, 0, 1, 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_000283.py"} {"focal_file": "utilities/prospector.py", "focal_class": "Prospector", "focal_method": "s3_backup_key", "tests": "import unittest\n\nclass Test_Prospector_s3_backup_key(unittest.TestCase):\n def test_s3_backup_key(self):\n p = Prospector(**self.cfg)\n dt = datetime(2020, 3, 4, 12, 35, 40)\n key = p.s3_backup_key(dt)\n key.should.equal('my_server/backups/my_world-20200304T123540.zip')\n key_dt = p.backup_time_from_key(key)\n key_dt.should.equal(dt)\n", "method_code": " def s3_backup_key(self, date):\n \"\"\"\n Given a `date` datetime instance, returns an s3 key for that backup,\n including the .zip suffix.\n \"\"\"\n return '{}-{}.zip'.format(self.s3_backup_prefix, date.strftime(S3_BACKUP_DATE_FMT))\n ", "context": "class Prospector(object):\n def s3_backup_key(self, date): ...\n def __init__(self, server_name, world_name, server_root_dir, s3_bucket): ...\n def s3_backup_prefix(self): ...\n def server_path(self): ...\n def world_path(self): ...\n def backup_time_from_key(backup_key): ...\n def tag_s3_object(self, key, **kwargs): ...\n def fetch_most_recent_backup(self): ...\n def upload_backup(self, zipfile): ...\n def push_current_backup(self): ...\n def create_current_backup(self): ...\n def get_most_recent_backup_key(self): ...\n\n self.server_name = server_name\n self.world_name = world_name\n self.server_root_dir = server_root_dir\n self.s3_bucket = s3_bucket\n self.client = boto3.client('s3')\n", "repository": "gerhalt/mining-camp", "test_name": "test_s3_backup_key", "smells": [0, 1, 0, 0, 0, 0, 1, 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, 1], "pynose_source_file": "test_000284.py"} {"focal_file": "utilities/prospector.py", "focal_class": "Prospector", "focal_method": "push_current_backup", "tests": "import unittest\n\nclass Test_Prospector_push_current_backup(unittest.TestCase):\n @freeze_time('2020-03-04 02:34:56')\n def test_push_current_backup(self):\n p = Prospector(**self.cfg)\n response = self.s3_client.list_objects_v2(Bucket=self.cfg['s3_bucket'])\n response['KeyCount'].should.equal(0)\n p.push_current_backup()\n response = self.s3_client.list_objects_v2(Bucket=self.cfg['s3_bucket'])\n response['KeyCount'].should.equal(1)\n backup_meta = response['Contents'][0]\n backup_time = p.backup_time_from_key(backup_meta['Key'])\n backup_time.should.equal(datetime(2020, 3, 4, 2, 34, 56))\n", "method_code": " def push_current_backup(self):\n \"\"\"\n Builds a backup archive from the server's active world and pushes it to\n S3. The server must not be writing to disk while this is executing.\n \"\"\"\n backup_path = self.create_current_backup()\n if not backup_path:\n logger.error('Unable to create backup')\n else:\n self.upload_backup(backup_path)\n shutil.rmtree(os.path.dirname(backup_path))\n ", "context": "class Prospector(object):\n def push_current_backup(self): ...\n def __init__(self, server_name, world_name, server_root_dir, s3_bucket): ...\n def s3_backup_prefix(self): ...\n def server_path(self): ...\n def world_path(self): ...\n def backup_time_from_key(backup_key): ...\n def tag_s3_object(self, key, **kwargs): ...\n def s3_backup_key(self, date): ...\n def fetch_most_recent_backup(self): ...\n def upload_backup(self, zipfile): ...\n def create_current_backup(self): ...\n def get_most_recent_backup_key(self): ...\n\n self.server_name = server_name\n self.world_name = world_name\n self.server_root_dir = server_root_dir\n self.s3_bucket = s3_bucket\n self.client = boto3.client('s3')\n", "repository": "gerhalt/mining-camp", "test_name": "", "smells": [0, 1, 0, 0, 0, 0, 1, 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, 1], "pynose_source_file": "test_000285.py"} {"focal_file": "utilities/prospector.py", "focal_class": "Prospector", "focal_method": "upload_backup", "tests": "import unittest\n\nclass Test_Prospector_upload_backup(unittest.TestCase):\n def test_upload_backup(self):\n p = Prospector(**self.cfg)\n mock_archive = os.path.join(self.temp_dir, 'backup.zip')\n with open(mock_archive, 'w') as f:\n f.write(os.urandom(100))\n time = datetime(2020, 5, 23, 11, 45)\n backup_times = []\n for i in range(0, 5):\n backup_times.append(time)\n with freeze_time(time):\n p.upload_backup(mock_archive)\n time += timedelta(hours=13)\n response = self.s3_client.list_objects_v2(Bucket=self.cfg['s3_bucket'])\n response['KeyCount'].should.equal(len(backup_times))\n for item in response['Contents']:\n response = self.s3_client.get_object_tagging(Bucket=self.cfg['s3_bucket'], Key=item['Key'])\n tags = {t['Key']: t['Value'] for t in response['TagSet']}\n bt = p.backup_time_from_key(item['Key'])\n if bt in backup_times[:-1]:\n tags.should.equal({'backup': 'old'})\n elif bt == backup_times[-1]:\n tags.should.equal({'backup': 'new'})\n else:\n raise Exception(\"Unexpected backup key '{}'\".format(item['Key']))\n", "method_code": " def upload_backup(self, zipfile):\n \"\"\"\n Uploads `zipfile` to S3, stamping it using the current time. The\n previous most-recent backup in S3, if one exists, is re-tagged as old.\n \"\"\"\n latest_path = zipfile\n latest_stamp = datetime.utcnow()\n latest_s3_key = self.get_most_recent_backup_key()\n latest_s3_stamp = None\n if latest_s3_key:\n result = S3_BACKUP_RE.match(os.path.basename(latest_s3_key))\n latest_s3_stamp = datetime.strptime(result.group(1), S3_BACKUP_DATE_FMT)\n new_s3_key = self.s3_backup_key(latest_stamp)\n logger.info('Uploading backup file {} to s3://{}/{}'.format(latest_path, self.s3_bucket, new_s3_key))\n self.client.upload_file(latest_path, self.s3_bucket, new_s3_key)\n self.tag_s3_object(new_s3_key, backup='new')\n if latest_s3_stamp:\n self.tag_s3_object(latest_s3_key, backup='old')\n ", "context": "class Prospector(object):\n def upload_backup(self, zipfile): ...\n def __init__(self, server_name, world_name, server_root_dir, s3_bucket): ...\n def s3_backup_prefix(self): ...\n def server_path(self): ...\n def world_path(self): ...\n def backup_time_from_key(backup_key): ...\n def tag_s3_object(self, key, **kwargs): ...\n def s3_backup_key(self, date): ...\n def fetch_most_recent_backup(self): ...\n def push_current_backup(self): ...\n def create_current_backup(self): ...\n def get_most_recent_backup_key(self): ...\n\n self.server_name = server_name\n self.world_name = world_name\n self.server_root_dir = server_root_dir\n self.s3_bucket = s3_bucket\n self.client = boto3.client('s3')\n", "repository": "gerhalt/mining-camp", "test_name": "test_upload_backup", "smells": [0, 1, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000286.py"} {"focal_file": "utilities/prospector.py", "focal_class": "Prospector", "focal_method": "get_most_recent_backup_key", "tests": "import unittest\n\nclass Test_Prospector_get_most_recent_backup_key(unittest.TestCase):\n def test_get_most_recent_backup_key(self):\n p = Prospector(**self.cfg)\n mock_archive = os.path.join(self.temp_dir, 'backup.zip')\n with open(mock_archive, 'w') as f:\n f.write(os.urandom(100))\n time = datetime(2020, 5, 23, 11, 45)\n backup_times = []\n for i in range(0, 5):\n backup_times.append(time)\n with freeze_time(time):\n p.upload_backup(mock_archive)\n time += timedelta(hours=13)\n backup_key = p.get_most_recent_backup_key()\n backup_key.should.equal('my_server/backups/my_world-20200525T154500.zip')\n", "method_code": " def get_most_recent_backup_key(self):\n \"\"\"\n Returns the key of the most recent backup in S3, or `None` if no\n backups are found.\n \"\"\"\n obj_list = self.client.list_objects(Bucket=self.s3_bucket, Prefix=self.s3_backup_prefix)\n backups = [o['Key'] for o in obj_list.get('Contents', [])]\n backups.sort(reverse=True)\n backup_key = None\n for b in backups:\n if S3_BACKUP_RE.match(os.path.basename(b)):\n backup_key = b\n break\n return backup_key\n ", "context": "class Prospector(object):\n def get_most_recent_backup_key(self): ...\n def __init__(self, server_name, world_name, server_root_dir, s3_bucket): ...\n def s3_backup_prefix(self): ...\n def server_path(self): ...\n def world_path(self): ...\n def backup_time_from_key(backup_key): ...\n def tag_s3_object(self, key, **kwargs): ...\n def s3_backup_key(self, date): ...\n def fetch_most_recent_backup(self): ...\n def upload_backup(self, zipfile): ...\n def push_current_backup(self): ...\n def create_current_backup(self): ...\n\n self.server_name = server_name\n self.world_name = world_name\n self.server_root_dir = server_root_dir\n self.s3_bucket = s3_bucket\n self.client = boto3.client('s3')\n", "repository": "gerhalt/mining-camp", "test_name": "test_get_most_recent_backup_key", "smells": [0, 1, 0, 0, 0, 0, 1, 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, 1], "pynose_source_file": "test_000287.py"} {"focal_file": "utilities/prospector.py", "focal_class": "Prospector", "focal_method": "fetch_most_recent_backup", "tests": "import unittest\n\nclass Test_Prospector_fetch_most_recent_backup(unittest.TestCase):\n def test_fetch_most_recent_backup(self):\n p = Prospector(**self.cfg)\n time = datetime(2020, 5, 23, 11, 45)\n backup_times = []\n for i in range(0, 5):\n backup_times.append(time)\n shutil.rmtree(self.server_path)\n os.makedirs(self.world_path)\n self.populate_mock_server()\n with freeze_time(time):\n p.push_current_backup()\n time += timedelta(days=27)\n current_world_checksum = self.checksum_walk(self.world_path)\n shutil.rmtree(self.world_path)\n p.fetch_most_recent_backup()\n backup_world_checksum = self.checksum_walk(self.world_path)\n len(current_world_checksum).should.equal(21)\n current_world_checksum.should.equal(backup_world_checksum)\n", "method_code": " def fetch_most_recent_backup(self):\n \"\"\"\n Fetches the most recent backup in S3 and returns the local temporary\n file path.\n \"\"\"\n key = self.get_most_recent_backup_key()\n if key:\n tmp_path = os.path.join('/tmp', os.path.basename(key))\n logger.info('Downloading backup from s3://{}/{} to {}'.format(self.s3_bucket, key, tmp_path))\n self.client.download_file(self.s3_bucket, key, tmp_path)\n try:\n with ZipFile(tmp_path, 'r') as z:\n z.extractall(os.path.join(self.server_root_dir, self.server_name))\n except BadZipfile:\n logger.error('Zipfile is bad!')\n os.remove(tmp_path)\n else:\n logger.warning('No backups found in S3')\n ", "context": "class Prospector(object):\n def fetch_most_recent_backup(self): ...\n def __init__(self, server_name, world_name, server_root_dir, s3_bucket): ...\n def s3_backup_prefix(self): ...\n def server_path(self): ...\n def world_path(self): ...\n def backup_time_from_key(backup_key): ...\n def tag_s3_object(self, key, **kwargs): ...\n def s3_backup_key(self, date): ...\n def upload_backup(self, zipfile): ...\n def push_current_backup(self): ...\n def create_current_backup(self): ...\n def get_most_recent_backup_key(self): ...\n\n self.server_name = server_name\n self.world_name = world_name\n self.server_root_dir = server_root_dir\n self.s3_bucket = s3_bucket\n self.client = boto3.client('s3')\n", "repository": "gerhalt/mining-camp", "test_name": "test_fetch_most_recent_backup", "smells": [0, 1, 0, 0, 0, 0, 1, 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, 1], "pynose_source_file": "test_000288.py"} {"focal_file": "tests/test_utils.py", "focal_class": null, "focal_method": "_test_orientations", "tests": "import unittest\n\nclass Test_test_orientations(unittest.TestCase):\n def test_orientations(self):\n \"\"\"it scales images regardless of orientation\"\"\"\n self._test_orientations(1600, 900, 2400 * 1350, 2400, 1350)\n", "method_code": " def _test_orientations(self, w, h, m, nw, nh):\n self.assertEqual(beautyscale(w, h, m), (nw, nh))\n self.assertEqual(beautyscale(h, w, m), (nh, nw))\n ", "context": "class Test_BeautyScale(unittest.TestCase):\n def _test_orientations(self, w, h, m, nw, nh): ...\n def test_16_to_9(self): ...\n def test_prime(self): ...\n def test_small(self): ...\n def test_equal_size(self): ...\n def test_scale_up(self): ...\n def test_orientations(self): ...\n", "repository": "tbleicher/wxfalsecolor", "test_name": "test_orientations", "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, 1], "pynose_source_file": "test_000289.py"} {"focal_file": "src/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": "cintiamh/PythonCrashCourse", "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_000290.py"} {"focal_file": "src/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 properly.\"\"\"\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 individual responses are stored properly.\"\"\"\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 \"\"\"Store a single response to the survey.\"\"\"\n self.responses.append(new_response)\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": "cintiamh/PythonCrashCourse", "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_000291.py"} {"focal_file": "lire_entree.py", "focal_class": null, "focal_method": "decomposition_faces", "tests": "import unittest\n\nclass Test_decomposition_faces(unittest.TestCase):\n def testDecomposition(self):\n \"\"\"decomposition_faces() doit faire son job\"\"\"\n entree = 'GRBYWYWWORRRBBGWBYOBYWROBBRWOGOGOWGYRGWOROGOGBWBYYGRYY'\n faces = [[3, 2, 1, 5, 0, 5, 0, 0, 4], [2, 2, 2, 0, 2, 4, 0, 3, 5], [1, 1, 3, 1, 1, 2, 2, 3, 0], [0, 1, 5, 0, 4, 3, 4, 2, 4], [4, 1, 5, 4, 3, 4, 3, 4, 3], [1, 0, 1, 5, 5, 3, 2, 5, 5]]\n result = decomposition_faces(entree)\n self.assertEqual(result, faces)\n", "method_code": "def decomposition_faces(s):\n \"\"\"\n decomposition_faces\n\n Décompose la chaîne représentant les 54 facettes en 6 faces\n\n :Args:\n s {String} chaîne de 54 facettes\n\n :Returns:\n {List|None} Liste de 6 liste de 9 éléments (les 6 faces)\n couleurs codées en entiers\n \"\"\"\n if not type(s) == str:\n raise TypeError(str(s) + \" n'est pas une chaîne\")\n elif not len(s) == 54:\n raise ValueError('La chaîne ne fait pas 54 caractères')\n else:\n faces = [[] for i in range(6)]\n for i in range(len(s)):\n case = colorToCode(s[i])\n if i < 9:\n faces[0].append(case)\n elif i > 44:\n faces[5].append(case)\n else:\n i_ = (i - 9) % 12\n if i_ < 3:\n faces[1].append(case)\n elif i_ < 6:\n faces[2].append(case)\n elif i_ < 9:\n faces[3].append(case)\n else:\n faces[4].append(case)\n return faces", "context": "def decomposition_faces(s): ...\ndef decomposition_faces(s): ...\ndef check_faces(faces): ...\ndef lecture_cube(str_cube): ...\n", "repository": "Togodumnus/Ragnulf", "test_name": "testDecomposition", "smells": [1, 1, 0, 0, 1, 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_000292.py"} {"focal_file": "lire_entree.py", "focal_class": null, "focal_method": "lecture_cube", "tests": "import unittest\n\nclass Test_lecture_cube(unittest.TestCase):\n def testLecture(self):\n \"\"\"\n lecture_cube doit fonctionner\n \"\"\"\n entree = 'OGRBWYBGBGYYOYOWOWGRYOOOBGBRRYRBWWWRBWYGROWGRYBRGYWBOG'\n error, cube = lecture_cube(entree)\n self.assertFalse(error)\n self.assertEqual(cube.to_line(colors=False), 'YBRGYWBOGRWWRGWORGYWBOOOWBRYRRBGBYYGYRGWOWOYOOGRBWYBGB')\n", "method_code": "def lecture_cube(str_cube):\n \"\"\"\n lecture_cube\n\n Fonction qui permet de lire l'entrée de l'utilisateur.\n Prend une chaîne de 54 caractères et renvoie un objet cube initialisé,\n avec les nombres se rapportant aux couleurs.\n\n :Args:\n str {String} chaîne de 54 facettes\n\n :Returns:\n {Boolean|String}, {Cube} (error, cube)\n Un objet cube initialisé avec les numéros\n correspondant à la chaîne de caractères entrée\n en paramètre\n \"\"\"\n c = Cube()\n try:\n faces = decomposition_faces(str_cube)\n except ValueError as e:\n return (str(e), None)\n error = check_faces(faces)\n if error:\n return (error, None)\n insertions = [('FU', [faces[2][1], faces[0][7]]), ('FRU', [faces[2][2], faces[3][0], faces[0][8]]), ('FR', [faces[2][5], faces[3][3]]), ('FRD', [faces[2][8], faces[3][6], faces[5][2]]), ('FD', [faces[2][7], faces[5][1]]), ('LFD', [faces[1][8], faces[2][6], faces[5][0]]), ('FL', [faces[2][3], faces[1][5]]), ('LFU', [faces[1][2], faces[2][0], faces[0][6]]), ('LU', [faces[1][1], faces[0][3]]), ('LD', [faces[1][7], faces[5][3]]), ('BU', [faces[4][1], faces[0][1]]), ('RBU', [faces[3][2], faces[4][0], faces[0][2]]), ('BR', [faces[4][3], faces[3][5]]), ('RBD', [faces[3][8], faces[4][6], faces[5][8]]), ('BD', [faces[4][7], faces[5][7]]), ('BLD', [faces[4][8], faces[1][6], faces[5][6]]), ('BL', [faces[4][5], faces[1][3]]), ('BLU', [faces[4][2], faces[1][0], faces[0][0]]), ('RD', [faces[3][7], faces[5][5]]), ('RU', [faces[3][1], faces[0][5]])]\n i = 0\n l = len(insertions)\n while i < l:\n try:\n c.edit_cube(insertions[i][0], insertions[i][1])\n except ValueError as e:\n return ('Petits cubes invalides', None)\n i += 1\n couleurs_faces = [face[4] for face in faces]\n v = (couleurs_faces.index(0), couleurs_faces.index(1))\n if v[0] == 0:\n c.rot_UF()\n c.rot_UF()\n if not v[1] == 4:\n for _ in range(v[1]):\n c.rot_FR()\n elif v[0] == 5:\n if v[1] == 1:\n c.rot_FR()\n for j in [3, 4]:\n if v[1] == j or v[1] == j:\n for x in range(6 - j):\n c.rot_FR()\n else:\n if v[0] == 1:\n c.rot_FR()\n else:\n for j in [3, 4]:\n if v[0] == j or v[0] == j:\n for x in range(6 - j):\n c.rot_FR()\n c.rot_UF()\n if v[1] == 5:\n c.rot_FR()\n c.rot_FR()\n elif v[1] == v[0] + 1 or (v[0], v[1]) == (4, 1):\n for x in range(3):\n c.rot_FR()\n elif v[1] == v[0] - 1 or (v[0], v[1]) == (1, 4):\n c.rot_FR()\n return (False, c)", "context": "def lecture_cube(str_cube): ...\ndef decomposition_faces(s): ...\ndef check_faces(faces): ...\ndef lecture_cube(str_cube): ...\n", "repository": "Togodumnus/Ragnulf", "test_name": "testLecture", "smells": [1, 1, 0, 0, 1, 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_000293.py"} {"focal_file": "utils.py", "focal_class": null, "focal_method": "codeToColor", "tests": "import unittest\n\nclass Test_codeToColor(unittest.TestCase):\n def testCodeToColorTypes(self):\n \"\"\"codeToColor() demande un int entre 0 et 6 en param\"\"\"\n with self.assertRaises(TypeError):\n codeToColor(1.0)\n with self.assertRaises(TypeError):\n codeToColor('a')\n with self.assertRaises(TypeError):\n codeToColor(None)\n with self.assertRaises(TypeError):\n codeToColor()\n with self.assertRaises(ValueError):\n colorToCode(6)\n with self.assertRaises(ValueError):\n colorToCode(-1)\n\n def testCodeToColorCodes(self):\n \"\"\"codeToColor() doit renvoyer les bonnes valeurs\"\"\"\n tests = [(0, 'W'), (1, 'B'), (2, 'R'), (3, 'G'), (4, 'O'), (5, 'Y')]\n for t in tests:\n self.assertEqual(codeToColor(t[0]), t[1])\n", "method_code": "def codeToColor(code):\n \"\"\"\n codeToColor\n\n Convertit un code entier en la couleur qui respond\n\n :Args:\n code {Int} {0, 1, ... 5}\n\n :Return:\n {String|None} La couleur en anglais dans\n {'W', 'B', 'R', 'G', 'O', 'Y'}.\n None si erreur de code.\n \"\"\"\n if code < 6 and code > -1:\n return COULEURS[code]\n else:\n raise ValueError(str(code) + \" n'est pas dans {0,1,2,3,4,5}\")", "context": "def codeToColor(code): ...\ndef Array(arr): ...\ndef readArgs(): ...\ndef codeToColor(code): ...\ndef colorToCode(color): ...\ndef codeToGroup(code): ...\ndef colorize(c, convert=None): ...\ndef croix_valide(c): ...\ndef ftl_valide(c): ...\ndef cfop_valide(cube, mouvements): ...\ndef translate_mvt(mvt): ...\ndef clear(): ...\ndef newGetch(): ...\ndef find_sublists(seq, sublist): ...\ndef replace_sublist(seq, target, replacement): ...\n", "repository": "Togodumnus/Ragnulf", "test_name": "testCodeToColorTypes", "smells": [1, 1, 0, 0, 1, 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, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000294.py"} {"focal_file": "utils.py", "focal_class": null, "focal_method": "colorToCode", "tests": "import unittest\n\nclass Test_colorToCode(unittest.TestCase):\n def testColorToCodeType(self):\n \"\"\"\n colorToCode() ne doit accèpter qu'un caractère\n dans {'W', 'B', 'R', 'G', 'O', 'Y'}\n \"\"\"\n with self.assertRaises(ValueError):\n colorToCode(1)\n with self.assertRaises(ValueError):\n colorToCode(None)\n with self.assertRaises(ValueError):\n colorToCode([])\n with self.assertRaises(ValueError):\n colorToCode('A')\n\n def testColorToCode(self):\n \"\"\"colorToCode() doit renvoyer les bonnes valeurs\"\"\"\n tests = [('W', 0), ('B', 1), ('R', 2), ('G', 3), ('O', 4), ('Y', 5)]\n for t in tests:\n self.assertEqual(colorToCode(t[0]), t[1])\n", "method_code": "def colorToCode(color):\n \"\"\"\n codeToColor\n\n Convertit la str couleur (W,O..) au code correspondant\n\n :Args:\n code {Str} {'W', 'B', 'R', 'G', 'O', 'Y'}\n\n :Return:\n {Int|None} Le code associé à la couleur\n \"\"\"\n if color in COULEURS:\n return COULEURS.index(color)\n else:\n raise ValueError(str(color) + \" n'est pas dans {'W', 'B', 'R', 'G', 'O', 'Y'}\")", "context": "def colorToCode(color): ...\ndef Array(arr): ...\ndef readArgs(): ...\ndef codeToColor(code): ...\ndef colorToCode(color): ...\ndef codeToGroup(code): ...\ndef colorize(c, convert=None): ...\ndef croix_valide(c): ...\ndef ftl_valide(c): ...\ndef cfop_valide(cube, mouvements): ...\ndef translate_mvt(mvt): ...\ndef clear(): ...\ndef newGetch(): ...\ndef find_sublists(seq, sublist): ...\ndef replace_sublist(seq, target, replacement): ...\n", "repository": "Togodumnus/Ragnulf", "test_name": "testColorToCodeType", "smells": [1, 1, 0, 0, 1, 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, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000295.py"} {"focal_file": "utils.py", "focal_class": null, "focal_method": "codeToGroup", "tests": "import unittest\n\nclass Test_codeToGroup(unittest.TestCase):\n def testCodeToGroupType(self):\n \"\"\"codeToGroup() ne doit accèpter qu'un int entre 0 et 6\"\"\"\n with self.assertRaises(ValueError):\n codeToGroup(-1)\n with self.assertRaises(ValueError):\n codeToGroup(6)\n with self.assertRaises(ValueError):\n codeToGroup('a')\n\n def testCodeToGroup(self):\n \"\"\"codeToGroup()\"\"\"\n tests = [(0, 0), (5, 0), (2, 1), (4, 1), (1, 2), (3, 2)]\n for t in tests:\n self.assertEqual(codeToGroup(t[0]), t[1])\n", "method_code": "def codeToGroup(code):\n \"\"\"\n codeToGroup\n\n On défini 3 groupes :\n - 0 : Blanc (0) et Jaune (5)\n - 1 : Orange (4) et Rouge (2)\n - 2 : Bleu (1) et Vert (3)\n\n Ils servent à valider un petit cube\n\n :Args:\n code {Int} La couleur dans {0, 1 ... 5}\n\n :Return:\n {Int} Le groupe\n \"\"\"\n if code == 0 or code == 5:\n return 0\n elif code == 4 or code == 2:\n return 1\n elif code == 1 or code == 3:\n return 2\n else:\n raise ValueError(str(code) + \" n'est pas une couleur\")", "context": "def codeToGroup(code): ...\ndef Array(arr): ...\ndef readArgs(): ...\ndef codeToColor(code): ...\ndef colorToCode(color): ...\ndef codeToGroup(code): ...\ndef colorize(c, convert=None): ...\ndef croix_valide(c): ...\ndef ftl_valide(c): ...\ndef cfop_valide(cube, mouvements): ...\ndef translate_mvt(mvt): ...\ndef clear(): ...\ndef newGetch(): ...\ndef find_sublists(seq, sublist): ...\ndef replace_sublist(seq, target, replacement): ...\n", "repository": "Togodumnus/Ragnulf", "test_name": "testCodeToGroupType", "smells": [1, 1, 0, 0, 1, 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, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000296.py"} {"focal_file": "utils.py", "focal_class": null, "focal_method": "colorize", "tests": "import unittest\n\nclass Test_colorize(unittest.TestCase):\n @unittest.skipIf(not os_name == 'nt', 'Lancé sous Windows')\n def testColorizeWindows(self):\n \"\"\"colorize() ne doit pas retourner de couleurs sous Windows\"\"\"\n tests = [('W', 'W'), ('Y', 'Y'), ('B', 'B'), ('R', 'R'), ('G', 'G'), ('O', 'O'), ('a', 'a'), (1, 1)]\n for t in tests:\n self.assertEqual(colorize(t[0]), t[1])\n self.assertEqual(colorize(t[0], []), t[1])\n", "method_code": "def colorize(c, convert=None):\n \"\"\"\n colorize\n\n :Args:\n c {String} La couleur (W, B, R, G, O, Y)\n convert {List} Optionel. Une traduction.\n ex: convert[0] = , etc.\n Defaut, voir COULEURS\n\n :Returns:\n {String} Une chaîne prête à être renvoyée au terminal pour un\n affichage coloré\n \"\"\"\n if not convert:\n convert = COULEURS\n else:\n assert len(convert) >= 6\n if c == 'W':\n return TermColors.bgWhite + TermColors.black + convert[0] + TermColors.end\n elif c == 'B':\n return TermColors.bgBlue + convert[1] + TermColors.end\n elif c == 'R':\n return TermColors.bgRed + convert[2] + TermColors.end\n elif c == 'G':\n return TermColors.bgGreen + convert[3] + TermColors.end\n elif c == 'O':\n return TermColors.bgOrange + convert[4] + TermColors.end\n elif c == 'Y':\n return TermColors.bgYellow + TermColors.black + convert[5] + TermColors.end\n else:\n return c", "context": "def colorize(c, convert=None): ...\ndef Array(arr): ...\ndef readArgs(): ...\ndef codeToColor(code): ...\ndef colorToCode(color): ...\ndef codeToGroup(code): ...\ndef colorize(c, convert=None): ...\ndef croix_valide(c): ...\ndef ftl_valide(c): ...\ndef cfop_valide(cube, mouvements): ...\ndef translate_mvt(mvt): ...\ndef clear(): ...\ndef newGetch(): ...\ndef find_sublists(seq, sublist): ...\ndef replace_sublist(seq, target, replacement): ...\n", "repository": "Togodumnus/Ragnulf", "test_name": "", "smells": [1, 1, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000297.py"} {"focal_file": "odoo_connector/connectors.py", "focal_class": null, "focal_method": "link", "tests": "import unittest\n\nclass Test_link(unittest.TestCase):\n def test_odoo_link_built(self):\n \"\"\"\n Test to check the link connection to Odoo instance through OdooConnector class.\n :return: None\n \"\"\"\n result = self.odoo.link()\n self.assertTrue(hasattr(result, 'version'), False)\n self.assertIsNotNone(result.version())\n", "method_code": " def link(self, link_type='common'):\n connection = None\n url = '{0}/xmlrpc/2/{1}'.format(self.endpoint, link_type)\n try:\n connection = client.ServerProxy(url, allow_none=1, encoding='utf-8')\n except Error as error:\n raise error\n except OSError as error:\n raise error\n except ConnectionRefusedError as error:\n raise error\n return connection\n ", "context": "class OdooConnector(OdooProtocol):\n def link(self, link_type='common'): ...\n def __init__(self, endpoint, dbname, username, password): ...\n def connect(self, dbname=None, username=None, password=None): ...\n def write(self, uid, model, action, data, password=None): ...\n def search(self, uid, model, action, password=None, queries=None, parameters=None, formatted=False): ...\n def output_formatter(self, result=[]): ...\n\n self.endpoint = endpoint\n self.dbname = dbname\n self.username = username\n self.password = password\n\n username = None\n password = None\n endpoint = None\n link_type = None\n dbname = None\n client = client\n", "repository": "franklintiel/odoo-connector-2", "test_name": "test_odoo_link_built", "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_000298.py"} {"focal_file": "odoo_connector/connectors.py", "focal_class": null, "focal_method": "link", "tests": "import unittest\n\nclass Test_link(unittest.TestCase):\n def test_odoo_link_built(self):\n \"\"\"\n Test to check the link connection to Odoo instance through OdooConnector class.\n :return: None\n \"\"\"\n result = self.odoo.link()\n self.assertTrue(hasattr(result, 'version'), False)\n self.assertIsNotNone(result.version())\n", "method_code": " def link(self, link_type='common'):\n connection = None\n url = '{0}/xmlrpc/2/{1}'.format(self.endpoint, link_type)\n try:\n connection = xmlrpclib.ServerProxy(url, allow_none=1, encoding='utf-8')\n except xmlrpclib.Error as error:\n raise error\n except Exception as error:\n raise error\n return connection\n ", "context": "class OdooConnector(OdooProtocol):\n def link(self, link_type='common'): ...\n def __init__(self, endpoint, dbname, username, password): ...\n def connect(self, dbname=None, username=None, password=None): ...\n def write(self, uid, model, action, data, password=None): ...\n def search(self, uid, model, action, password=None, queries=None, parameters=None, formatted=False): ...\n def output_formatter(self, result=[]): ...\n\n self.username = username\n self.endpoint = endpoint\n self.dbname = dbname\n self.password = password\n\n username = None\n password = None\n endpoint = None\n link_type = None\n dbname = None\n", "repository": "franklintiel/odoo-connector", "test_name": "test_odoo_link_built", "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_000299.py"} {"focal_file": "quickjs/__init__.py", "focal_class": null, "focal_method": "set_memory_limit", "tests": "import unittest\n\nclass Test_set_memory_limit(unittest.TestCase):\n def test_memory_limit(self):\n code = '\\n (function() {\\n let arr = [];\\n for (let i = 0; i < 1000; ++i) {\\n arr.push(i);\\n }\\n })();\\n '\n self.context.eval(code)\n self.context.set_memory_limit(1000)\n with self.assertRaisesRegex(quickjs.JSException, 'null'):\n self.context.eval(code)\n self.context.set_memory_limit(1000000)\n self.context.eval(code)\n", "method_code": " def set_memory_limit(self, limit):\n with self._lock:\n return self._context.set_memory_limit(limit)\n ", "context": "class Function():\n def set_memory_limit(self, limit): ...\n def __init__(self, name: str, code: str, *, own_executor=False) -> None: ...\n def __call__(self, *args, run_gc=True): ...\n def set_time_limit(self, limit): ...\n def set_max_stack_size(self, limit): ...\n def memory(self): ...\n def add_callable(self, global_name: str, callable: Callable) -> None: ...\n def gc(self): ...\n def _compile(self, name: str, code: str) -> Tuple[Context, Object]: ...\n def _call(self, *args, run_gc=True): ...\n\n self._lock = threading.Lock()\n self._context, self._f = future.result()\n\n _threadpool = concurrent.futures.ThreadPoolExecutor(max_workers=1)\n", "repository": "PetterS/quickjs", "test_name": "test_memory_limit", "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_000300.py"} {"focal_file": "quickjs/__init__.py", "focal_class": "quickjs.Function", "focal_method": "set_time_limit", "tests": "import unittest\n\nclass Test_quickjs_Function_set_time_limit(unittest.TestCase):\n def test_time_limit(self):\n f = quickjs.Function('f', '\\n function f() {\\n let arr = [];\\n for (let i = 0; i < 100000; ++i) {\\n arr.push(i);\\n }\\n return arr;\\n }\\n ')\n f()\n f.set_time_limit(0)\n with self.assertRaisesRegex(quickjs.JSException, 'InternalError: interrupted'):\n f()\n f.set_time_limit(-1)\n f()\n", "method_code": " def set_time_limit(self, limit):\n with self._lock:\n return self._context.set_time_limit(limit)\n ", "context": "class Function():\n def set_time_limit(self, limit): ...\n def __init__(self, name: str, code: str, *, own_executor=False) -> None: ...\n def __call__(self, *args, run_gc=True): ...\n def set_memory_limit(self, limit): ...\n def set_max_stack_size(self, limit): ...\n def memory(self): ...\n def add_callable(self, global_name: str, callable: Callable) -> None: ...\n def gc(self): ...\n def _compile(self, name: str, code: str) -> Tuple[Context, Object]: ...\n def _call(self, *args, run_gc=True): ...\n\n self._lock = threading.Lock()\n self._context, self._f = future.result()\n\n _threadpool = concurrent.futures.ThreadPoolExecutor(max_workers=1)\n", "repository": "PetterS/quickjs", "test_name": "test_time_limit", "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_000301.py"} {"focal_file": "quickjs/__init__.py", "focal_class": null, "focal_method": "set_time_limit", "tests": "import unittest\n\nclass Test_set_time_limit(unittest.TestCase):\n def test_time_limit_disallowed(self):\n self.context.add_callable('f', lambda x: x + 2)\n self.context.set_time_limit(1000)\n with self.assertRaises(quickjs.JSException):\n self.context.eval('f(40)')\n", "method_code": " def set_time_limit(self, limit):\n with self._lock:\n return self._context.set_time_limit(limit)\n ", "context": "class Function():\n def set_time_limit(self, limit): ...\n def __init__(self, name: str, code: str, *, own_executor=False) -> None: ...\n def __call__(self, *args, run_gc=True): ...\n def set_memory_limit(self, limit): ...\n def set_max_stack_size(self, limit): ...\n def memory(self): ...\n def add_callable(self, global_name: str, callable: Callable) -> None: ...\n def gc(self): ...\n def _compile(self, name: str, code: str) -> Tuple[Context, Object]: ...\n def _call(self, *args, run_gc=True): ...\n\n self._lock = threading.Lock()\n self._context, self._f = future.result()\n\n _threadpool = concurrent.futures.ThreadPoolExecutor(max_workers=1)\n", "repository": "PetterS/quickjs", "test_name": "test_time_limit_disallowed", "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_000302.py"} {"focal_file": "quickjs/__init__.py", "focal_class": "quickjs.Function", "focal_method": "add_callable", "tests": "import unittest\n\nclass Test_quickjs_Function_add_callable(unittest.TestCase):\n def test_add_callable(self):\n f = quickjs.Function('f', '\\n function f() {\\n return pfunc();\\n }\\n ')\n f.add_callable('pfunc', lambda: 42)\n self.assertEqual(f(), 42)\n", "method_code": " def add_callable(self, global_name: str, callable: Callable) -> None:\n with self._lock:\n self._context.add_callable(global_name, callable)\n ", "context": "class Function():\n def add_callable(self, global_name: str, callable: Callable) -> None: ...\n def __init__(self, name: str, code: str, *, own_executor=False) -> None: ...\n def __call__(self, *args, run_gc=True): ...\n def set_memory_limit(self, limit): ...\n def set_time_limit(self, limit): ...\n def set_max_stack_size(self, limit): ...\n def memory(self): ...\n def gc(self): ...\n def _compile(self, name: str, code: str) -> Tuple[Context, Object]: ...\n def _call(self, *args, run_gc=True): ...\n\n self._lock = threading.Lock()\n self._context, self._f = future.result()\n\n _threadpool = concurrent.futures.ThreadPoolExecutor(max_workers=1)\n", "repository": "PetterS/quickjs", "test_name": "test_add_callable", "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": "boto-2.2.2/boto/cloudfront/distribution.py", "focal_class": null, "focal_method": "_sign_string", "tests": "import unittest\n\nclass Test_sign_string(unittest.TestCase):\n def test_sign_custom_policy_1(self):\n \"\"\"\n Test signing custom policy 1 from amazon's cloudfront documentation.\n \"\"\"\n expected = 'cPFtRKvUfYNYmxek6ZNs6vgKEZP6G3Cb4cyVt~FjqbHOnMdxdT7eT6pYmhHYzuDsFH4Jpsctke2Ux6PCXcKxUcTIm8SO4b29~1QvhMl-CIojki3Hd3~Unxjw7Cpo1qRjtvrimW0DPZBZYHFZtiZXsaPt87yBP9GWnTQoaVysMxQ_'\n sig = self.dist._sign_string(self.custom_policy_1, private_key_string=self.pk_str)\n encoded_sig = self.dist._url_base64_encode(sig)\n self.assertEqual(expected, encoded_sig)\n\n def test_sign_custom_policy_2(self):\n \"\"\"\n Test signing custom policy 2 from amazon's cloudfront documentation.\n \"\"\"\n expected = 'rc~5Qbbm8EJXjUTQ6Cn0LAxR72g1DOPrTmdtfbWVVgQNw0q~KHUAmBa2Zv1Wjj8dDET4XSL~Myh44CLQdu4dOH~N9huH7QfPSR~O4tIOS1WWcP~2JmtVPoQyLlEc8YHRCuN3nVNZJ0m4EZcXXNAS-0x6Zco2SYx~hywTRxWR~5Q_'\n sig = self.dist._sign_string(self.custom_policy_2, private_key_string=self.pk_str)\n encoded_sig = self.dist._url_base64_encode(sig)\n self.assertEqual(expected, encoded_sig)\n", "method_code": " def _sign_string(message, private_key_file=None, private_key_string=None):\n \"\"\"\n Signs a string for use with Amazon CloudFront. Requires the M2Crypto\n library be installed.\n \"\"\"\n try:\n from M2Crypto import EVP\n except ImportError:\n raise NotImplementedError('Boto depends on the python M2Crypto library to generate signed URLs for CloudFront')\n if private_key_file and private_key_string:\n raise ValueError('Only specify the private_key_file or the private_key_string not both')\n if not private_key_file and (not private_key_string):\n raise ValueError('You must specify one of private_key_file or private_key_string')\n if isinstance(private_key_file, file):\n private_key_string = private_key_file.read()\n if private_key_string:\n key = EVP.load_key_string(private_key_string)\n else:\n key = EVP.load_key(private_key_file)\n key.reset_context(md='sha1')\n key.sign_init()\n key.sign_update(str(message))\n signature = key.sign_final()\n return signature\n ", "context": "class Distribution():\n @staticmethod\n def _sign_string(message, private_key_file=None, private_key_string=None): ...\n def __init__(self, connection=None, config=None, domain_name='', id='', last_modified_time=None, status=''): ...\n def startElement(self, name, attrs, connection): ...\n def endElement(self, name, value, connection): ...\n def update(self, enabled=None, cnames=None, comment=None): ...\n def enable(self): ...\n def disable(self): ...\n def delete(self): ...\n def _get_bucket(self): ...\n def get_objects(self): ...\n def set_permissions(self, object, replace=False): ...\n def set_permissions_all(self, replace=False): ...\n def add_object(self, name, content, headers=None, replace=True): ...\n def create_signed_url(self, url, keypair_id, expire_time=None, valid_after_time=None, ip_address=None, policy_url=None, private_key_file=None, private_key_string=None): ...\n def _create_signing_params(self, url, keypair_id, expire_time=None, valid_after_time=None, ip_address=None, policy_url=None, private_key_file=None, private_key_string=None): ...\n def _canned_policy(resource, expires): ...\n def _custom_policy(resource, expires=None, valid_after=None, ip_address=None): ...\n def _url_base64_encode(msg): ...\n\n self.connection = connection\n self.config = config\n self.domain_name = domain_name\n self.id = id\n self.last_modified_time = last_modified_time\n self.status = status\n self.in_progress_invalidation_batches = 0\n self.active_signers = None\n self.etag = None\n self._bucket = None\n self._object_class = Object\n", "repository": "jasonc1/collide_game_MTURK", "test_name": "test_sign_custom_policy_1", "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_000304.py"} {"focal_file": "boto-2.2.2/boto/cloudfront/distribution.py", "focal_class": null, "focal_method": "_canned_policy", "tests": "import unittest\n\nclass Test_canned_policy(unittest.TestCase):\n def test_create_canned_policy(self):\n \"\"\"\n Test that a canned policy is generated correctly.\n \"\"\"\n url = 'http://1234567.cloudfront.com/test_resource.mp3?dog=true'\n expires = 999999\n policy = self.dist._canned_policy(url, expires)\n policy = json.loads(policy)\n self.assertEqual(1, len(policy.keys()))\n statements = policy['Statement']\n self.assertEqual(1, len(statements))\n statement = statements[0]\n resource = statement['Resource']\n self.assertEqual(url, resource)\n condition = statement['Condition']\n self.assertEqual(1, len(condition.keys()))\n date_less_than = condition['DateLessThan']\n self.assertEqual(1, len(date_less_than.keys()))\n aws_epoch_time = date_less_than['AWS:EpochTime']\n self.assertEqual(expires, aws_epoch_time)\n", "method_code": " def _canned_policy(resource, expires):\n \"\"\"\n Creates a canned policy string.\n \"\"\"\n policy = '{\"Statement\":[{\"Resource\":\"%(resource)s\",\"Condition\":{\"DateLessThan\":{\"AWS:EpochTime\":%(expires)s}}}]}' % locals()\n return policy\n ", "context": "class Distribution():\n @staticmethod\n def _canned_policy(resource, expires): ...\n def __init__(self, connection=None, config=None, domain_name='', id='', last_modified_time=None, status=''): ...\n def startElement(self, name, attrs, connection): ...\n def endElement(self, name, value, connection): ...\n def update(self, enabled=None, cnames=None, comment=None): ...\n def enable(self): ...\n def disable(self): ...\n def delete(self): ...\n def _get_bucket(self): ...\n def get_objects(self): ...\n def set_permissions(self, object, replace=False): ...\n def set_permissions_all(self, replace=False): ...\n def add_object(self, name, content, headers=None, replace=True): ...\n def create_signed_url(self, url, keypair_id, expire_time=None, valid_after_time=None, ip_address=None, policy_url=None, private_key_file=None, private_key_string=None): ...\n def _create_signing_params(self, url, keypair_id, expire_time=None, valid_after_time=None, ip_address=None, policy_url=None, private_key_file=None, private_key_string=None): ...\n def _custom_policy(resource, expires=None, valid_after=None, ip_address=None): ...\n def _sign_string(message, private_key_file=None, private_key_string=None): ...\n def _url_base64_encode(msg): ...\n\n self.connection = connection\n self.config = config\n self.domain_name = domain_name\n self.id = id\n self.last_modified_time = last_modified_time\n self.status = status\n self.in_progress_invalidation_batches = 0\n self.active_signers = None\n self.etag = None\n self._bucket = None\n self._object_class = Object\n", "repository": "jasonc1/collide_game_MTURK", "test_name": "test_create_canned_policy", "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, 0, 0, 0], "pynose_source_file": "test_000305.py"} {"focal_file": "boto-2.2.2/boto/cloudfront/distribution.py", "focal_class": null, "focal_method": "_custom_policy", "tests": "import unittest\n\nclass Test_custom_policy(unittest.TestCase):\n def test_custom_policy_expires_and_policy_url(self):\n \"\"\"\n Test that a custom policy can be created with an expire time and an\n arbitrary URL.\n \"\"\"\n url = 'http://1234567.cloudfront.com/*'\n expires = 999999\n policy = self.dist._custom_policy(url, expires=expires)\n policy = json.loads(policy)\n self.assertEqual(1, len(policy.keys()))\n statements = policy['Statement']\n self.assertEqual(1, len(statements))\n statement = statements[0]\n resource = statement['Resource']\n self.assertEqual(url, resource)\n condition = statement['Condition']\n self.assertEqual(1, len(condition.keys()))\n date_less_than = condition['DateLessThan']\n self.assertEqual(1, len(date_less_than.keys()))\n aws_epoch_time = date_less_than['AWS:EpochTime']\n self.assertEqual(expires, aws_epoch_time)\n\n def test_custom_policy_valid_after(self):\n \"\"\"\n Test that a custom policy can be created with a valid-after time and\n an arbitrary URL.\n \"\"\"\n url = 'http://1234567.cloudfront.com/*'\n valid_after = 999999\n policy = self.dist._custom_policy(url, valid_after=valid_after)\n policy = json.loads(policy)\n self.assertEqual(1, len(policy.keys()))\n statements = policy['Statement']\n self.assertEqual(1, len(statements))\n statement = statements[0]\n resource = statement['Resource']\n self.assertEqual(url, resource)\n condition = statement['Condition']\n self.assertEqual(1, len(condition.keys()))\n date_greater_than = condition['DateGreaterThan']\n self.assertEqual(1, len(date_greater_than.keys()))\n aws_epoch_time = date_greater_than['AWS:EpochTime']\n self.assertEqual(valid_after, aws_epoch_time)\n\n def test_custom_policy_ip_address(self):\n \"\"\"\n Test that a custom policy can be created with an IP address and\n an arbitrary URL.\n \"\"\"\n url = 'http://1234567.cloudfront.com/*'\n ip_range = '192.168.0.1'\n policy = self.dist._custom_policy(url, ip_address=ip_range)\n policy = json.loads(policy)\n self.assertEqual(1, len(policy.keys()))\n statements = policy['Statement']\n self.assertEqual(1, len(statements))\n statement = statements[0]\n resource = statement['Resource']\n self.assertEqual(url, resource)\n condition = statement['Condition']\n self.assertEqual(1, len(condition.keys()))\n ip_address = condition['IpAddress']\n self.assertEqual(1, len(ip_address.keys()))\n source_ip = ip_address['AWS:SourceIp']\n self.assertEqual('%s/32' % ip_range, source_ip)\n\n def test_custom_policy_ip_range(self):\n \"\"\"\n Test that a custom policy can be created with an IP address and\n an arbitrary URL.\n \"\"\"\n url = 'http://1234567.cloudfront.com/*'\n ip_range = '192.168.0.0/24'\n policy = self.dist._custom_policy(url, ip_address=ip_range)\n policy = json.loads(policy)\n self.assertEqual(1, len(policy.keys()))\n statements = policy['Statement']\n self.assertEqual(1, len(statements))\n statement = statements[0]\n resource = statement['Resource']\n self.assertEqual(url, resource)\n condition = statement['Condition']\n self.assertEqual(1, len(condition.keys()))\n ip_address = condition['IpAddress']\n self.assertEqual(1, len(ip_address.keys()))\n source_ip = ip_address['AWS:SourceIp']\n self.assertEqual(ip_range, source_ip)\n\n def test_custom_policy_all(self):\n \"\"\"\n Test that a custom policy can be created with an IP address and\n an arbitrary URL.\n \"\"\"\n url = 'http://1234567.cloudfront.com/test.txt'\n expires = 999999\n valid_after = 111111\n ip_range = '192.168.0.0/24'\n policy = self.dist._custom_policy(url, expires=expires, valid_after=valid_after, ip_address=ip_range)\n policy = json.loads(policy)\n self.assertEqual(1, len(policy.keys()))\n statements = policy['Statement']\n self.assertEqual(1, len(statements))\n statement = statements[0]\n resource = statement['Resource']\n self.assertEqual(url, resource)\n condition = statement['Condition']\n self.assertEqual(3, len(condition.keys()))\n date_less_than = condition['DateLessThan']\n self.assertEqual(1, len(date_less_than.keys()))\n aws_epoch_time = date_less_than['AWS:EpochTime']\n self.assertEqual(expires, aws_epoch_time)\n date_greater_than = condition['DateGreaterThan']\n self.assertEqual(1, len(date_greater_than.keys()))\n aws_epoch_time = date_greater_than['AWS:EpochTime']\n self.assertEqual(valid_after, aws_epoch_time)\n ip_address = condition['IpAddress']\n self.assertEqual(1, len(ip_address.keys()))\n source_ip = ip_address['AWS:SourceIp']\n self.assertEqual(ip_range, source_ip)\n", "method_code": " def _custom_policy(resource, expires=None, valid_after=None, ip_address=None):\n \"\"\"\n Creates a custom policy string based on the supplied parameters.\n \"\"\"\n condition = {}\n if expires:\n condition['DateLessThan'] = {'AWS:EpochTime': expires}\n if valid_after:\n condition['DateGreaterThan'] = {'AWS:EpochTime': valid_after}\n if ip_address:\n if '/' not in ip_address:\n ip_address += '/32'\n condition['IpAddress'] = {'AWS:SourceIp': ip_address}\n policy = {'Statement': [{'Resource': resource, 'Condition': condition}]}\n return json.dumps(policy, separators=(',', ':'))\n ", "context": "class Distribution():\n @staticmethod\n def _custom_policy(resource, expires=None, valid_after=None, ip_address=None): ...\n def __init__(self, connection=None, config=None, domain_name='', id='', last_modified_time=None, status=''): ...\n def startElement(self, name, attrs, connection): ...\n def endElement(self, name, value, connection): ...\n def update(self, enabled=None, cnames=None, comment=None): ...\n def enable(self): ...\n def disable(self): ...\n def delete(self): ...\n def _get_bucket(self): ...\n def get_objects(self): ...\n def set_permissions(self, object, replace=False): ...\n def set_permissions_all(self, replace=False): ...\n def add_object(self, name, content, headers=None, replace=True): ...\n def create_signed_url(self, url, keypair_id, expire_time=None, valid_after_time=None, ip_address=None, policy_url=None, private_key_file=None, private_key_string=None): ...\n def _create_signing_params(self, url, keypair_id, expire_time=None, valid_after_time=None, ip_address=None, policy_url=None, private_key_file=None, private_key_string=None): ...\n def _canned_policy(resource, expires): ...\n def _sign_string(message, private_key_file=None, private_key_string=None): ...\n def _url_base64_encode(msg): ...\n\n self.connection = connection\n self.config = config\n self.domain_name = domain_name\n self.id = id\n self.last_modified_time = last_modified_time\n self.status = status\n self.in_progress_invalidation_batches = 0\n self.active_signers = None\n self.etag = None\n self._bucket = None\n self._object_class = Object\n", "repository": "jasonc1/collide_game_MTURK", "test_name": "test_custom_policy_expires_and_policy_url", "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, 1, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000306.py"} {"focal_file": "boto-2.2.2/boto/ec2/cloudwatch/metric.py", "focal_class": null, "focal_method": "describe_alarms", "tests": "import unittest\n\nclass Test_describe_alarms(unittest.TestCase):\n def test_describe_alarms(self):\n c = CloudWatchConnection()\n\n def make_request(*args, **kwargs):\n\n class Body(object):\n\n def __init__(self):\n self.status = 200\n\n def read(self):\n return DESCRIBE_ALARMS_BODY\n return Body()\n c.make_request = make_request\n alarms = c.describe_alarms()\n self.assertEquals(alarms[0].name, 'FancyAlarm')\n self.assertEquals(alarms[0].comparison, '<')\n self.assertEquals(alarms[0].dimensions, {u'Job': [u'ANiceCronJob']})\n self.assertEquals(alarms[1].name, 'SuperFancyAlarm')\n self.assertEquals(alarms[1].comparison, '>')\n self.assertEquals(alarms[1].dimensions, {u'Job': [u'ABadCronJob']})\n", "method_code": " def describe_alarms(self, period=None, statistic=None, dimensions=None, unit=None):\n return self.connection.describe_alarms_for_metric(self.name, self.namespace, period, statistic, dimensions, unit)\n ", "context": "class Metric(object):\n def describe_alarms(self, period=None, statistic=None, dimensions=None, unit=None): ...\n def __init__(self, connection=None): ...\n def __repr__(self): ...\n def startElement(self, name, attrs, connection): ...\n def endElement(self, name, value, connection): ...\n def query(self, start_time, end_time, statistics, unit=None, period=60): ...\n def create_alarm(self, name, comparison, threshold, period, evaluation_periods, statistic, enabled=True, description=None, dimensions=None, alarm_actions=None, ok_actions=None, insufficient_data_actions=None, unit=None): ...\n\n self.connection = connection\n self.name = None\n self.namespace = None\n self.dimensions = None\n\n Statistics = ['Minimum', 'Maximum', 'Sum', 'Average', 'SampleCount']\n Units = ['Seconds', 'Microseconds', 'Milliseconds', 'Bytes', 'Kilobytes', 'Megabytes', 'Gigabytes', 'Terabytes', 'Bits', 'Kilobits', 'Megabits', 'Gigabits', 'Terabits', 'Percent', 'Count', 'Bytes/Second', 'Kilobytes/Second', 'Megabytes/Second', 'Gigabytes/Second', 'Terabytes/Second', 'Bits/Second', 'Kilobits/Second', 'Megabits/Second', 'Gigabits/Second', 'Terabits/Second', 'Count/Second', None]\n", "repository": "jasonc1/collide_game_MTURK", "test_name": "test_describe_alarms", "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_000307.py"} {"focal_file": "boto-2.2.2/boto/ec2/elb/__init__.py", "focal_class": "ELBConnection", "focal_method": "build_list_params", "tests": "import unittest\n\nclass Test_ELBConnection_build_list_params(unittest.TestCase):\n def test_build_list_params(self):\n c = ELBConnection()\n params = {}\n c.build_list_params(params, ['thing1', 'thing2', 'thing3'], 'ThingName%d')\n expected_params = {'ThingName1': 'thing1', 'ThingName2': 'thing2', 'ThingName3': 'thing3'}\n self.assertEqual(params, expected_params)\n", "method_code": " def build_list_params(self, params, items, label):\n if isinstance(items, str):\n items = [items]\n for index, item in enumerate(items):\n params[label % (index + 1)] = item\n ", "context": "class ELBConnection(AWSQueryConnection):\n def build_list_params(self, params, items, label): ...\n def __init__(self, aws_access_key_id=None, aws_secret_access_key=None, is_secure=False, port=None, proxy=None, proxy_port=None, proxy_user=None, proxy_pass=None, debug=0, https_connection_factory=None, region=None, path='/'): ...\n def _required_auth_capability(self): ...\n def get_all_load_balancers(self, load_balancer_names=None): ...\n def create_load_balancer(self, name, zones, listeners, subnets=None, security_groups=None): ...\n def create_load_balancer_listeners(self, name, listeners): ...\n def delete_load_balancer(self, name): ...\n def delete_load_balancer_listeners(self, name, ports): ...\n def enable_availability_zones(self, load_balancer_name, zones_to_add): ...\n def disable_availability_zones(self, load_balancer_name, zones_to_remove): ...\n def register_instances(self, load_balancer_name, instances): ...\n def deregister_instances(self, load_balancer_name, instances): ...\n def describe_instance_health(self, load_balancer_name, instances=None): ...\n def configure_health_check(self, name, health_check): ...\n def set_lb_listener_SSL_certificate(self, lb_name, lb_port, ssl_certificate_id): ...\n def create_app_cookie_stickiness_policy(self, name, lb_name, policy_name): ...\n def create_lb_cookie_stickiness_policy(self, cookie_expiration_period, lb_name, policy_name): ...\n def delete_lb_policy(self, lb_name, policy_name): ...\n def set_lb_policies_of_listener(self, lb_name, lb_port, policies): ...\n def apply_security_groups_to_lb(self, name, security_groups): ...\n def attach_lb_to_subnets(self, name, subnets): ...\n def detach_lb_from_subnets(self, name, subnets): ...\n\n self.region = region\n\n APIVersion = boto.config.get('Boto', 'elb_version', '2011-11-15')\n DefaultRegionName = boto.config.get('Boto', 'elb_region_name', 'us-east-1')\n DefaultRegionEndpoint = boto.config.get('Boto', 'elb_region_endpoint', 'elasticloadbalancing.amazonaws.com')\n", "repository": "jasonc1/collide_game_MTURK", "test_name": "test_build_list_params", "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_000308.py"} {"focal_file": "boto-2.2.2/boto/ec2/elb/__init__.py", "focal_class": "ELBConnection", "focal_method": "create_load_balancer", "tests": "import unittest\n\nclass Test_ELBConnection_create_load_balancer(unittest.TestCase):\n def test_create_load_balancer(self):\n c = ELBConnection()\n name = 'elb-boto-unit-test'\n availability_zones = ['us-east-1a']\n listeners = [(80, 8000, 'HTTP')]\n balancer = c.create_load_balancer(name, availability_zones, listeners)\n self.assertEqual(balancer.name, name)\n self.assertEqual(balancer.availability_zones, availability_zones)\n self.assertEqual(balancer.listeners, listeners)\n balancers = c.get_all_load_balancers()\n self.assertEqual([lb.name for lb in balancers], [name])\n", "method_code": " def create_load_balancer(self, name, zones, listeners, subnets=None, security_groups=None):\n \"\"\"\n Create a new load balancer for your account. By default the load\n balancer will be created in EC2. To create a load balancer inside a\n VPC, parameter zones must be set to None and subnets must not be None.\n The load balancer will be automatically created under the VPC that\n contains the subnet(s) specified.\n \n :type name: string\n :param name: The mnemonic name associated with the new load balancer\n \n :type zones: List of strings\n :param zones: The names of the availability zone(s) to add.\n \n :type listeners: List of tuples\n :param listeners: Each tuple contains three or four values,\n (LoadBalancerPortNumber, InstancePortNumber,\n Protocol, [SSLCertificateId])\n where LoadBalancerPortNumber and InstancePortNumber\n are integer values between 1 and 65535, Protocol is a\n string containing either 'TCP', 'HTTP' or 'HTTPS';\n SSLCertificateID is the ARN of a AWS AIM certificate,\n and must be specified when doing HTTPS.\n \n :rtype: :class:`boto.ec2.elb.loadbalancer.LoadBalancer`\n :return: The newly created :class:`boto.ec2.elb.loadbalancer.LoadBalancer`\n \"\"\"\n params = {'LoadBalancerName': name}\n for index, listener in enumerate(listeners):\n i = index + 1\n params['Listeners.member.%d.LoadBalancerPort' % i] = listener[0]\n params['Listeners.member.%d.InstancePort' % i] = listener[1]\n params['Listeners.member.%d.Protocol' % i] = listener[2]\n if listener[2] == 'HTTPS':\n params['Listeners.member.%d.SSLCertificateId' % i] = listener[3]\n if zones:\n self.build_list_params(params, zones, 'AvailabilityZones.member.%d')\n if subnets:\n self.build_list_params(params, subnets, 'Subnets.member.%d')\n if security_groups:\n self.build_list_params(params, security_groups, 'SecurityGroups.member.%d')\n load_balancer = self.get_object('CreateLoadBalancer', params, LoadBalancer)\n load_balancer.name = name\n load_balancer.listeners = listeners\n load_balancer.availability_zones = zones\n load_balancer.subnets = subnets\n load_balancer.security_groups = security_groups\n return load_balancer\n ", "context": "class ELBConnection(AWSQueryConnection):\n def create_load_balancer(self, name, zones, listeners, subnets=None, security_groups=None): ...\n def __init__(self, aws_access_key_id=None, aws_secret_access_key=None, is_secure=False, port=None, proxy=None, proxy_port=None, proxy_user=None, proxy_pass=None, debug=0, https_connection_factory=None, region=None, path='/'): ...\n def _required_auth_capability(self): ...\n def build_list_params(self, params, items, label): ...\n def get_all_load_balancers(self, load_balancer_names=None): ...\n def create_load_balancer_listeners(self, name, listeners): ...\n def delete_load_balancer(self, name): ...\n def delete_load_balancer_listeners(self, name, ports): ...\n def enable_availability_zones(self, load_balancer_name, zones_to_add): ...\n def disable_availability_zones(self, load_balancer_name, zones_to_remove): ...\n def register_instances(self, load_balancer_name, instances): ...\n def deregister_instances(self, load_balancer_name, instances): ...\n def describe_instance_health(self, load_balancer_name, instances=None): ...\n def configure_health_check(self, name, health_check): ...\n def set_lb_listener_SSL_certificate(self, lb_name, lb_port, ssl_certificate_id): ...\n def create_app_cookie_stickiness_policy(self, name, lb_name, policy_name): ...\n def create_lb_cookie_stickiness_policy(self, cookie_expiration_period, lb_name, policy_name): ...\n def delete_lb_policy(self, lb_name, policy_name): ...\n def set_lb_policies_of_listener(self, lb_name, lb_port, policies): ...\n def apply_security_groups_to_lb(self, name, security_groups): ...\n def attach_lb_to_subnets(self, name, subnets): ...\n def detach_lb_from_subnets(self, name, subnets): ...\n\n self.region = region\n\n APIVersion = boto.config.get('Boto', 'elb_version', '2011-11-15')\n DefaultRegionName = boto.config.get('Boto', 'elb_region_name', 'us-east-1')\n DefaultRegionEndpoint = boto.config.get('Boto', 'elb_region_endpoint', 'elasticloadbalancing.amazonaws.com')\n", "repository": "jasonc1/collide_game_MTURK", "test_name": "test_create_load_balancer", "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, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000309.py"} {"focal_file": "boto-2.2.2/boto/ec2/elb/__init__.py", "focal_class": "ELBConnection", "focal_method": "create_load_balancer_listeners", "tests": "import unittest\n\nclass Test_ELBConnection_create_load_balancer_listeners(unittest.TestCase):\n def test_create_load_balancer_listeners(self):\n c = ELBConnection()\n name = 'elb-boto-unit-test'\n availability_zones = ['us-east-1a']\n listeners = [(80, 8000, 'HTTP')]\n balancer = c.create_load_balancer(name, availability_zones, listeners)\n more_listeners = [(443, 8001, 'HTTP')]\n c.create_load_balancer_listeners(name, more_listeners)\n balancers = c.get_all_load_balancers()\n self.assertEqual([lb.name for lb in balancers], [name])\n self.assertEqual(sorted((l.get_tuple() for l in balancers[0].listeners)), sorted(listeners + more_listeners))\n", "method_code": " def create_load_balancer_listeners(self, name, listeners):\n \"\"\"\n Creates a Listener (or group of listeners) for an existing Load Balancer\n \n :type name: string\n :param name: The name of the load balancer to create the listeners for\n \n :type listeners: List of tuples\n :param listeners: Each tuple contains three values,\n (LoadBalancerPortNumber, InstancePortNumber, Protocol,\n [SSLCertificateId])\n where LoadBalancerPortNumber and InstancePortNumber are\n integer values between 1 and 65535, Protocol is a\n string containing either 'TCP', 'HTTP' or 'HTTPS';\n SSLCertificateID is the ARN of a AWS AIM certificate,\n and must be specified when doing HTTPS.\n \n :return: The status of the request\n \"\"\"\n params = {'LoadBalancerName': name}\n for index, listener in enumerate(listeners):\n i = index + 1\n params['Listeners.member.%d.LoadBalancerPort' % i] = listener[0]\n params['Listeners.member.%d.InstancePort' % i] = listener[1]\n params['Listeners.member.%d.Protocol' % i] = listener[2]\n if listener[2] == 'HTTPS':\n params['Listeners.member.%d.SSLCertificateId' % i] = listener[3]\n return self.get_status('CreateLoadBalancerListeners', params)\n ", "context": "class ELBConnection(AWSQueryConnection):\n def create_load_balancer_listeners(self, name, listeners): ...\n def __init__(self, aws_access_key_id=None, aws_secret_access_key=None, is_secure=False, port=None, proxy=None, proxy_port=None, proxy_user=None, proxy_pass=None, debug=0, https_connection_factory=None, region=None, path='/'): ...\n def _required_auth_capability(self): ...\n def build_list_params(self, params, items, label): ...\n def get_all_load_balancers(self, load_balancer_names=None): ...\n def create_load_balancer(self, name, zones, listeners, subnets=None, security_groups=None): ...\n def delete_load_balancer(self, name): ...\n def delete_load_balancer_listeners(self, name, ports): ...\n def enable_availability_zones(self, load_balancer_name, zones_to_add): ...\n def disable_availability_zones(self, load_balancer_name, zones_to_remove): ...\n def register_instances(self, load_balancer_name, instances): ...\n def deregister_instances(self, load_balancer_name, instances): ...\n def describe_instance_health(self, load_balancer_name, instances=None): ...\n def configure_health_check(self, name, health_check): ...\n def set_lb_listener_SSL_certificate(self, lb_name, lb_port, ssl_certificate_id): ...\n def create_app_cookie_stickiness_policy(self, name, lb_name, policy_name): ...\n def create_lb_cookie_stickiness_policy(self, cookie_expiration_period, lb_name, policy_name): ...\n def delete_lb_policy(self, lb_name, policy_name): ...\n def set_lb_policies_of_listener(self, lb_name, lb_port, policies): ...\n def apply_security_groups_to_lb(self, name, security_groups): ...\n def attach_lb_to_subnets(self, name, subnets): ...\n def detach_lb_from_subnets(self, name, subnets): ...\n\n self.region = region\n\n APIVersion = boto.config.get('Boto', 'elb_version', '2011-11-15')\n DefaultRegionName = boto.config.get('Boto', 'elb_region_name', 'us-east-1')\n DefaultRegionEndpoint = boto.config.get('Boto', 'elb_region_endpoint', 'elasticloadbalancing.amazonaws.com')\n", "repository": "jasonc1/collide_game_MTURK", "test_name": "test_create_load_balancer_listeners", "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, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000310.py"} {"focal_file": "boto-2.2.2/boto/ec2/elb/__init__.py", "focal_class": "ELBConnection", "focal_method": "delete_load_balancer_listeners", "tests": "import unittest\n\nclass Test_ELBConnection_delete_load_balancer_listeners(unittest.TestCase):\n def test_delete_load_balancer_listeners(self):\n c = ELBConnection()\n name = 'elb-boto-unit-test'\n availability_zones = ['us-east-1a']\n listeners = [(80, 8000, 'HTTP'), (443, 8001, 'HTTP')]\n balancer = c.create_load_balancer(name, availability_zones, listeners)\n balancers = c.get_all_load_balancers()\n self.assertEqual([lb.name for lb in balancers], [name])\n self.assertEqual([l.get_tuple() for l in balancers[0].listeners], listeners)\n c.delete_load_balancer_listeners(name, [443])\n balancers = c.get_all_load_balancers()\n self.assertEqual([lb.name for lb in balancers], [name])\n self.assertEqual([l.get_tuple() for l in balancers[0].listeners], listeners[:1])\n", "method_code": " def delete_load_balancer_listeners(self, name, ports):\n \"\"\"\n Deletes a load balancer listener (or group of listeners)\n \n :type name: string\n :param name: The name of the load balancer to create the listeners for\n \n :type ports: List int\n :param ports: Each int represents the port on the ELB to be removed\n \n :return: The status of the request\n \"\"\"\n params = {'LoadBalancerName': name}\n for index, port in enumerate(ports):\n params['LoadBalancerPorts.member.%d' % (index + 1)] = port\n return self.get_status('DeleteLoadBalancerListeners', params)\n ", "context": "class ELBConnection(AWSQueryConnection):\n def delete_load_balancer_listeners(self, name, ports): ...\n def __init__(self, aws_access_key_id=None, aws_secret_access_key=None, is_secure=False, port=None, proxy=None, proxy_port=None, proxy_user=None, proxy_pass=None, debug=0, https_connection_factory=None, region=None, path='/'): ...\n def _required_auth_capability(self): ...\n def build_list_params(self, params, items, label): ...\n def get_all_load_balancers(self, load_balancer_names=None): ...\n def create_load_balancer(self, name, zones, listeners, subnets=None, security_groups=None): ...\n def create_load_balancer_listeners(self, name, listeners): ...\n def delete_load_balancer(self, name): ...\n def enable_availability_zones(self, load_balancer_name, zones_to_add): ...\n def disable_availability_zones(self, load_balancer_name, zones_to_remove): ...\n def register_instances(self, load_balancer_name, instances): ...\n def deregister_instances(self, load_balancer_name, instances): ...\n def describe_instance_health(self, load_balancer_name, instances=None): ...\n def configure_health_check(self, name, health_check): ...\n def set_lb_listener_SSL_certificate(self, lb_name, lb_port, ssl_certificate_id): ...\n def create_app_cookie_stickiness_policy(self, name, lb_name, policy_name): ...\n def create_lb_cookie_stickiness_policy(self, cookie_expiration_period, lb_name, policy_name): ...\n def delete_lb_policy(self, lb_name, policy_name): ...\n def set_lb_policies_of_listener(self, lb_name, lb_port, policies): ...\n def apply_security_groups_to_lb(self, name, security_groups): ...\n def attach_lb_to_subnets(self, name, subnets): ...\n def detach_lb_from_subnets(self, name, subnets): ...\n\n self.region = region\n\n APIVersion = boto.config.get('Boto', 'elb_version', '2011-11-15')\n DefaultRegionName = boto.config.get('Boto', 'elb_region_name', 'us-east-1')\n DefaultRegionEndpoint = boto.config.get('Boto', 'elb_region_endpoint', 'elasticloadbalancing.amazonaws.com')\n", "repository": "jasonc1/collide_game_MTURK", "test_name": "test_delete_load_balancer_listeners", "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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000311.py"} {"focal_file": "boto-2.2.2/boto/s3/key.py", "focal_class": null, "focal_method": "set_contents_from_file", "tests": "import unittest\n\nclass Test_set_contents_from_file(unittest.TestCase):\n def test_set_contents_as_file(self):\n content = '01234567890123456789'\n sfp = StringIO.StringIO(content)\n k = self.bucket.new_key('k')\n k.set_contents_from_file(sfp)\n self.assertEqual(k.size, 20)\n kn = self.bucket.new_key('k')\n ks = kn.get_contents_as_string()\n self.assertEqual(ks, content)\n sfp.seek(5)\n k = self.bucket.new_key('k')\n k.set_contents_from_file(sfp)\n self.assertEqual(k.size, 15)\n kn = self.bucket.new_key('k')\n ks = kn.get_contents_as_string()\n self.assertEqual(ks, content[5:])\n sfp.seek(5)\n k = self.bucket.new_key('k')\n k.set_contents_from_file(sfp, size=5)\n self.assertEqual(k.size, 5)\n self.assertEqual(sfp.tell(), 10)\n kn = self.bucket.new_key('k')\n ks = kn.get_contents_as_string()\n self.assertEqual(ks, content[5:10])\n\n def test_set_contents_with_md5(self):\n content = '01234567890123456789'\n sfp = StringIO.StringIO(content)\n k = self.bucket.new_key('k')\n good_md5 = k.compute_md5(sfp)\n k.set_contents_from_file(sfp, md5=good_md5)\n kn = self.bucket.new_key('k')\n ks = kn.get_contents_as_string()\n self.assertEqual(ks, content)\n sfp.seek(5)\n k = self.bucket.new_key('k')\n good_md5 = k.compute_md5(sfp, size=5)\n k.set_contents_from_file(sfp, size=5, md5=good_md5)\n self.assertEqual(sfp.tell(), 10)\n kn = self.bucket.new_key('k')\n ks = kn.get_contents_as_string()\n self.assertEqual(ks, content[5:10])\n k = self.bucket.new_key('k')\n sfp.seek(0)\n hexdig, base64 = k.compute_md5(sfp)\n bad_md5 = (hexdig, base64[3:])\n try:\n k.set_contents_from_file(sfp, md5=bad_md5)\n self.fail('should fail with bad md5')\n except S3ResponseError:\n pass\n\n def test_get_contents_with_md5(self):\n content = '01234567890123456789'\n sfp = StringIO.StringIO(content)\n k = self.bucket.new_key('k')\n k.set_contents_from_file(sfp)\n kn = self.bucket.new_key('k')\n s = kn.get_contents_as_string()\n self.assertEqual(kn.md5, k.md5)\n self.assertEqual(s, content)\n", "method_code": " def set_contents_from_file(self, fp, headers=None, replace=True, cb=None, num_cb=10, policy=None, md5=None, reduced_redundancy=False, query_args=None, encrypt_key=False, size=None):\n \"\"\"\n Store an object in S3 using the name of the Key object as the\n key in S3 and the contents of the file pointed to by 'fp' as the\n contents.\n \n :type fp: file\n :param fp: the file whose contents to upload\n \n :type headers: dict\n :param headers: Additional HTTP headers that will be sent with\n the PUT request.\n \n :type replace: bool\n :param replace: If this parameter is False, the method\n will first check to see if an object exists in the\n bucket with the same key. If it does, it won't\n overwrite it. The default value is True which will\n overwrite the object.\n \n :type cb: function\n :param cb: a callback function that will be called to report\n progress on the upload. The callback should accept\n two integer parameters, the first representing the\n number of bytes that have been successfully\n transmitted to S3 and the second representing the\n size of the to be transmitted object.\n \n :type cb: int\n :param num_cb: (optional) If a callback is specified with the cb\n parameter this parameter determines the granularity\n of the callback by defining the maximum number of\n times the callback will be called during the\n file transfer.\n \n :type policy: :class:`boto.s3.acl.CannedACLStrings`\n :param policy: A canned ACL policy that will be applied to the\n new key in S3.\n \n :type md5: A tuple containing the hexdigest version of the MD5\n checksum of the file as the first element and the\n Base64-encoded version of the plain checksum as the\n second element. This is the same format returned by\n the compute_md5 method.\n :param md5: If you need to compute the MD5 for any reason prior\n to upload, it's silly to have to do it twice so this\n param, if present, will be used as the MD5 values of\n the file. Otherwise, the checksum will be computed.\n \n :type reduced_redundancy: bool\n :param reduced_redundancy: If True, this will set the storage\n class of the new Key to be\n REDUCED_REDUNDANCY. The Reduced Redundancy\n Storage (RRS) feature of S3, provides lower\n redundancy at lower storage cost.\n \n :type encrypt_key: bool\n :param encrypt_key: If True, the new copy of the object will\n be encrypted on the server-side by S3 and\n will be stored in an encrypted form while\n at rest in S3.\n \n :type size: int\n :param size: (optional) The Maximum number of bytes to read from\n the file pointer (fp). This is useful when uploading\n a file in multiple parts where you are splitting the\n file up into different ranges to be uploaded. If not\n specified, the default behaviour is to read all bytes\n from the file pointer. Less bytes may be available.\n \"\"\"\n provider = self.bucket.connection.provider\n headers = headers or {}\n if policy:\n headers[provider.acl_header] = policy\n if encrypt_key:\n headers[provider.server_side_encryption_header] = 'AES256'\n if reduced_redundancy:\n self.storage_class = 'REDUCED_REDUNDANCY'\n if provider.storage_class_header:\n headers[provider.storage_class_header] = self.storage_class\n if hasattr(fp, 'name'):\n self.path = fp.name\n if self.bucket != None:\n if not md5 and provider.supports_chunked_transfer():\n chunked_transfer = True\n self.size = None\n else:\n chunked_transfer = False\n if not md5:\n md5 = self.compute_md5(fp, size)\n size = self.size\n elif size:\n self.size = size\n else:\n spos = fp.tell()\n fp.seek(0, os.SEEK_END)\n self.size = fp.tell() - spos\n fp.seek(spos)\n size = self.size\n self.md5 = md5[0]\n self.base64md5 = md5[1]\n if self.name == None:\n self.name = self.md5\n if not replace:\n if self.bucket.lookup(self.name):\n return\n self.send_file(fp, headers=headers, cb=cb, num_cb=num_cb, query_args=query_args, chunked_transfer=chunked_transfer, size=size)\n ", "context": "class Key(object):\n def set_contents_from_file(self, fp, headers=None, replace=True, cb=None, num_cb=10, policy=None, md5=None, reduced_redundancy=False, query_args=None, encrypt_key=False, size=None): ...\n def __init__(self, bucket=None, name=None): ...\n def __repr__(self): ...\n def __getattr__(self, name): ...\n def __setattr__(self, name, value): ...\n def __iter__(self): ...\n def provider(self): ...\n def get_md5_from_hexdigest(self, md5_hexdigest): ...\n def handle_encryption_headers(self, resp): ...\n def handle_version_headers(self, resp, force=False): ...\n def open_read(self, headers=None, query_args='', override_num_retries=None, response_headers=None): ...\n def open_write(self, headers=None, override_num_retries=None): ...\n def open(self, mode='r', headers=None, query_args=None, override_num_retries=None): ...\n def close(self): ...\n def next(self): ...\n def read(self, size=0): ...\n def change_storage_class(self, new_storage_class, dst_bucket=None): ...\n def copy(self, dst_bucket, dst_key, metadata=None, reduced_redundancy=False, preserve_acl=False, encrypt_key=False): ...\n def startElement(self, name, attrs, connection): ...\n def endElement(self, name, value, connection): ...\n def exists(self): ...\n def delete(self): ...\n def get_metadata(self, name): ...\n def set_metadata(self, name, value): ...\n def update_metadata(self, d): ...\n def set_acl(self, acl_str, headers=None): ...\n def get_acl(self, headers=None): ...\n def get_xml_acl(self, headers=None): ...\n def set_xml_acl(self, acl_str, headers=None): ...\n def set_canned_acl(self, acl_str, headers=None): ...\n def make_public(self, headers=None): ...\n def generate_url(self, expires_in, method='GET', headers=None, query_auth=True, force_http=False, response_headers=None, expires_in_absolute=False): ...\n def send_file(self, fp, headers=None, cb=None, num_cb=10, query_args=None, chunked_transfer=False, size=None): ...\n def compute_md5(self, fp, size=None): ...\n def set_contents_from_stream(self, fp, headers=None, replace=True, cb=None, num_cb=10, policy=None, reduced_redundancy=False, query_args=None, size=None): ...\n def set_contents_from_filename(self, filename, headers=None, replace=True, cb=None, num_cb=10, policy=None, md5=None, reduced_redundancy=False, encrypt_key=False): ...\n def set_contents_from_string(self, s, headers=None, replace=True, cb=None, num_cb=10, policy=None, md5=None, reduced_redundancy=False, encrypt_key=False): ...\n def get_file(self, fp, headers=None, cb=None, num_cb=10, torrent=False, version_id=None, override_num_retries=None, response_headers=None): ...\n def get_torrent_file(self, fp, headers=None, cb=None, num_cb=10): ...\n def get_contents_to_file(self, fp, headers=None, cb=None, num_cb=10, torrent=False, version_id=None, res_download_handler=None, response_headers=None): ...\n def get_contents_to_filename(self, filename, headers=None, cb=None, num_cb=10, torrent=False, version_id=None, res_download_handler=None, response_headers=None): ...\n def get_contents_as_string(self, headers=None, cb=None, num_cb=10, torrent=False, version_id=None, response_headers=None): ...\n def add_email_grant(self, permission, email_address, headers=None): ...\n def add_user_grant(self, permission, user_id, headers=None, display_name=None): ...\n\n self.bucket = bucket\n self.name = name\n self.metadata = {}\n self.cache_control = None\n self.content_type = self.DefaultContentType\n self.content_encoding = None\n self.filename = None\n self.etag = None\n self.is_latest = False\n self.last_modified = None\n self.owner = None\n self.storage_class = 'STANDARD'\n self.md5 = None\n self.base64md5 = None\n self.path = None\n self.resp = None\n self.mode = None\n self.size = None\n self.version_id = None\n self.source_version_id = None\n self.delete_marker = False\n self.encrypted = None\n\n DefaultContentType = 'application/octet-stream'\n BufferSize = 8192\n closed = False\n", "repository": "jasonc1/collide_game_MTURK", "test_name": "test_set_contents_as_file", "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, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000312.py"} {"focal_file": "sorting.py", "focal_class": null, "focal_method": "bubble_sort", "tests": "import unittest\n\nclass Test_bubble_sort(unittest.TestCase):\n def test_bubble_sort(self):\n u_list = [8, 2, 6, 4, 5]\n s_list = [2, 4, 5, 6, 8]\n self.assertEqual(bubble_sort(u_list)['u_list'], s_list)\n", "method_code": "def bubble_sort(u_list=None):\n \"\"\"\n bubble sort algorithm\n :param u_list: unsorted list of numbers\n :return:\n \"\"\"\n logging.debug('Inside bubble_sort')\n start_time = time.perf_counter()\n if u_list is None:\n u_list = [random.randint(1, 100) for _ in range(10)]\n logging.debug(u_list)\n n = len(u_list)\n for i in range(n, 0, -1):\n fully_sorted = True\n for j in range(0, i - 1):\n if u_list[j] > u_list[j + 1]:\n u_list[j], u_list[j + 1] = (u_list[j + 1], u_list[j])\n fully_sorted = False\n if fully_sorted:\n break\n logging.debug(u_list)\n finish_time = time.perf_counter()\n exec_time = finish_time - start_time\n return {'name': 'bubble_sort', 'u_list': u_list, 'exec_time': f'{exec_time:.5f}'}", "context": "def bubble_sort(u_list=None): ...\ndef bubble_sort(u_list=None): ...\ndef insertion_sort(u_list=None): ...\ndef selection_sort(u_list=None): ...\ndef merge(left, right): ...\ndef m_sort(u_list=None): ...\ndef merge_sort(u_list=None): ...\ndef q_sort(u_list=None): ...\ndef quick_sort(u_list=None): ...\ndef main(): ...\n", "repository": "ankushsawant/sorting_algorithms", "test_name": "test_bubble_sort", "smells": [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "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": "sorting.py", "focal_class": null, "focal_method": "insertion_sort", "tests": "import unittest\n\nclass Test_insertion_sort(unittest.TestCase):\n def test_insertion_sort(self):\n u_list = [8, 2, 6, 4, 5]\n s_list = [2, 4, 5, 6, 8]\n self.assertEqual(insertion_sort(u_list)['u_list'], s_list)\n", "method_code": "def insertion_sort(u_list=None):\n \"\"\"\n insertion sort algorithm\n :param u_list: unsorted list of numbers\n :return:\n \"\"\"\n logging.debug('Inside insertion_sort')\n start_time = time.perf_counter()\n if u_list is None:\n u_list = [random.randint(1, 100) for _ in range(10)]\n logging.debug(u_list)\n n = len(u_list)\n for i in range(1, n):\n key_value = u_list[i]\n moved = False\n pos = -1\n for j in range(i - 1, -1, -1):\n if key_value < u_list[j]:\n u_list[j + 1] = u_list[j]\n moved = True\n pos = j\n else:\n break\n if moved:\n u_list[pos] = key_value\n logging.debug(u_list)\n finish = time.perf_counter()\n finish_time = time.perf_counter()\n exec_time = finish_time - start_time\n return {'name': 'insertion_sort', 'u_list': u_list, 'exec_time': f'{exec_time:.5f}'}", "context": "def insertion_sort(u_list=None): ...\ndef bubble_sort(u_list=None): ...\ndef insertion_sort(u_list=None): ...\ndef selection_sort(u_list=None): ...\ndef merge(left, right): ...\ndef m_sort(u_list=None): ...\ndef merge_sort(u_list=None): ...\ndef q_sort(u_list=None): ...\ndef quick_sort(u_list=None): ...\ndef main(): ...\n", "repository": "ankushsawant/sorting_algorithms", "test_name": "test_insertion_sort", "smells": [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "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": "sorting.py", "focal_class": null, "focal_method": "selection_sort", "tests": "import unittest\n\nclass Test_selection_sort(unittest.TestCase):\n def test_selection_sort(self):\n u_list = [8, 2, 6, 4, 5]\n s_list = [2, 4, 5, 6, 8]\n self.assertEqual(selection_sort(u_list)['u_list'], s_list)\n", "method_code": "def selection_sort(u_list=None):\n \"\"\"\n selection sort algorithm\n :param u_list: unsorted list of numbers\n :return:\n \"\"\"\n logging.debug('Inside selection_sort')\n start_time = time.perf_counter()\n if u_list is None:\n u_list = [random.randint(1, 100) for _ in range(10)]\n logging.debug(u_list)\n n = len(u_list)\n for i in range(n):\n min_index = i\n for j in range(i + 1, n):\n if u_list[j] < u_list[min_index]:\n min_index = j\n u_list[i], u_list[min_index] = (u_list[min_index], u_list[i])\n logging.debug(u_list)\n finish = time.perf_counter()\n finish_time = time.perf_counter()\n exec_time = finish_time - start_time\n return {'name': 'selection_sort', 'u_list': u_list, 'exec_time': f'{exec_time:.5f}'}", "context": "def selection_sort(u_list=None): ...\ndef bubble_sort(u_list=None): ...\ndef insertion_sort(u_list=None): ...\ndef selection_sort(u_list=None): ...\ndef merge(left, right): ...\ndef m_sort(u_list=None): ...\ndef merge_sort(u_list=None): ...\ndef q_sort(u_list=None): ...\ndef quick_sort(u_list=None): ...\ndef main(): ...\n", "repository": "ankushsawant/sorting_algorithms", "test_name": "test_selection_sort", "smells": [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "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": "sorting.py", "focal_class": null, "focal_method": "merge", "tests": "import unittest\n\nclass Test_merge(unittest.TestCase):\n def test_merge(self):\n list_a = [3, 5, 7]\n list_b = [2, 4, 6, 8, 10]\n self.assertEqual(merge(list_a, list_b), [2, 3, 4, 5, 6, 7, 8, 10])\n", "method_code": "def merge(left, right):\n \"\"\"\n merge left and right lists into a sorted list\n :param left: left sorted list\n :param right: right sorted list\n :return: sorted merged list\n \"\"\"\n if len(left) == 0:\n return right\n if len(right) == 0:\n return left\n left_index = right_index = 0\n result = []\n while len(result) < len(left) + len(right):\n if left[left_index] <= right[right_index]:\n result.append(left[left_index])\n left_index += 1\n else:\n result.append(right[right_index])\n right_index += 1\n if left_index == len(left):\n result += right[right_index:]\n break\n if right_index == len(right):\n result += left[left_index:]\n break\n return result", "context": "def merge(left, right): ...\ndef bubble_sort(u_list=None): ...\ndef insertion_sort(u_list=None): ...\ndef selection_sort(u_list=None): ...\ndef merge(left, right): ...\ndef m_sort(u_list=None): ...\ndef merge_sort(u_list=None): ...\ndef q_sort(u_list=None): ...\ndef quick_sort(u_list=None): ...\ndef main(): ...\n", "repository": "ankushsawant/sorting_algorithms", "test_name": "test_merge", "smells": [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000316.py"} {"focal_file": "sorting.py", "focal_class": null, "focal_method": "m_sort", "tests": "import unittest\n\nclass Test_m_sort(unittest.TestCase):\n def test_m_sort(self):\n u_list = [8, 2, 6, 4, 5]\n s_list = [2, 4, 5, 6, 8]\n self.assertEqual(m_sort(u_list), s_list)\n", "method_code": "def m_sort(u_list=None):\n \"\"\"\n recursive merge sort algorithm\n :param u_list: unsorted list of numbers\n :return:\n \"\"\"\n if len(u_list) < 2:\n return u_list\n mid = len(u_list) // 2\n return merge(m_sort(u_list[:mid]), m_sort(u_list[mid:]))", "context": "def m_sort(u_list=None): ...\ndef bubble_sort(u_list=None): ...\ndef insertion_sort(u_list=None): ...\ndef selection_sort(u_list=None): ...\ndef merge(left, right): ...\ndef m_sort(u_list=None): ...\ndef merge_sort(u_list=None): ...\ndef q_sort(u_list=None): ...\ndef quick_sort(u_list=None): ...\ndef main(): ...\n", "repository": "ankushsawant/sorting_algorithms", "test_name": "test_m_sort", "smells": [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000317.py"} {"focal_file": "sorting.py", "focal_class": null, "focal_method": "q_sort", "tests": "import unittest\n\nclass Test_q_sort(unittest.TestCase):\n def test_q_sort(self):\n u_list = [8, 2, 6, 4, 5]\n s_list = [2, 4, 5, 6, 8]\n self.assertEqual(q_sort(u_list), s_list)\n", "method_code": "def q_sort(u_list=None):\n \"\"\"\n recursive quick sort algorithm\n :param u_list: unsorted list of numbers\n :return:\n \"\"\"\n if len(u_list) < 2:\n return u_list\n low, mid, high = ([], [], [])\n pivot = u_list[random.randint(0, len(u_list) - 1)]\n for num in u_list:\n if num < pivot:\n low.append(num)\n elif num == pivot:\n mid.append(num)\n else:\n high.append(num)\n return q_sort(low) + mid + q_sort(high)", "context": "def q_sort(u_list=None): ...\ndef bubble_sort(u_list=None): ...\ndef insertion_sort(u_list=None): ...\ndef selection_sort(u_list=None): ...\ndef merge(left, right): ...\ndef m_sort(u_list=None): ...\ndef merge_sort(u_list=None): ...\ndef q_sort(u_list=None): ...\ndef quick_sort(u_list=None): ...\ndef main(): ...\n", "repository": "ankushsawant/sorting_algorithms", "test_name": "test_q_sort", "smells": [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000318.py"} {"focal_file": "plugin.program.shell/resources/lib/simplejson/__init__.py", "focal_class": null, "focal_method": "dumps", "tests": "import unittest\n\nclass Test_dumps(unittest.TestCase):\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\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", "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, **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 *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 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 bigint_as_string) and (not sort_keys) and (not item_sort_key) and (not for_json) and (not ignore_nan) 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, bigint_as_string=bigint_as_string, sort_keys=sort_keys, item_sort_key=item_sort_key, for_json=for_json, ignore_nan=ignore_nan, **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, **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, **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, **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": "dbsr/_xbmc", "test_name": "test_tuple_array_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_000319.py"} {"focal_file": "plugin.program.shell/resources/lib/simplejson/__init__.py", "focal_class": null, "focal_method": "dump", "tests": "import unittest\n\nclass Test_dump(unittest.TestCase):\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\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", "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, **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 *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 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 bigint_as_string) and (not item_sort_key) and (not for_json) and (not ignore_nan) 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, bigint_as_string=bigint_as_string, sort_keys=sort_keys, item_sort_key=item_sort_key, for_json=for_json, ignore_nan=ignore_nan, **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, **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, **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, **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": "dbsr/_xbmc", "test_name": "test_tuple_array_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_000320.py"} {"focal_file": "TestAutomation/project/build/lib/fuzzywuzzy/fuzz.py", "focal_class": null, "focal_method": "partial_token_sort_ratio", "tests": "import unittest\n\nclass Test_partial_token_sort_ratio(unittest.TestCase):\n def testPartialTokenSortRatio(self):\n self.assertEqual(fuzz.partial_token_sort_ratio(self.s1, self.s1a), 100)\n self.assertEqual(fuzz.partial_token_sort_ratio(self.s4, self.s5), 100)\n", "method_code": "def partial_token_sort_ratio(s1, s2, force_ascii=True):\n \"\"\"Return the ratio of the most similar substring as a number between\n 0 and 100 but sorting the token before comparing.\n \"\"\"\n return _token_sort(s1, s2, partial=True, force_ascii=force_ascii)", "context": "def partial_token_sort_ratio(s1, s2, force_ascii=True): ...\ndef ratio(s1, s2): ...\ndef partial_ratio(s1, s2): ...\ndef _process_and_sort(s, force_ascii): ...\ndef _token_sort(s1, s2, partial=True, force_ascii=True): ...\ndef token_sort_ratio(s1, s2, force_ascii=True): ...\ndef partial_token_sort_ratio(s1, s2, force_ascii=True): ...\ndef _token_set(s1, s2, partial=True, force_ascii=True): ...\ndef token_set_ratio(s1, s2, force_ascii=True): ...\ndef partial_token_set_ratio(s1, s2, force_ascii=True): ...\ndef QRatio(s1, s2, force_ascii=True): ...\ndef UQRatio(s1, s2): ...\ndef WRatio(s1, s2, force_ascii=True): ...\ndef UWRatio(s1, s2): ...\n", "repository": "CSCI-362-02-2015/The-Darkness", "test_name": "testPartialTokenSortRatio", "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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000321.py"} {"focal_file": "TestAutomation/project/build/lib/fuzzywuzzy/fuzz.py", "focal_class": null, "focal_method": "partial_token_set_ratio", "tests": "import unittest\n\nclass Test_partial_token_set_ratio(unittest.TestCase):\n def testPartialTokenSetRatio(self):\n self.assertEqual(fuzz.partial_token_set_ratio(self.s4, self.s7), 100)\n", "method_code": "def partial_token_set_ratio(s1, s2, force_ascii=True):\n return _token_set(s1, s2, partial=True, force_ascii=force_ascii)", "context": "def partial_token_set_ratio(s1, s2, force_ascii=True): ...\ndef ratio(s1, s2): ...\ndef partial_ratio(s1, s2): ...\ndef _process_and_sort(s, force_ascii): ...\ndef _token_sort(s1, s2, partial=True, force_ascii=True): ...\ndef token_sort_ratio(s1, s2, force_ascii=True): ...\ndef partial_token_sort_ratio(s1, s2, force_ascii=True): ...\ndef _token_set(s1, s2, partial=True, force_ascii=True): ...\ndef token_set_ratio(s1, s2, force_ascii=True): ...\ndef partial_token_set_ratio(s1, s2, force_ascii=True): ...\ndef QRatio(s1, s2, force_ascii=True): ...\ndef UQRatio(s1, s2): ...\ndef WRatio(s1, s2, force_ascii=True): ...\ndef UWRatio(s1, s2): ...\n", "repository": "CSCI-362-02-2015/The-Darkness", "test_name": "testPartialTokenSetRatio", "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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000322.py"} {"focal_file": "TestAutomation/project/src/mercurial/util.py", "focal_class": "atomictempfile", "focal_method": "discard", "tests": "import unittest\n\nclass Test_atomictempfile_discard(unittest.TestCase):\n def test2_discard(self):\n if os.path.exists('foo'):\n os.remove('foo')\n file = atomictempfile('foo')\n dir, basename = os.path.split(file._tempname)\n file.write('yo\\n')\n file.discard()\n self.assertFalse(os.path.isfile('foo'))\n self.assertTrue(basename not in os.listdir('.'))\n\n def test2_discard(self):\n if os.path.exists('foo'):\n os.remove('foo')\n file = atomictempfile('foo')\n dir, basename = os.path.split(file._tempname)\n file.write('yo\\n')\n file.discard()\n self.assertFalse(os.path.isfile('foo'))\n self.assertTrue(basename not in os.listdir('.'))\n", "method_code": " def discard(self):\n if not self._fp.closed:\n try:\n os.unlink(self._tempname)\n except OSError:\n pass\n self._fp.close()\n ", "context": "class atomictempfile(object):\n def discard(self): ...\n def __init__(self, name, mode='w+b', createmode=None): ...\n def close(self): ...\n def __del__(self): ...\n\n self.__name = name\n self._tempname = mktempcopy(name, emptyok='w' in mode, createmode=createmode)\n self._fp = posixfile(self._tempname, mode)\n self.write = self._fp.write\n self.seek = self._fp.seek\n self.tell = self._fp.tell\n self.fileno = self._fp.fileno\n", "repository": "CSCI-362-02-2015/RedTeam", "test_name": "test2_discard", "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_000323.py"} {"focal_file": "mercurial-3.6.2/mercurial/manifest.py", "focal_class": null, "focal_method": "setflag", "tests": "import unittest\n\nclass Test_setflag(unittest.TestCase):\n def testSetFlag(self):\n want = 'x'\n m = self.parsemanifest(EMTPY_MANIFEST)\n m['a'] = BIN_HASH_1\n m.setflag('a', want)\n self.assertEqual(want, m.flags('a'))\n self.assertEqual('a\\x00' + HASH_1 + want + '\\n', m.text())\n m = self.parsemanifest(A_SHORT_MANIFEST)\n m['a'] = BIN_HASH_1\n m.setflag('a', want)\n self.assertEqual(want, m.flags('a'))\n self.assertEqual('a\\x00' + HASH_1 + want + '\\n' + A_SHORT_MANIFEST, m.text())\n\n def testSetFlag(self):\n want = 'x'\n m = self.parsemanifest(EMTPY_MANIFEST)\n m['a'] = BIN_HASH_1\n m.setflag('a', want)\n self.assertEqual(want, m.flags('a'))\n self.assertEqual('a\\x00' + HASH_1 + want + '\\n', m.text())\n m = self.parsemanifest(A_SHORT_MANIFEST)\n m['a'] = BIN_HASH_1\n m.setflag('a', want)\n self.assertEqual(want, m.flags('a'))\n self.assertEqual('a\\x00' + HASH_1 + want + '\\n' + A_SHORT_MANIFEST, m.text())\n", "method_code": " def setflag(self, key, flag):\n self._lm[key] = (self[key], flag)\n ", "context": "class manifestdict(object):\n def setflag(self, key, flag): ...\n def __init__(self, data=''): ...\n def __getitem__(self, key): ...\n def find(self, key): ...\n def __len__(self): ...\n def __setitem__(self, key, node): ...\n def __contains__(self, key): ...\n def __delitem__(self, key): ...\n def __iter__(self): ...\n def iterkeys(self): ...\n def keys(self): ...\n def filesnotin(self, m2): ...\n def _dirs(self): ...\n def dirs(self): ...\n def hasdir(self, dir): ...\n def _filesfastpath(self, match): ...\n def walk(self, match): ...\n def matches(self, match): ...\n def diff(self, m2, clean=False): ...\n def get(self, key, default=None): ...\n def flags(self, key, default=''): ...\n def copy(self): ...\n def iteritems(self): ...\n def text(self, usemanifestv2=False): ...\n def fastdelta(self, base, changes): ...\n", "repository": "CSCI-362-02-2015/RedTeam", "test_name": "testSetFlag", "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_000324.py"} {"focal_file": "mercurial-3.6.2/mercurial/manifest.py", "focal_class": null, "focal_method": "matches", "tests": "import unittest\n\nclass Test_matches(unittest.TestCase):\n def testMatchesCwd(self):\n \"\"\"Tests matches() on a relpath match with the current directory ('.')\n when not in the root directory.\"\"\"\n m = self.parsemanifest(A_DEEPER_MANIFEST)\n match = matchmod.match('/', 'a/b', ['.'], default='relpath')\n m2 = m.matches(match)\n self.assertEqual(['a/b/c/bar.py', 'a/b/c/bar.txt', 'a/b/c/foo.py', 'a/b/c/foo.txt', 'a/b/d/baz.py', 'a/b/d/qux.py', 'a/b/d/ten.txt', 'a/b/dog.py', 'a/b/fish.py'], m2.keys())\n\n def testMatchesCwd(self):\n \"\"\"Tests matches() on a relpath match with the current directory ('.')\n when not in the root directory.\"\"\"\n m = self.parsemanifest(A_DEEPER_MANIFEST)\n match = matchmod.match('/', 'a/b', ['.'], default='relpath')\n m2 = m.matches(match)\n self.assertEqual(['a/b/c/bar.py', 'a/b/c/bar.txt', 'a/b/c/foo.py', 'a/b/c/foo.txt', 'a/b/d/baz.py', 'a/b/d/qux.py', 'a/b/d/ten.txt', 'a/b/dog.py', 'a/b/fish.py'], m2.keys())\n", "method_code": " def matches(self, match):\n \"\"\"generate a new manifest filtered by the match argument\"\"\"\n if match.always():\n return self.copy()\n if self._filesfastpath(match):\n m = manifestdict()\n lm = self._lm\n for fn in match.files():\n if fn in lm:\n m._lm[fn] = lm[fn]\n return m\n m = manifestdict()\n m._lm = self._lm.filtercopy(match)\n return m\n ", "context": "class manifestdict(object):\n def matches(self, match): ...\n def __init__(self, data=''): ...\n def __getitem__(self, key): ...\n def find(self, key): ...\n def __len__(self): ...\n def __setitem__(self, key, node): ...\n def __contains__(self, key): ...\n def __delitem__(self, key): ...\n def __iter__(self): ...\n def iterkeys(self): ...\n def keys(self): ...\n def filesnotin(self, m2): ...\n def _dirs(self): ...\n def dirs(self): ...\n def hasdir(self, dir): ...\n def _filesfastpath(self, match): ...\n def walk(self, match): ...\n def diff(self, m2, clean=False): ...\n def setflag(self, key, flag): ...\n def get(self, key, default=None): ...\n def flags(self, key, default=''): ...\n def copy(self): ...\n def iteritems(self): ...\n def text(self, usemanifestv2=False): ...\n def fastdelta(self, base, changes): ...\n", "repository": "CSCI-362-02-2015/RedTeam", "test_name": "testMatchesCwd", "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_000325.py"} {"focal_file": "mercurial-3.6.2/mercurial/simplemerge.py", "focal_class": null, "focal_method": "find_unconflicted", "tests": "import unittest\n\nclass Test_find_unconflicted(unittest.TestCase):\n def test_no_conflicts(self):\n \"\"\"No conflicts because only one side changed\"\"\"\n m3 = Merge3(['aaa', 'bbb'], ['aaa', '111', 'bbb'], ['aaa', 'bbb'])\n self.assertEquals(m3.find_unconflicted(), [(0, 1), (1, 2)])\n self.assertEquals(list(m3.find_sync_regions()), [(0, 1, 0, 1, 0, 1), (1, 2, 2, 3, 1, 2), (2, 2, 3, 3, 2, 2)])\n self.assertEquals(list(m3.merge_regions()), [('unchanged', 0, 1), ('a', 1, 2), ('unchanged', 1, 2)])\n\n def test_no_conflicts(self):\n \"\"\"No conflicts because only one side changed\"\"\"\n m3 = Merge3(['aaa', 'bbb'], ['aaa', '111', 'bbb'], ['aaa', 'bbb'])\n self.assertEquals(m3.find_unconflicted(), [(0, 1), (1, 2)])\n self.assertEquals(list(m3.find_sync_regions()), [(0, 1, 0, 1, 0, 1), (1, 2, 2, 3, 1, 2), (2, 2, 3, 3, 2, 2)])\n self.assertEquals(list(m3.merge_regions()), [('unchanged', 0, 1), ('a', 1, 2), ('unchanged', 1, 2)])\n", "method_code": " def find_unconflicted(self):\n \"\"\"Return a list of ranges in base that are not conflicted.\"\"\"\n am = mdiff.get_matching_blocks(self.basetext, self.atext)\n bm = mdiff.get_matching_blocks(self.basetext, self.btext)\n unc = []\n while am and bm:\n a1 = am[0][0]\n a2 = a1 + am[0][2]\n b1 = bm[0][0]\n b2 = b1 + bm[0][2]\n i = intersect((a1, a2), (b1, b2))\n if i:\n unc.append(i)\n if a2 < b2:\n del am[0]\n else:\n del bm[0]\n return unc\n ", "context": "class Merge3Text(object):\n def find_unconflicted(self): ...\n def __init__(self, basetext, atext, btext, base=None, a=None, b=None): ...\n def merge_lines(self, name_a=None, name_b=None, name_base=None, start_marker='<<<<<<<', mid_marker='=======', end_marker='>>>>>>>', base_marker=None, localorother=None): ...\n def merge_groups(self): ...\n def merge_regions(self): ...\n def find_sync_regions(self): ...\n\n self.basetext = basetext\n self.atext = atext\n self.btext = btext\n self.base = base\n self.a = a\n self.b = b\n", "repository": "CSCI-362-02-2015/RedTeam", "test_name": "test_no_conflicts", "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_000326.py"} {"focal_file": "mercurial-3.6.2/mercurial/lock.py", "focal_class": "mercurial.lock.lock", "focal_method": "lock", "tests": "import unittest\n\nclass Test_mercurial_lock_lock_lock(unittest.TestCase):\n def testrecursivelock(self):\n state = teststate(self, tempfile.mkdtemp(dir=os.getcwd()))\n lock = state.makelock()\n state.assertacquirecalled(True)\n state.resetacquirefn()\n lock.lock()\n state.assertacquirecalled(False)\n lock.release()\n state.assertreleasecalled(False)\n state.assertpostreleasecalled(False)\n state.assertlockexists(True)\n lock.release()\n state.assertreleasecalled(True)\n state.assertpostreleasecalled(True)\n state.assertlockexists(False)\n", "method_code": " def lock(self):\n timeout = self.timeout\n while True:\n try:\n self._trylock()\n return self.timeout - timeout\n except error.LockHeld as inst:\n if timeout != 0:\n time.sleep(1)\n if timeout > 0:\n timeout -= 1\n continue\n raise error.LockHeld(errno.ETIMEDOUT, inst.filename, self.desc, inst.locker)\n ", "context": "class lock(object):\n def lock(self): ...\n def __init__(self, vfs, file, timeout=-1, releasefn=None, acquirefn=None, desc=None, inheritchecker=None, parentlock=None): ...\n def __del__(self): ...\n def _getpid(self): ...\n def _trylock(self): ...\n def _readlock(self): ...\n def _testlock(self, locker): ...\n def testlock(self): ...\n def inherit(self): ...\n def release(self): ...\n\n self.vfs = vfs\n self.f = file\n self.held = 0\n self.timeout = timeout\n self.releasefn = releasefn\n self.acquirefn = acquirefn\n self.desc = desc\n self._inheritchecker = inheritchecker\n self.parentlock = parentlock\n self._parentheld = False\n self._inherited = False\n self.postrelease = []\n self.pid = self._getpid()\n self.delay = self.lock()\n\n _host = None\n", "repository": "CSCI-362-02-2015/RedTeam", "test_name": "testrecursivelock", "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_000327.py"} {"focal_file": "mercurial-3.6.2/mercurial/lock.py", "focal_class": null, "focal_method": "inherit", "tests": "import unittest\n\nclass Test_inherit(unittest.TestCase):\n def testinheritlock(self):\n d = tempfile.mkdtemp(dir=os.getcwd())\n parentstate = teststate(self, d)\n parentlock = parentstate.makelock()\n parentstate.assertacquirecalled(True)\n with parentlock.inherit() as lockname:\n parentstate.assertreleasecalled(True)\n parentstate.assertpostreleasecalled(False)\n parentstate.assertlockexists(True)\n childstate = teststate(self, d, pidoffset=1)\n childlock = childstate.makelock(parentlock=lockname)\n childstate.assertacquirecalled(True)\n childlock.release()\n childstate.assertreleasecalled(True)\n childstate.assertpostreleasecalled(False)\n childstate.assertlockexists(True)\n parentstate.resetacquirefn()\n parentstate.assertacquirecalled(True)\n parentlock.release()\n parentstate.assertreleasecalled(True)\n parentstate.assertpostreleasecalled(True)\n parentstate.assertlockexists(False)\n", "method_code": " def inherit(self):\n \"\"\"context for the lock to be inherited by a Mercurial subprocess.\n \n Yields a string that will be recognized by the lock in the subprocess.\n Communicating this string to the subprocess needs to be done separately\n -- typically by an environment variable.\n \"\"\"\n if not self.held:\n raise error.LockInheritanceContractViolation('inherit can only be called while lock is held')\n if self._inherited:\n raise error.LockInheritanceContractViolation('inherit cannot be called while lock is already inherited')\n if self._inheritchecker is not None:\n self._inheritchecker()\n if self.releasefn:\n self.releasefn()\n if self._parentheld:\n lockname = self.parentlock\n else:\n lockname = '%s:%s' % (lock._host, self.pid)\n self._inherited = True\n try:\n yield lockname\n finally:\n if self.acquirefn:\n self.acquirefn()\n self._inherited = False\n ", "context": "class lock(object):\n @contextlib.contextmanager\n def inherit(self): ...\n def __init__(self, vfs, file, timeout=-1, releasefn=None, acquirefn=None, desc=None, inheritchecker=None, parentlock=None): ...\n def __del__(self): ...\n def _getpid(self): ...\n def lock(self): ...\n def _trylock(self): ...\n def _readlock(self): ...\n def _testlock(self, locker): ...\n def testlock(self): ...\n def release(self): ...\n\n self.vfs = vfs\n self.f = file\n self.held = 0\n self.timeout = timeout\n self.releasefn = releasefn\n self.acquirefn = acquirefn\n self.desc = desc\n self._inheritchecker = inheritchecker\n self.parentlock = parentlock\n self._parentheld = False\n self._inherited = False\n self.postrelease = []\n self.pid = self._getpid()\n self.delay = self.lock()\n\n _host = None\n", "repository": "CSCI-362-02-2015/RedTeam", "test_name": "testinheritlock", "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": "signal.py", "focal_class": null, "focal_method": "normalize", "tests": "import unittest\n\nclass Test_normalize(unittest.TestCase):\n def test_normalize_energy(self):\n t = np.arange(6) * 1e-06\n s = Signal(np.ones(6), index=t)\n npt.assert_allclose(s.normalize('energy')[0], np.sqrt(1 / 5e-06))\n\n def test_normalize_max(self):\n t = np.arange(6) * 1e-06\n s = Signal(2 * np.ones(6), index=t)\n npt.assert_allclose(s.normalize('max')[0], (1.0,))\n", "method_code": " def normalize(self, option='max', inplace=False):\n \"\"\"\n Normalizes the signal according to a given option.\n \n Parameters\n ----------\n option: string, optional\n Method to be used to normalize the signal. The possible options are:\n \n * *'max' (Default)* : Divide by the maximum of the signal, so that the normalized\n maximum has an amplitude of 1. :math:`\\\\max \\\\mathbf{s}`\n \n * *'energy'*: Divide by the signal energy: :math:`\\\\sum_{i=1}^N s_i^2`\n \n * *'rms'* : The normalization is given by: :math:`\\\\sqrt{\\\\frac{\\\\sum_{i=1}^N s_i^2}{N}}`\n \n inplace : bool\n Change the Signal in place.\n Returns\n -------\n : Signal\n Signal with normalized amplitude.\n \"\"\"\n if option == 'energy':\n fact = np.sqrt(self.energy())\n elif option == 'max':\n fact = np.max(np.abs(self.values))\n elif option == 'rms':\n fact = np.sqrt(self.energy() / len(self))\n else:\n raise ValueError('Unknown option value.')\n if inplace:\n self[:] = self / fact\n return self\n else:\n return self / fact\n ", "context": "class Signal(pd.Series):\n def normalize(self, option='max', inplace=False): ...\n def __init__(self, data=None, index=None, *args, **kwargs): ...\n def _constructor(self): ...\n def __hash__(self): ...\n def __call__(self, key=None, ts=None, **kwargs): ...\n def window(self, index1=None, index2=None, is_positional=False, win_fcn='boxcar', fftbins=False): ...\n def peaks(self, threshold=None, min_dist=None, by_envelop=False): ...\n def pad(self, extent, fill=0.0, position='split'): ...\n def segment(self, threshold, pulse_width, min_dist=None, holdoff=None, win_fcn='boxcar'): ...\n def operate(self, option='', norm_method='max', inplace=False): ...\n def fft(self, nfft=None, ssb=False): ...\n def limits(self, thresh=None): ...\n def attenuation(self, a, d, pw, f=None, thres=None): ...\n def tof(self, method='corr', ref=None): ...\n def spectrogram(self, width, overlap=0, **kwargs): ...\n def psd(self, width, overlap=0, **kwargs): ...\n def sparse_pse(self, threshold, fc, pulse_width, overlap=0, nfft=None, win_fcn='boxcar'): ...\n def pse(self, fc, pulse_width, overlap=0, nfft=None, win_fcn='boxcar'): ...\n def coherence(self, other, width, overlap=0, **kwargs): ...\n def filter_freq(self, cutoff, option='lp', win_fcn='boxcar'): ...\n def frequency(self, option='center', threshold=None, nfft=None): ...\n def bandwidth(self, threshold=None, nfft=None): ...\n def maxof(self, option='peak'): ...\n def energy(self): ...\n def remove_mean(self): ...\n def ts(self): ...\n def extent(self): ...\n def fs(self): ...\n", "repository": "dibgerge/utkit", "test_name": "test_normalize_energy", "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_000329.py"} {"focal_file": "signal2d.py", "focal_class": null, "focal_method": "shift_axes", "tests": "import unittest\n\nclass Test_shift_axes(unittest.TestCase):\n def test_shift_axis_axisnone(self):\n s = Signal2D(np.ones(12).reshape(4, 3), index=[0.0, 1.0, 2.0, 3.0], columns=[0.0, 1.0, 2.0])\n s2 = Signal2D(np.ones(12).reshape(4, 3), index=[-1.0, 0.0, 1.0, 2.0], columns=[-1.0, 0.0, 1.0])\n pdt.assert_frame_equal(s.shift_axes(1), s2)\n\n def test_shift_axis_axisnone2(self):\n s = Signal2D(np.ones(12).reshape(4, 3), index=[0.0, 1.0, 2.0, 3.0], columns=[0.0, 1.0, 2.0])\n s2 = Signal2D(np.ones(12).reshape(4, 3), index=[-1.0, 0.0, 1.0, 2.0], columns=[-2.0, -1.0, 0.0])\n pdt.assert_frame_equal(s.shift_axes([1, 2]), s2)\n\n def test_shift_axis_axisindex(self):\n s = Signal2D(np.ones(12).reshape(4, 3), index=[0.0, 1.0, 2.0, 3.0], columns=[0.0, 1.0, 2.0])\n s2 = Signal2D(np.ones(12).reshape(4, 3), index=[-1.0, 0.0, 1.0, 2.0], columns=[0.0, 1.0, 2.0])\n pdt.assert_frame_equal(s.shift_axes(1, axes='y'), s2)\n\n def test_shift_axis_axisindex2(self):\n s = Signal2D(np.ones(12).reshape(4, 3), index=[0.0, 1.0, 2.0, 3.0], columns=[0.0, 1.0, 2.0])\n s2 = Signal2D(np.ones(12).reshape(4, 3), index=[-1.0, 0.0, 1.0, 2.0], columns=[0.0, 1.0, 2.0])\n pdt.assert_frame_equal(s.shift_axes(1, axes=0), s2)\n\n def test_shift_axis_columns(self):\n s = Signal2D(np.ones(12).reshape(4, 3), index=[0.0, 1.0, 2.0, 3.0], columns=[0.0, 1.0, 2.0])\n s2 = Signal2D(np.ones(12).reshape(4, 3), index=[0.0, 1.0, 2.0, 3.0], columns=[-1.0, 0.0, 1.0])\n pdt.assert_frame_equal(s.shift_axes(1, axes='x'), s2)\n\n def test_shift_axis_columns2(self):\n s = Signal2D(np.ones(12).reshape(4, 3), index=[0.0, 1.0, 2.0, 3.0], columns=[0.0, 1.0, 2.0])\n s2 = Signal2D(np.ones(12).reshape(4, 3), index=[0.0, 1.0, 2.0, 3.0], columns=[-1.0, 0.0, 1.0])\n pdt.assert_frame_equal(s.shift_axes(1, axes=1), s2)\n", "method_code": " def shift_axes(self, shift, axes=None):\n \"\"\"\n Shifts an axis (or both axis) by a specified amount.\n \n Parameters\n ----------\n shift : float, array_like\n The amount to shift the axis. If *shift* is an array, it should have the same size as\n *axes*, if specified.\n \n axes : int, string, array_like, optional\n The axes to shift. If not specified, all axes will be shifted by the given *shift*\n value.\n \n Returns\n -------\n : Signal2D\n A new Signal2D with shifted axes.\n \"\"\"\n axes = self._get_axes_numbers(axes)\n shift = self._cook_args(shift, axes, [0.0, 0.0])\n return Signal2D(self.values, index=self.index - shift[0], columns=self.columns - shift[1])\n ", "context": "class Signal2D(pd.DataFrame):\n def shift_axes(self, shift, axes=None): ...\n def __init__(self, data=None, index=None, columns=None, dtype=None, copy=False): ...\n def _constructor(self): ...\n def _constructor_sliced(self): ...\n def _constructor_expanddim(self): ...\n def _get_axes_numbers(self, axes): ...\n def __call__(self, index=None, columns=None, **kwargs): ...\n def reset_rate(self, ts, axes=None, **kwargs): ...\n def operate(self, option='', norm='max', axis=0): ...\n def _cook_args(self, val, axes, default=None): ...\n def fft(self, ssb=False, axes=None, shape=None, **kwargs): ...\n def window(self, index1=None, index2=None, axes=None, win_fcn='boxcar'): ...\n def filter_freq(self, low_freq=None, high_freq=None, axes=None, win_fcn='boxcar'): ...\n def scale_axes(self, scale, axes=None): ...\n def skew(self, angle, axes=1, interpolate=False, ts=None, **kwargs): ...\n def pad(self, extent, axes=None, fill=0.0, position='split'): ...\n def pad_coords(self, index=None, columns=None, fill=0.0): ...\n def flip(self, axes=None): ...\n def roll(self, value, axes=None): ...\n def max_point(self): ...\n def flatten(self): ...\n def remove_mean(self, axes=None): ...\n def extract(self, axis=1, option='max'): ...\n def tof(self, method='corr'): ...\n def attenuation(self, a, d, c=None, f=None): ...\n def ts(self): ...\n def x(self): ...\n def y(self): ...\n def extent(self): ...\n", "repository": "dibgerge/utkit", "test_name": "test_shift_axis_axisnone", "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_000330.py"} {"focal_file": "signal2d.py", "focal_class": null, "focal_method": "window", "tests": "import unittest\n\nclass Test_window(unittest.TestCase):\n def test_window_axis1(self):\n t = np.arange(6) * 1e-06\n x = np.arange(6) * 0.001\n s = Signal2D(np.ones((6, 6)), index=t, columns=x)\n swindowed = Signal2D([[0.0, 0.0, 1.0, 1.0, 1.0, 0.0], [0.0, 0.0, 1.0, 1.0, 1.0, 0.0], [0.0, 0.0, 1.0, 1.0, 1.0, 0.0], [0.0, 0.0, 1.0, 1.0, 1.0, 0.0], [0.0, 0.0, 1.0, 1.0, 1.0, 0.0], [0.0, 0.0, 1.0, 1.0, 1.0, 0.0]], index=t, columns=x)\n s = s.window(index1=0.002, index2=0.004, axes=1, win_fcn='boxcar')\n pdt.assert_frame_equal(s, swindowed)\n\n def test_window_axis0(self):\n t = np.arange(6) * 1e-06\n x = np.arange(6) * 0.001\n s = Signal2D(np.ones((6, 6)), index=t, columns=x)\n swindowed = Signal2D([[0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], index=t, columns=x)\n s = s.window(index1=2e-06, index2=4e-06, axes=0, win_fcn='boxcar')\n pdt.assert_frame_equal(s, swindowed)\n\n def test_window_fftbins(self):\n t = np.arange(7) * 1e-06 - 3e-06\n x = np.arange(6) * 0.001\n s = Signal2D(np.ones((7, 6)), index=t, columns=x)\n swindowed = Signal2D([[0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], index=t, columns=x)\n s = s.window(index1=9e-07, index2=2.1e-06, axes=0, fftbins=True, win_fcn='boxcar')\n pdt.assert_frame_equal(s, swindowed)\n", "method_code": " def window(self, index1=None, index2=None, axes=None, win_fcn='boxcar'):\n \"\"\"\n Applies a window to the signal within a given time range.\n \n Parameters\n ----------\n index1 : {float, int, array_like}, optional\n The start index/position of the window. Default value is minimum of index and columns.\n If *index1* is a two_element array, then it specifies the start positions for both axes.\n \n index2 : {float, int, array_like}, optional\n The end index/position of the window. Default value is maximum of index and columns.\n If *index2* is a two_element array, then it specifies the end positions for both axes.\n \n axes : {int, string, array_like}, optional\n The axes names/numbers along which to apply the window.\n \n win_fcn : string/float/tuple, optional\n The type of window to create. See the function :func:`scipy.signal.get_window()` for\n a complete list of available windows, and how to pass extra parameters for a\n specific window function.\n \n Returns\n -------\n Signal:\n The windowed Signal signal.\n \n Note\n ----\n If the window requires no parameters, then `win_fcn` can be a string.\n If the window requires parameters, then `win_fcn` must be a tuple\n with the first argument the string name of the window, and the next\n arguments the needed parameters. If `win_fcn` is a floating point\n number, it is interpreted as the beta parameter of the kaiser window.\n \"\"\"\n axes = self._get_axes_numbers(axes)\n index1 = self._cook_args(index1, axes)\n index2 = self._cook_args(index2, axes)\n if index1 is None:\n index1 = [self.axes[i][0] for i in axes]\n if index2 is None:\n index2 = [self.axes[i][-1] for i in axes]\n win2d = Signal2D(0, index=self.index, columns=self.columns)\n win = []\n for ax in sorted(axes):\n st, en = self.axes[ax].slice_locs(index1[ax], index2[ax])\n win.append(get_window(win_fcn, en - st, fftbins=False))\n if len(win) == 2:\n win = np.sqrt(np.outer(win[0], win[1]))\n win2d.loc[index1[0]:index2[0], index1[1]:index2[1]] = win\n elif len(win) == 1:\n win = np.repeat(win[0][:, np.newaxis], self.shape[axes[0] - 1], axes[0] - 1)\n win_slice = win2d.select(lambda x: (x >= index1[0]) & (x <= index2[0]), axis=axes[0])\n win_slice.loc[:] = win\n win2d.update(win_slice)\n else:\n raise ValueError('Could not make window.')\n return self * win2d\n ", "context": "class Signal2D(pd.DataFrame):\n def window(self, index1=None, index2=None, axes=None, win_fcn='boxcar'): ...\n def __init__(self, data=None, index=None, columns=None, dtype=None, copy=False): ...\n def _constructor(self): ...\n def _constructor_sliced(self): ...\n def _constructor_expanddim(self): ...\n def _get_axes_numbers(self, axes): ...\n def __call__(self, index=None, columns=None, **kwargs): ...\n def reset_rate(self, ts, axes=None, **kwargs): ...\n def operate(self, option='', norm='max', axis=0): ...\n def _cook_args(self, val, axes, default=None): ...\n def fft(self, ssb=False, axes=None, shape=None, **kwargs): ...\n def filter_freq(self, low_freq=None, high_freq=None, axes=None, win_fcn='boxcar'): ...\n def shift_axes(self, shift, axes=None): ...\n def scale_axes(self, scale, axes=None): ...\n def skew(self, angle, axes=1, interpolate=False, ts=None, **kwargs): ...\n def pad(self, extent, axes=None, fill=0.0, position='split'): ...\n def pad_coords(self, index=None, columns=None, fill=0.0): ...\n def flip(self, axes=None): ...\n def roll(self, value, axes=None): ...\n def max_point(self): ...\n def flatten(self): ...\n def remove_mean(self, axes=None): ...\n def extract(self, axis=1, option='max'): ...\n def tof(self, method='corr'): ...\n def attenuation(self, a, d, c=None, f=None): ...\n def ts(self): ...\n def x(self): ...\n def y(self): ...\n def extent(self): ...\n", "repository": "dibgerge/utkit", "test_name": "test_window_axis1", "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_000331.py"} {"focal_file": "signal2d.py", "focal_class": null, "focal_method": "_get_axes_numbers", "tests": "import unittest\n\nclass Test_get_axes_numbers(unittest.TestCase):\n def test_get_axes_numbers_two_axes(self):\n \"\"\":meth:`_get_axes_numbers` test\"\"\"\n s = Signal2D(np.arange(10))\n ax = s._get_axes_numbers(['x', 'y'])\n self.assertEqual(ax, [1, 0])\n\n def test_get_axes_numbers_two_axes2(self):\n \"\"\":meth:`_get_axes_numbers` test\"\"\"\n s = Signal2D(np.arange(10))\n ax = s._get_axes_numbers([1, 0])\n self.assertEqual(ax, [1, 0])\n\n def test_get_axes_numbers_none_axis(self):\n \"\"\":meth:`_get_axes_numbers` test\"\"\"\n s = Signal2D(np.arange(10))\n ax = s._get_axes_numbers(None)\n self.assertEqual(ax, [0, 1])\n\n def test_get_axes_numbers_one_axis(self):\n \"\"\":meth:`_get_axes_numbers` test\"\"\"\n s = Signal2D(np.arange(10))\n ax = s._get_axes_numbers('x')\n self.assertEqual(ax, [1])\n\n def test_get_axes_numbers_one_axis2(self):\n \"\"\":meth:`_get_axes_numbers` test\"\"\"\n s = Signal2D(np.arange(10))\n ax = s._get_axes_numbers(1)\n self.assertEqual(ax, [1])\n", "method_code": " def _get_axes_numbers(self, axes):\n \"\"\"\n Returns the numbers of axes, given a list of them.\n \n Parameters\n ----------\n axes : int, str, list\n The axes list to be evaluated. axes could be named alias for corresponding axes\n numbers.\n \n Returns\n -------\n : list\n Axes as numbers. If axes was None, all available axes are returned. If axes was a\n scalar, return a list of size one.\n \"\"\"\n if axes is None:\n return [0, 1]\n if isinstance(axes, str):\n return [self._get_axis_number(axes)]\n elif hasattr(axes, '__len__'):\n return [self._get_axis_number(ax) for ax in axes]\n return [axes]\n ", "context": "class Signal2D(pd.DataFrame):\n def _get_axes_numbers(self, axes): ...\n def __init__(self, data=None, index=None, columns=None, dtype=None, copy=False): ...\n def _constructor(self): ...\n def _constructor_sliced(self): ...\n def _constructor_expanddim(self): ...\n def __call__(self, index=None, columns=None, **kwargs): ...\n def reset_rate(self, ts, axes=None, **kwargs): ...\n def operate(self, option='', norm='max', axis=0): ...\n def _cook_args(self, val, axes, default=None): ...\n def fft(self, ssb=False, axes=None, shape=None, **kwargs): ...\n def window(self, index1=None, index2=None, axes=None, win_fcn='boxcar'): ...\n def filter_freq(self, low_freq=None, high_freq=None, axes=None, win_fcn='boxcar'): ...\n def shift_axes(self, shift, axes=None): ...\n def scale_axes(self, scale, axes=None): ...\n def skew(self, angle, axes=1, interpolate=False, ts=None, **kwargs): ...\n def pad(self, extent, axes=None, fill=0.0, position='split'): ...\n def pad_coords(self, index=None, columns=None, fill=0.0): ...\n def flip(self, axes=None): ...\n def roll(self, value, axes=None): ...\n def max_point(self): ...\n def flatten(self): ...\n def remove_mean(self, axes=None): ...\n def extract(self, axis=1, option='max'): ...\n def tof(self, method='corr'): ...\n def attenuation(self, a, d, c=None, f=None): ...\n def ts(self): ...\n def x(self): ...\n def y(self): ...\n def extent(self): ...\n", "repository": "dibgerge/utkit", "test_name": "test_get_axes_numbers_two_axes", "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_000332.py"} {"focal_file": "signal3d.py", "focal_class": null, "focal_method": "shift_axes", "tests": "import unittest\n\nclass Test_shift_axes(unittest.TestCase):\n def test_shift_one_axis(self):\n \"\"\" :meth:`shift` test: shift one axis. \"\"\"\n shifted = self.s.shift_axes(1, 0)\n s_true = Signal3D(self._data, items=np.arange(3) - 1)\n pdt.assert_panel_equal(shifted, s_true)\n\n def test_shift_two_axes(self):\n \"\"\" :meth:`shift`: shift two axes with the same shift value.\"\"\"\n shifted = self.s.shift_axes(1, (0, 1))\n s_true = Signal3D(self._data, items=np.arange(3) - 1, major_axis=np.arange(3) - 1)\n pdt.assert_panel_equal(shifted, s_true)\n\n def test_shift_three_axes(self):\n \"\"\" :meth:`shift`: shift three axes with the same shift value.\"\"\"\n shifted = self.s.shift_axes(1)\n s_true = Signal3D(self._data, items=np.arange(3) - 1, major_axis=np.arange(3) - 1, minor_axis=np.arange(3) - 1)\n pdt.assert_panel_equal(shifted, s_true)\n\n def test_shift_three_axes2(self):\n \"\"\" :meth:`shift`: shift three axes with different shift values.\"\"\"\n shift_vals = [1, 2, 3]\n shifted = self.s.shift_axes(shift_vals, (0, 1, 2))\n s_true = Signal3D(self._data, items=np.arange(3) - shift_vals[0], major_axis=np.arange(3) - shift_vals[1], minor_axis=np.arange(3) - shift_vals[2])\n pdt.assert_panel_equal(shifted, s_true)\n", "method_code": " def shift_axes(self, shift, axes=None, inplace=False):\n \"\"\"\n Applies shifting of a given axis.\n \n Parameters\n ----------\n shift : float, array_like\n The value to shift the axis. If this is an array, it should be the same size as\n :attr:`axes`.\n \n axes : int, string, array_like, optional\n Specifies which of the axes to shift. To shift a single axis, :attr:`axes` is an\n int or string representing the dimension or the axis alias name. To shift\n multiple axes, :attr:`axes` can be an array of value or string names. If axes is\n :const:`None`, all three axes are shifted.\n \n inplace : bool\n Modify the current instance if True.\n \n Returns\n -------\n : Signal3D\n A copy of Signal3D with shifted axes, or the current instance if :attr:`inplace` is\n :const:`True`.\n \"\"\"\n axes = self._get_axes_numbers(axes)\n shift, axes = self._cook_axes_args(shift, axes)\n out = Signal3D(self.values, items=self.items, major_axis=self.major_axis, minor_axis=self.minor_axis) if not inplace else self\n for i, ax in enumerate(axes):\n out.set_axis(ax, out.axes[ax] - shift[i])\n return out\n ", "context": "class Signal3D(pd.Panel):\n def shift_axes(self, shift, axes=None, inplace=False): ...\n def __init__(self, data, items=None, major_axis=None, minor_axis=None, **kwargs): ...\n def _constructor(self): ...\n def _constructor_sliced(self): ...\n def from_panel(cls, pnl): ...\n def operate(self, option='', axis=2): ...\n def _get_other_axes(axis): ...\n def _get_axes_numbers(self, axes): ...\n def _cook_axes_args(val, axes): ...\n def scale_axes(self, scale, axes=None, inplace=False): ...\n def skew(self, angle, skew_axis, other_axis): ...\n def extract(self, option='max', axis=0): ...\n def dscan(self, option='max'): ...\n def bscan(self, option='max'): ...\n def cscan(self, theta=None): ...\n def flatten(self): ...\n def align(self, other, **kwargs): ...\n def shift(self, periods=1, freq=None, axis='major'): ...\n def ts(self): ...\n def x(self): ...\n def y(self): ...\n def z(self): ...\n\n self.items = self.items.astype(dtype=np.float64)\n self.major_axis = self.major_axis.astype(dtype=np.float64)\n self.minor_axis = self.minor_axis.astype(dtype=np.float64)\n", "repository": "dibgerge/utkit", "test_name": "test_shift_one_axis", "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_000333.py"} {"focal_file": "signal3d.py", "focal_class": null, "focal_method": "scale_axes", "tests": "import unittest\n\nclass Test_scale_axes(unittest.TestCase):\n def test_scale_one_axis(self):\n \"\"\" :meth:`scale`: scale one axis.\"\"\"\n scale = 2.0\n scaled = self.s.scale_axes(scale, axes=0)\n s_true = Signal3D(self._data, items=np.arange(3) * scale, major_axis=np.arange(3), minor_axis=np.arange(3))\n pdt.assert_panel_equal(scaled, s_true)\n\n def test_scale_two_axes(self):\n \"\"\" :meth:`scale`: scale two axes.\"\"\"\n scale = 2.0\n scaled = self.s.scale_axes(scale, axes=(0, 1))\n s_true = Signal3D(self._data, items=np.arange(3) * scale, major_axis=np.arange(3) * scale, minor_axis=np.arange(3))\n pdt.assert_panel_equal(scaled, s_true)\n\n def test_scale_three_axes(self):\n \"\"\" :meth:`scale`: scale three axes.\"\"\"\n scale = 2.0\n scaled = self.s.scale_axes(scale)\n s_true = Signal3D(self._data, items=np.arange(3) * scale, major_axis=np.arange(3) * scale, minor_axis=np.arange(3) * scale)\n pdt.assert_panel_equal(scaled, s_true)\n\n def test_scale_three_axes2(self):\n \"\"\" :meth:`scale`: scale three axes.\"\"\"\n scale = [1, 2, 3]\n scaled = self.s.scale_axes(scale, axes=(0, 1, 2))\n s_true = Signal3D(self._data, items=np.arange(3) * scale[0], major_axis=np.arange(3) * scale[1], minor_axis=np.arange(3) * scale[2])\n pdt.assert_panel_equal(scaled, s_true)\n", "method_code": " def scale_axes(self, scale, axes=None, inplace=False):\n \"\"\"\n Scale axes by a given amount.\n \n Parameters\n ----------\n scale : float, array_like\n The amount to scale the axes. If :attr:`scale` is an array, it should be the same\n size as :attr:`axes`.\n \n axes : int, string, array_like, optional\n Specifies which of the axes to shift. To shift a single axis, :attr:`axes` is an\n int or string representing the dimension or the axis alias name. To shift\n multiple axes, :attr:`axes` can be an array of value or string names. If axes is\n :const:`None`, all three axes are shifted.\n \n inplace : bool\n Modify the current instance if True.\n \n Returns\n -------\n : Signal3D\n A copy of Signal3D with scaled axes or the current instance if :attr:`inplace` is\n :const:`True`.\n \"\"\"\n axes = self._get_axes_numbers(axes)\n scale, axes = self._cook_axes_args(scale, axes)\n out = Signal3D(self.values, items=self.items, major_axis=self.major_axis, minor_axis=self.minor_axis) if not inplace else self\n for i, ax in enumerate(axes):\n out.set_axis(ax, out.axes[ax] * scale[i])\n return out\n ", "context": "class Signal3D(pd.Panel):\n def scale_axes(self, scale, axes=None, inplace=False): ...\n def __init__(self, data, items=None, major_axis=None, minor_axis=None, **kwargs): ...\n def _constructor(self): ...\n def _constructor_sliced(self): ...\n def from_panel(cls, pnl): ...\n def operate(self, option='', axis=2): ...\n def _get_other_axes(axis): ...\n def _get_axes_numbers(self, axes): ...\n def _cook_axes_args(val, axes): ...\n def shift_axes(self, shift, axes=None, inplace=False): ...\n def skew(self, angle, skew_axis, other_axis): ...\n def extract(self, option='max', axis=0): ...\n def dscan(self, option='max'): ...\n def bscan(self, option='max'): ...\n def cscan(self, theta=None): ...\n def flatten(self): ...\n def align(self, other, **kwargs): ...\n def shift(self, periods=1, freq=None, axis='major'): ...\n def ts(self): ...\n def x(self): ...\n def y(self): ...\n def z(self): ...\n\n self.items = self.items.astype(dtype=np.float64)\n self.major_axis = self.major_axis.astype(dtype=np.float64)\n self.minor_axis = self.minor_axis.astype(dtype=np.float64)\n", "repository": "dibgerge/utkit", "test_name": "test_scale_one_axis", "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_000334.py"} {"focal_file": "django_plim/template.py", "focal_class": "Template", "focal_method": "render", "tests": "import unittest\n\nclass Test_Template_render(unittest.TestCase):\n def test_template_render(self):\n t = Template('h1 hello')\n self.assertEqual(t.render(), '

hello

')\n", "method_code": " def render(self, context):\n context_dict = {}\n for d in context.dicts:\n context_dict.update(d)\n return super(Template, self).render(**context_dict)\n ", "context": "class Template(MakoTemplate):\n def render(self, context): ...", "repository": "imom0/django-plim", "test_name": "test_template_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_000335.py"} {"focal_file": "smartcache/redis_cache.py", "focal_class": null, "focal_method": "get", "tests": "import unittest\n\nclass Test_get(unittest.TestCase):\n def test_set_get(self):\n self.assertTrue(self.cc.set(self.key, self.key) is None)\n self.assertTrue(self.cc.get(self.key) == self.key)\n\n def test_set_get(self):\n self.assertTrue(self.cc.set(self.key, self.key) is None)\n self.assertTrue(self.cc.get(self.key) == self.key)\n", "method_code": " def get(self, name):\n \"\"\"redis get command\n \"\"\"\n data = self.__get(str(name))\n try:\n return self.loads(data) if data else data\n except:\n return data\n ", "context": "class Cache(object):\n def get(self, name): ...\n def __getattr__(self, name): ...\n def get_connection(self, host='localhost', port=6379, db=0): ...\n def inject_connection(self, connection): ...\n def master_connection(self): ...\n def slave_connection(self): ...\n def valid(self, key): ...\n def pack(self, *args): ...\n def unpack(self, key): ...\n def set(self, name, value): ...\n def inc(self, key, amount=1): ...\n def hinc(self, name, key, amount=1): ...\n def inc_score(self, name, value, amount=1): ...\n def exists(self, name): ...\n def __contains__(self, item): ...\n def delete(self, name): ...\n def expire(self, name, expire): ...\n def expireat(self, name, timestamp): ...\n def persist(self, name): ...\n def move(self, name, db): ...\n def object(self, name, infotype='idletime'): ...\n def rename(self, name, newname): ...\n def renamenx(self, name, newname): ...\n def ttl(self, name): ...\n def type(self, name): ...\n def size(self, key): ...\n def append(self, name, value): ...\n def scan_db(self): ...\n def _update_hash(self, name, key, value): ...\n def hash(self, name, key=None, value=None): ...\n def hash_keys(self, name): ...\n def hash_values(self, name): ...\n def hash_items(self, name): ...\n def _hash_all(self, name): ...\n def lupdate(self, name, data): ...\n def rupdate(self, name, data): ...\n def list(self, name, skip=0, limit=1): ...\n def rpop(self, name): ...\n def lpop(self, name): ...\n def _pop_list_value(self, name, func): ...\n def _update_list(self, name, data, func): ...\n def _is_iterable(data): ...\n def members(self, name, count=1, with_all=False): ...\n def all(self, name): ...\n def sadd(self, name, member): ...\n def update_set(self, name, member): ...\n def contains(self, name, key): ...\n def move_set_member(self, src, dst, member): ...\n def pop_member(self, name, value=None): ...\n def _pop_sortedset(self, name, value): ...\n def _pop_set(self, name, value): ...\n def sortedset_members(self, name, skip=0, limit=1, min_score='-inf', max_score='inf', withscores=False): ...\n def remove_member_with_score(self, name, min_score=0, max_score=0): ...\n def remove_member_with_rank(self): ...\n def score(self, name, key): ...\n def zadd(self, name, value, score): ...\n def update_sortedset(self, name, value_list): ...\n def loads(self, obj): ...\n def dumps(self, obj): ...\n", "repository": "wecatch/smartcache", "test_name": "test_set_get", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 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_000336.py"} {"focal_file": "smartcache/redis_cache.py", "focal_class": null, "focal_method": "unpack", "tests": "import unittest\n\nclass Test_unpack(unittest.TestCase):\n def test_pack_unpack(self):\n key1, key2, key3 = (self.key, self.key, '%s_%s' % (self.key, self.key))\n self.assertTrue(self.cc.pack(key1, key2) == key3)\n tmp1, tmp2 = self.cc.unpack(key3)\n self.assertTrue(key1 == tmp1)\n self.assertTrue(key2 == tmp2)\n\n def test_pack_unpack(self):\n key1, key2, key3 = (self.key, self.key, '%s_%s' % (self.key, self.key))\n self.assertTrue(self.cc.pack(key1, key2) == key3)\n tmp1, tmp2 = self.cc.unpack(key3)\n self.assertTrue(key1 == tmp1)\n self.assertTrue(key2 == tmp2)\n", "method_code": " def unpack(self, key):\n \"\"\"unpack redis key to tuple\n \"\"\"\n return tuple(key.split('_'))\n ", "context": "class Cache(object):\n def unpack(self, key): ...\n def __getattr__(self, name): ...\n def get_connection(self, host='localhost', port=6379, db=0): ...\n def inject_connection(self, connection): ...\n def master_connection(self): ...\n def slave_connection(self): ...\n def valid(self, key): ...\n def pack(self, *args): ...\n def set(self, name, value): ...\n def inc(self, key, amount=1): ...\n def hinc(self, name, key, amount=1): ...\n def inc_score(self, name, value, amount=1): ...\n def get(self, name): ...\n def exists(self, name): ...\n def __contains__(self, item): ...\n def delete(self, name): ...\n def expire(self, name, expire): ...\n def expireat(self, name, timestamp): ...\n def persist(self, name): ...\n def move(self, name, db): ...\n def object(self, name, infotype='idletime'): ...\n def rename(self, name, newname): ...\n def renamenx(self, name, newname): ...\n def ttl(self, name): ...\n def type(self, name): ...\n def size(self, key): ...\n def append(self, name, value): ...\n def scan_db(self): ...\n def _update_hash(self, name, key, value): ...\n def hash(self, name, key=None, value=None): ...\n def hash_keys(self, name): ...\n def hash_values(self, name): ...\n def hash_items(self, name): ...\n def _hash_all(self, name): ...\n def lupdate(self, name, data): ...\n def rupdate(self, name, data): ...\n def list(self, name, skip=0, limit=1): ...\n def rpop(self, name): ...\n def lpop(self, name): ...\n def _pop_list_value(self, name, func): ...\n def _update_list(self, name, data, func): ...\n def _is_iterable(data): ...\n def members(self, name, count=1, with_all=False): ...\n def all(self, name): ...\n def sadd(self, name, member): ...\n def update_set(self, name, member): ...\n def contains(self, name, key): ...\n def move_set_member(self, src, dst, member): ...\n def pop_member(self, name, value=None): ...\n def _pop_sortedset(self, name, value): ...\n def _pop_set(self, name, value): ...\n def sortedset_members(self, name, skip=0, limit=1, min_score='-inf', max_score='inf', withscores=False): ...\n def remove_member_with_score(self, name, min_score=0, max_score=0): ...\n def remove_member_with_rank(self): ...\n def score(self, name, key): ...\n def zadd(self, name, value, score): ...\n def update_sortedset(self, name, value_list): ...\n def loads(self, obj): ...\n def dumps(self, obj): ...\n", "repository": "wecatch/smartcache", "test_name": "test_pack_unpack", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 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_000337.py"} {"focal_file": "smartcache/redis_cache.py", "focal_class": null, "focal_method": "valid", "tests": "import unittest\n\nclass Test_valid(unittest.TestCase):\n def test_valid(self):\n self.assertFalse(self.cc.valid(''))\n self.assertFalse(self.cc.valid(None))\n self.assertTrue(self.cc.valid('s'))\n\n def test_valid(self):\n self.assertFalse(self.cc.valid(''))\n self.assertFalse(self.cc.valid(None))\n self.assertTrue(self.cc.valid('s'))\n", "method_code": " def valid(self, key):\n \"\"\"\n valid redis key and value\n \"\"\"\n if key is None or key is '':\n return False\n return True\n ", "context": "class Cache(object):\n def valid(self, key): ...\n def __getattr__(self, name): ...\n def get_connection(self, host='localhost', port=6379, db=0): ...\n def inject_connection(self, connection): ...\n def master_connection(self): ...\n def slave_connection(self): ...\n def pack(self, *args): ...\n def unpack(self, key): ...\n def set(self, name, value): ...\n def inc(self, key, amount=1): ...\n def hinc(self, name, key, amount=1): ...\n def inc_score(self, name, value, amount=1): ...\n def get(self, name): ...\n def exists(self, name): ...\n def __contains__(self, item): ...\n def delete(self, name): ...\n def expire(self, name, expire): ...\n def expireat(self, name, timestamp): ...\n def persist(self, name): ...\n def move(self, name, db): ...\n def object(self, name, infotype='idletime'): ...\n def rename(self, name, newname): ...\n def renamenx(self, name, newname): ...\n def ttl(self, name): ...\n def type(self, name): ...\n def size(self, key): ...\n def append(self, name, value): ...\n def scan_db(self): ...\n def _update_hash(self, name, key, value): ...\n def hash(self, name, key=None, value=None): ...\n def hash_keys(self, name): ...\n def hash_values(self, name): ...\n def hash_items(self, name): ...\n def _hash_all(self, name): ...\n def lupdate(self, name, data): ...\n def rupdate(self, name, data): ...\n def list(self, name, skip=0, limit=1): ...\n def rpop(self, name): ...\n def lpop(self, name): ...\n def _pop_list_value(self, name, func): ...\n def _update_list(self, name, data, func): ...\n def _is_iterable(data): ...\n def members(self, name, count=1, with_all=False): ...\n def all(self, name): ...\n def sadd(self, name, member): ...\n def update_set(self, name, member): ...\n def contains(self, name, key): ...\n def move_set_member(self, src, dst, member): ...\n def pop_member(self, name, value=None): ...\n def _pop_sortedset(self, name, value): ...\n def _pop_set(self, name, value): ...\n def sortedset_members(self, name, skip=0, limit=1, min_score='-inf', max_score='inf', withscores=False): ...\n def remove_member_with_score(self, name, min_score=0, max_score=0): ...\n def remove_member_with_rank(self): ...\n def score(self, name, key): ...\n def zadd(self, name, value, score): ...\n def update_sortedset(self, name, value_list): ...\n def loads(self, obj): ...\n def dumps(self, obj): ...\n", "repository": "wecatch/smartcache", "test_name": "test_valid", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 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_000338.py"} {"focal_file": "smartcache/redis_cache.py", "focal_class": null, "focal_method": "append", "tests": "import unittest\n\nclass Test_append(unittest.TestCase):\n def test_append(self):\n self.cc.append(self.key, self.key)\n self.cc.append(self.key, self.key)\n self.assertEqual(self.cc.get(self.key), '%s%s' % (self.key, self.key))\n\n def test_append(self):\n self.cc.append(self.key, self.key)\n self.cc.append(self.key, self.key)\n self.assertEqual(self.cc.get(self.key), '%s%s' % (self.key, self.key))\n", "method_code": " def append(self, name, value):\n \"\"\"redis append command\n \"\"\"\n return self.__append(str(name), value)\n ", "context": "class Cache(object):\n def append(self, name, value): ...\n def __getattr__(self, name): ...\n def get_connection(self, host='localhost', port=6379, db=0): ...\n def inject_connection(self, connection): ...\n def master_connection(self): ...\n def slave_connection(self): ...\n def valid(self, key): ...\n def pack(self, *args): ...\n def unpack(self, key): ...\n def set(self, name, value): ...\n def inc(self, key, amount=1): ...\n def hinc(self, name, key, amount=1): ...\n def inc_score(self, name, value, amount=1): ...\n def get(self, name): ...\n def exists(self, name): ...\n def __contains__(self, item): ...\n def delete(self, name): ...\n def expire(self, name, expire): ...\n def expireat(self, name, timestamp): ...\n def persist(self, name): ...\n def move(self, name, db): ...\n def object(self, name, infotype='idletime'): ...\n def rename(self, name, newname): ...\n def renamenx(self, name, newname): ...\n def ttl(self, name): ...\n def type(self, name): ...\n def size(self, key): ...\n def scan_db(self): ...\n def _update_hash(self, name, key, value): ...\n def hash(self, name, key=None, value=None): ...\n def hash_keys(self, name): ...\n def hash_values(self, name): ...\n def hash_items(self, name): ...\n def _hash_all(self, name): ...\n def lupdate(self, name, data): ...\n def rupdate(self, name, data): ...\n def list(self, name, skip=0, limit=1): ...\n def rpop(self, name): ...\n def lpop(self, name): ...\n def _pop_list_value(self, name, func): ...\n def _update_list(self, name, data, func): ...\n def _is_iterable(data): ...\n def members(self, name, count=1, with_all=False): ...\n def all(self, name): ...\n def sadd(self, name, member): ...\n def update_set(self, name, member): ...\n def contains(self, name, key): ...\n def move_set_member(self, src, dst, member): ...\n def pop_member(self, name, value=None): ...\n def _pop_sortedset(self, name, value): ...\n def _pop_set(self, name, value): ...\n def sortedset_members(self, name, skip=0, limit=1, min_score='-inf', max_score='inf', withscores=False): ...\n def remove_member_with_score(self, name, min_score=0, max_score=0): ...\n def remove_member_with_rank(self): ...\n def score(self, name, key): ...\n def zadd(self, name, value, score): ...\n def update_sortedset(self, name, value_list): ...\n def loads(self, obj): ...\n def dumps(self, obj): ...\n", "repository": "wecatch/smartcache", "test_name": "test_append", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 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_000339.py"} {"focal_file": "smartcache/redis_cache.py", "focal_class": null, "focal_method": "exists", "tests": "import unittest\n\nclass Test_exists(unittest.TestCase):\n def test_exists(self):\n self.cc.set(self.key, 1)\n self.assertTrue(self.cc.exists(self.key))\n self.cc.delete(self.key)\n self.assertFalse(self.cc.exists(self.key))\n\n def test_exists(self):\n self.cc.set(self.key, 1)\n self.assertTrue(self.cc.exists(self.key))\n self.cc.delete(self.key)\n self.assertFalse(self.cc.exists(self.key))\n", "method_code": " def exists(self, name):\n \"\"\"redis exists command\n \"\"\"\n return bool(self.__exists(str(name)))\n ", "context": "class Cache(object):\n def exists(self, name): ...\n def __getattr__(self, name): ...\n def get_connection(self, host='localhost', port=6379, db=0): ...\n def inject_connection(self, connection): ...\n def master_connection(self): ...\n def slave_connection(self): ...\n def valid(self, key): ...\n def pack(self, *args): ...\n def unpack(self, key): ...\n def set(self, name, value): ...\n def inc(self, key, amount=1): ...\n def hinc(self, name, key, amount=1): ...\n def inc_score(self, name, value, amount=1): ...\n def get(self, name): ...\n def __contains__(self, item): ...\n def delete(self, name): ...\n def expire(self, name, expire): ...\n def expireat(self, name, timestamp): ...\n def persist(self, name): ...\n def move(self, name, db): ...\n def object(self, name, infotype='idletime'): ...\n def rename(self, name, newname): ...\n def renamenx(self, name, newname): ...\n def ttl(self, name): ...\n def type(self, name): ...\n def size(self, key): ...\n def append(self, name, value): ...\n def scan_db(self): ...\n def _update_hash(self, name, key, value): ...\n def hash(self, name, key=None, value=None): ...\n def hash_keys(self, name): ...\n def hash_values(self, name): ...\n def hash_items(self, name): ...\n def _hash_all(self, name): ...\n def lupdate(self, name, data): ...\n def rupdate(self, name, data): ...\n def list(self, name, skip=0, limit=1): ...\n def rpop(self, name): ...\n def lpop(self, name): ...\n def _pop_list_value(self, name, func): ...\n def _update_list(self, name, data, func): ...\n def _is_iterable(data): ...\n def members(self, name, count=1, with_all=False): ...\n def all(self, name): ...\n def sadd(self, name, member): ...\n def update_set(self, name, member): ...\n def contains(self, name, key): ...\n def move_set_member(self, src, dst, member): ...\n def pop_member(self, name, value=None): ...\n def _pop_sortedset(self, name, value): ...\n def _pop_set(self, name, value): ...\n def sortedset_members(self, name, skip=0, limit=1, min_score='-inf', max_score='inf', withscores=False): ...\n def remove_member_with_score(self, name, min_score=0, max_score=0): ...\n def remove_member_with_rank(self): ...\n def score(self, name, key): ...\n def zadd(self, name, value, score): ...\n def update_sortedset(self, name, value_list): ...\n def loads(self, obj): ...\n def dumps(self, obj): ...\n", "repository": "wecatch/smartcache", "test_name": "test_exists", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 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_000340.py"} {"focal_file": "smartcache/redis_cache.py", "focal_class": null, "focal_method": "ttl", "tests": "import unittest\n\nclass Test_ttl(unittest.TestCase):\n def test_expire_persist_ttl(self):\n self.cc.set(self.key, 1)\n self.assertTrue(self.cc.exists(self.key))\n self.cc.expire(self.key, 1)\n time.sleep(2)\n self.assertFalse(self.cc.exists(self.key))\n self.cc.set(self.key, 1)\n self.cc.expire(self.key, 3864)\n self.assertTrue(self.cc.ttl(self.key) > 0)\n self.cc.persist(self.key)\n self.assertTrue(self.cc.ttl(self.key) < 0)\n\n def test_expire_persist_ttl(self):\n self.cc.set(self.key, 1)\n self.assertTrue(self.cc.exists(self.key))\n self.cc.expire(self.key, 1)\n time.sleep(2)\n self.assertFalse(self.cc.exists(self.key))\n self.cc.set(self.key, 1)\n self.cc.expire(self.key, 3864)\n self.assertTrue(self.cc.ttl(self.key) > 0)\n self.cc.persist(self.key)\n self.assertTrue(self.cc.ttl(self.key) < 0)\n", "method_code": " def ttl(self, name):\n \"\"\"redis ttl command\n \"\"\"\n return self.__ttl(str(name))\n ", "context": "class Cache(object):\n def ttl(self, name): ...\n def __getattr__(self, name): ...\n def get_connection(self, host='localhost', port=6379, db=0): ...\n def inject_connection(self, connection): ...\n def master_connection(self): ...\n def slave_connection(self): ...\n def valid(self, key): ...\n def pack(self, *args): ...\n def unpack(self, key): ...\n def set(self, name, value): ...\n def inc(self, key, amount=1): ...\n def hinc(self, name, key, amount=1): ...\n def inc_score(self, name, value, amount=1): ...\n def get(self, name): ...\n def exists(self, name): ...\n def __contains__(self, item): ...\n def delete(self, name): ...\n def expire(self, name, expire): ...\n def expireat(self, name, timestamp): ...\n def persist(self, name): ...\n def move(self, name, db): ...\n def object(self, name, infotype='idletime'): ...\n def rename(self, name, newname): ...\n def renamenx(self, name, newname): ...\n def type(self, name): ...\n def size(self, key): ...\n def append(self, name, value): ...\n def scan_db(self): ...\n def _update_hash(self, name, key, value): ...\n def hash(self, name, key=None, value=None): ...\n def hash_keys(self, name): ...\n def hash_values(self, name): ...\n def hash_items(self, name): ...\n def _hash_all(self, name): ...\n def lupdate(self, name, data): ...\n def rupdate(self, name, data): ...\n def list(self, name, skip=0, limit=1): ...\n def rpop(self, name): ...\n def lpop(self, name): ...\n def _pop_list_value(self, name, func): ...\n def _update_list(self, name, data, func): ...\n def _is_iterable(data): ...\n def members(self, name, count=1, with_all=False): ...\n def all(self, name): ...\n def sadd(self, name, member): ...\n def update_set(self, name, member): ...\n def contains(self, name, key): ...\n def move_set_member(self, src, dst, member): ...\n def pop_member(self, name, value=None): ...\n def _pop_sortedset(self, name, value): ...\n def _pop_set(self, name, value): ...\n def sortedset_members(self, name, skip=0, limit=1, min_score='-inf', max_score='inf', withscores=False): ...\n def remove_member_with_score(self, name, min_score=0, max_score=0): ...\n def remove_member_with_rank(self): ...\n def score(self, name, key): ...\n def zadd(self, name, value, score): ...\n def update_sortedset(self, name, value_list): ...\n def loads(self, obj): ...\n def dumps(self, obj): ...\n", "repository": "wecatch/smartcache", "test_name": "test_expire_persist_ttl", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 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_000341.py"} {"focal_file": "smartcache/redis_cache.py", "focal_class": null, "focal_method": "list", "tests": "import unittest\n\nclass Test_list(unittest.TestCase):\n def test_list(self):\n self.cc.lupdate(self.key, self.key)\n ls = self.cc.list(self.key)\n self.assertEqual(len(ls), 1)\n self.assertEqual(ls[0], self.key)\n self.cc.delete(self.key)\n self.cc.rupdate(self.key, self.key)\n ls = self.cc.list(self.key)\n self.assertEqual(len(ls), 1)\n self.assertEqual(ls[0], self.key)\n self.cc.delete(self.key)\n self.cc.lupdate(self.key, self.key)\n self.assertEqual(self.cc.size(self.key), 1)\n v = self.cc.rpop(self.key)\n self.assertEqual(v, self.key)\n self.assertEqual(self.cc.size(self.key), 0)\n self.cc.lupdate(self.key, self.key)\n self.assertEqual(self.cc.size(self.key), 1)\n v = self.cc.lpop(self.key)\n self.assertEqual(v, self.key)\n self.assertEqual(self.cc.size(self.key), 0)\n\n def test_list(self):\n self.cc.lupdate(self.key, self.key)\n ls = self.cc.list(self.key)\n self.assertEqual(len(ls), 1)\n self.assertEqual(ls[0], self.key)\n self.cc.delete(self.key)\n self.cc.rupdate(self.key, self.key)\n ls = self.cc.list(self.key)\n self.assertEqual(len(ls), 1)\n self.assertEqual(ls[0], self.key)\n self.cc.delete(self.key)\n self.cc.lupdate(self.key, self.key)\n self.assertEqual(self.cc.size(self.key), 1)\n v = self.cc.rpop(self.key)\n self.assertEqual(v, self.key)\n self.assertEqual(self.cc.size(self.key), 0)\n self.cc.lupdate(self.key, self.key)\n self.assertEqual(self.cc.size(self.key), 1)\n v = self.cc.lpop(self.key)\n self.assertEqual(v, self.key)\n self.assertEqual(self.cc.size(self.key), 0)\n", "method_code": " def list(self, name, skip=0, limit=1):\n \"\"\"lrange command\n :returns list value\n \"\"\"\n return [self.loads(i) for i in self.__lrange(str(name), skip, skip + limit - 1)]\n ", "context": "class Cache(object):\n def list(self, name, skip=0, limit=1): ...\n def __getattr__(self, name): ...\n def get_connection(self, host='localhost', port=6379, db=0): ...\n def inject_connection(self, connection): ...\n def master_connection(self): ...\n def slave_connection(self): ...\n def valid(self, key): ...\n def pack(self, *args): ...\n def unpack(self, key): ...\n def set(self, name, value): ...\n def inc(self, key, amount=1): ...\n def hinc(self, name, key, amount=1): ...\n def inc_score(self, name, value, amount=1): ...\n def get(self, name): ...\n def exists(self, name): ...\n def __contains__(self, item): ...\n def delete(self, name): ...\n def expire(self, name, expire): ...\n def expireat(self, name, timestamp): ...\n def persist(self, name): ...\n def move(self, name, db): ...\n def object(self, name, infotype='idletime'): ...\n def rename(self, name, newname): ...\n def renamenx(self, name, newname): ...\n def ttl(self, name): ...\n def type(self, name): ...\n def size(self, key): ...\n def append(self, name, value): ...\n def scan_db(self): ...\n def _update_hash(self, name, key, value): ...\n def hash(self, name, key=None, value=None): ...\n def hash_keys(self, name): ...\n def hash_values(self, name): ...\n def hash_items(self, name): ...\n def _hash_all(self, name): ...\n def lupdate(self, name, data): ...\n def rupdate(self, name, data): ...\n def rpop(self, name): ...\n def lpop(self, name): ...\n def _pop_list_value(self, name, func): ...\n def _update_list(self, name, data, func): ...\n def _is_iterable(data): ...\n def members(self, name, count=1, with_all=False): ...\n def all(self, name): ...\n def sadd(self, name, member): ...\n def update_set(self, name, member): ...\n def contains(self, name, key): ...\n def move_set_member(self, src, dst, member): ...\n def pop_member(self, name, value=None): ...\n def _pop_sortedset(self, name, value): ...\n def _pop_set(self, name, value): ...\n def sortedset_members(self, name, skip=0, limit=1, min_score='-inf', max_score='inf', withscores=False): ...\n def remove_member_with_score(self, name, min_score=0, max_score=0): ...\n def remove_member_with_rank(self): ...\n def score(self, name, key): ...\n def zadd(self, name, value, score): ...\n def update_sortedset(self, name, value_list): ...\n def loads(self, obj): ...\n def dumps(self, obj): ...\n", "repository": "wecatch/smartcache", "test_name": "test_list", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000342.py"} {"focal_file": "smartcache/redis_cache.py", "focal_class": null, "focal_method": "set", "tests": "import unittest\n\nclass Test_set(unittest.TestCase):\n def test_set(self):\n self.cc.update_set(self.key, self.key)\n self.assertTrue(self.cc.contains(self.key, self.key))\n self.assertFalse(self.cc.contains(self.key, 't'))\n self.assertEqual(self.cc.members(self.key), [self.key])\n self.assertEqual(self.cc.pop_member(self.key, self.key), 1)\n self.assertFalse(self.cc.contains(self.key, self.key))\n self.assertEqual(self.cc.pop_member(self.key, self.key), 0)\n data = [self.key, self.key + '1']\n self.cc.update_set(self.key, data)\n self.assertEqual(self.cc.size(self.key), 2)\n self.cc.pop_member(self.key, data)\n self.assertEqual(self.cc.size(self.key), 0)\n data = [self.key, self.key + '1', self.key + '2']\n self.cc.update_set(self.key, data)\n self.assertEqual(self.cc.size(self.key), len(data))\n self.assertEqual(set(self.cc.members(self.key, with_all=True)), set(data))\n self.assertEqual(set(self.cc.all(self.key)), set(data))\n self.cc.delete(self.key)\n self.cc.sadd(self.key, self.key)\n self.assertEqual(self.cc.size(self.key), 1)\n self.assertEqual(set(self.cc.members(self.key, with_all=True)), set([self.key]))\n self.assertEqual(set(self.cc.all(self.key)), set([self.key]))\n\n def test_set(self):\n self.cc.update_set(self.key, self.key)\n self.assertTrue(self.cc.contains(self.key, self.key))\n self.assertFalse(self.cc.contains(self.key, 't'))\n self.assertEqual(self.cc.members(self.key), [self.key])\n self.assertEqual(self.cc.pop_member(self.key, self.key), 1)\n self.assertFalse(self.cc.contains(self.key, self.key))\n self.assertEqual(self.cc.pop_member(self.key, self.key), 0)\n data = [self.key, self.key + '1']\n self.cc.update_set(self.key, data)\n self.assertEqual(self.cc.size(self.key), 2)\n self.cc.pop_member(self.key, data)\n self.assertEqual(self.cc.size(self.key), 0)\n data = [self.key, self.key + '1', self.key + '2']\n self.cc.update_set(self.key, data)\n self.assertEqual(self.cc.size(self.key), len(data))\n self.assertEqual(set(self.cc.members(self.key, with_all=True)), set(data))\n self.assertEqual(set(self.cc.all(self.key)), set(data))\n self.cc.delete(self.key)\n self.cc.sadd(self.key, self.key)\n self.assertEqual(self.cc.size(self.key), 1)\n self.assertEqual(set(self.cc.members(self.key, with_all=True)), set([self.key]))\n self.assertEqual(set(self.cc.all(self.key)), set([self.key]))\n", "method_code": " def set(self, name, value):\n \"\"\"redis set command\n \"\"\"\n if not self.valid(value):\n return\n if not self.valid(name):\n return\n name = str(name)\n self.__set(name, self.dumps(value))\n ", "context": "class Cache(object):\n def set(self, name, value): ...\n def __getattr__(self, name): ...\n def get_connection(self, host='localhost', port=6379, db=0): ...\n def inject_connection(self, connection): ...\n def master_connection(self): ...\n def slave_connection(self): ...\n def valid(self, key): ...\n def pack(self, *args): ...\n def unpack(self, key): ...\n def inc(self, key, amount=1): ...\n def hinc(self, name, key, amount=1): ...\n def inc_score(self, name, value, amount=1): ...\n def get(self, name): ...\n def exists(self, name): ...\n def __contains__(self, item): ...\n def delete(self, name): ...\n def expire(self, name, expire): ...\n def expireat(self, name, timestamp): ...\n def persist(self, name): ...\n def move(self, name, db): ...\n def object(self, name, infotype='idletime'): ...\n def rename(self, name, newname): ...\n def renamenx(self, name, newname): ...\n def ttl(self, name): ...\n def type(self, name): ...\n def size(self, key): ...\n def append(self, name, value): ...\n def scan_db(self): ...\n def _update_hash(self, name, key, value): ...\n def hash(self, name, key=None, value=None): ...\n def hash_keys(self, name): ...\n def hash_values(self, name): ...\n def hash_items(self, name): ...\n def _hash_all(self, name): ...\n def lupdate(self, name, data): ...\n def rupdate(self, name, data): ...\n def list(self, name, skip=0, limit=1): ...\n def rpop(self, name): ...\n def lpop(self, name): ...\n def _pop_list_value(self, name, func): ...\n def _update_list(self, name, data, func): ...\n def _is_iterable(data): ...\n def members(self, name, count=1, with_all=False): ...\n def all(self, name): ...\n def sadd(self, name, member): ...\n def update_set(self, name, member): ...\n def contains(self, name, key): ...\n def move_set_member(self, src, dst, member): ...\n def pop_member(self, name, value=None): ...\n def _pop_sortedset(self, name, value): ...\n def _pop_set(self, name, value): ...\n def sortedset_members(self, name, skip=0, limit=1, min_score='-inf', max_score='inf', withscores=False): ...\n def remove_member_with_score(self, name, min_score=0, max_score=0): ...\n def remove_member_with_rank(self): ...\n def score(self, name, key): ...\n def zadd(self, name, value, score): ...\n def update_sortedset(self, name, value_list): ...\n def loads(self, obj): ...\n def dumps(self, obj): ...\n", "repository": "wecatch/smartcache", "test_name": "test_set", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000343.py"} {"focal_file": "smartcache/redis_cache.py", "focal_class": null, "focal_method": "update_sortedset", "tests": "import unittest\n\nclass Test_update_sortedset(unittest.TestCase):\n def test_sorted(self):\n self.cc.update_sortedset(self.key, (self.key, 1))\n v = self.cc.sortedset_members(self.key)\n self.assertEqual(v, [self.key])\n v = self.cc.sortedset_members(self.key, withscores=True)\n self.assertEqual(v, [(self.key, 1)])\n self.assertEqual(self.cc.size(self.key), 1)\n self.cc.remove_member_with_score(self.key, 0, 2)\n self.assertEqual(self.cc.size(self.key), 0)\n self.cc.update_sortedset(self.key, (self.key, 1))\n self.assertEqual(self.cc.score(self.key, self.key), 1.0)\n self.assertEqual(self.cc.size(self.key), 1)\n self.cc.pop_member(self.key, self.key)\n self.assertEqual(self.cc.size(self.key), 0)\n self.cc.update_sortedset(self.key, [(self.key, 1), (self.key + '1', 2)])\n self.assertEqual(self.cc.size(self.key), 2)\n self.cc.pop_member(self.key, [self.key, self.key + '1'])\n self.assertEqual(self.cc.size(self.key), 0)\n self.cc.delete(self.key)\n self.cc.zadd(self.key, self.key, 1)\n v = self.cc.sortedset_members(self.key)\n self.assertEqual(v, [self.key])\n self.assertEqual(self.cc.score(self.key, self.key), 1.0)\n\n def test_sorted(self):\n self.cc.update_sortedset(self.key, (self.key, 1))\n v = self.cc.sortedset_members(self.key)\n self.assertEqual(v, [self.key])\n v = self.cc.sortedset_members(self.key, withscores=True)\n self.assertEqual(v, [(self.key, 1)])\n self.assertEqual(self.cc.size(self.key), 1)\n self.cc.remove_member_with_score(self.key, 0, 2)\n self.assertEqual(self.cc.size(self.key), 0)\n self.cc.update_sortedset(self.key, (self.key, 1))\n self.assertEqual(self.cc.score(self.key, self.key), 1.0)\n self.assertEqual(self.cc.size(self.key), 1)\n self.cc.pop_member(self.key, self.key)\n self.assertEqual(self.cc.size(self.key), 0)\n self.cc.update_sortedset(self.key, [(self.key, 1), (self.key + '1', 2)])\n self.assertEqual(self.cc.size(self.key), 2)\n self.cc.pop_member(self.key, [self.key, self.key + '1'])\n self.assertEqual(self.cc.size(self.key), 0)\n self.cc.delete(self.key)\n self.cc.zadd(self.key, self.key, 1)\n v = self.cc.sortedset_members(self.key)\n self.assertEqual(v, [self.key])\n self.assertEqual(self.cc.score(self.key, self.key), 1.0)\n", "method_code": " def update_sortedset(self, name, value_list):\n \"\"\"sortedset zadd command\n \"\"\"\n if not self.valid(name):\n return\n if not self._is_iterable(value_list):\n return\n result = []\n if isinstance(value_list, tuple):\n result.append(value_list[1])\n result.append(self.dumps(value_list[0]))\n else:\n for value, score in value_list:\n result.append(score)\n result.append(self.dumps(value))\n if not result:\n return\n name = str(name)\n try:\n return self.__zadd(name, *result)\n except Exception as e:\n return sum([self.__zadd(name, *tuple(result[index:index + 2])) for index in range(0, len(result), 2)])\n ", "context": "class Cache(object):\n def update_sortedset(self, name, value_list): ...\n def __getattr__(self, name): ...\n def get_connection(self, host='localhost', port=6379, db=0): ...\n def inject_connection(self, connection): ...\n def master_connection(self): ...\n def slave_connection(self): ...\n def valid(self, key): ...\n def pack(self, *args): ...\n def unpack(self, key): ...\n def set(self, name, value): ...\n def inc(self, key, amount=1): ...\n def hinc(self, name, key, amount=1): ...\n def inc_score(self, name, value, amount=1): ...\n def get(self, name): ...\n def exists(self, name): ...\n def __contains__(self, item): ...\n def delete(self, name): ...\n def expire(self, name, expire): ...\n def expireat(self, name, timestamp): ...\n def persist(self, name): ...\n def move(self, name, db): ...\n def object(self, name, infotype='idletime'): ...\n def rename(self, name, newname): ...\n def renamenx(self, name, newname): ...\n def ttl(self, name): ...\n def type(self, name): ...\n def size(self, key): ...\n def append(self, name, value): ...\n def scan_db(self): ...\n def _update_hash(self, name, key, value): ...\n def hash(self, name, key=None, value=None): ...\n def hash_keys(self, name): ...\n def hash_values(self, name): ...\n def hash_items(self, name): ...\n def _hash_all(self, name): ...\n def lupdate(self, name, data): ...\n def rupdate(self, name, data): ...\n def list(self, name, skip=0, limit=1): ...\n def rpop(self, name): ...\n def lpop(self, name): ...\n def _pop_list_value(self, name, func): ...\n def _update_list(self, name, data, func): ...\n def _is_iterable(data): ...\n def members(self, name, count=1, with_all=False): ...\n def all(self, name): ...\n def sadd(self, name, member): ...\n def update_set(self, name, member): ...\n def contains(self, name, key): ...\n def move_set_member(self, src, dst, member): ...\n def pop_member(self, name, value=None): ...\n def _pop_sortedset(self, name, value): ...\n def _pop_set(self, name, value): ...\n def sortedset_members(self, name, skip=0, limit=1, min_score='-inf', max_score='inf', withscores=False): ...\n def remove_member_with_score(self, name, min_score=0, max_score=0): ...\n def remove_member_with_rank(self): ...\n def score(self, name, key): ...\n def zadd(self, name, value, score): ...\n def loads(self, obj): ...\n def dumps(self, obj): ...\n", "repository": "wecatch/smartcache", "test_name": "test_sorted", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000344.py"} {"focal_file": "smartcache/redis_cache.py", "focal_class": null, "focal_method": "inc", "tests": "import unittest\n\nclass Test_inc(unittest.TestCase):\n def test_inc(self):\n self.cc.delete(self.key)\n self.cc.inc(self.key)\n self.assertEqual(self.cc.get(self.key), '1')\n self.cc.inc(self.key)\n self.assertEqual(self.cc.get(self.key), '2')\n self.cc.delete(self.key)\n self.cc.hinc(self.key, self.key)\n self.assertEqual(self.cc.hash(self.key, self.key), '1')\n self.cc.delete(self.key)\n self.cc.update_sortedset(self.key, (self.key, 1))\n self.cc.inc_score(self.key, self.key, 2)\n v = self.cc.sortedset_members(self.key, withscores=True)\n self.assertEqual(v, [(self.key, 3)])\n\n def test_inc(self):\n self.cc.delete(self.key)\n self.cc.inc(self.key)\n self.assertEqual(self.cc.get(self.key), '1')\n self.cc.inc(self.key)\n self.assertEqual(self.cc.get(self.key), '2')\n self.cc.delete(self.key)\n self.cc.hinc(self.key, self.key)\n self.assertEqual(self.cc.hash(self.key, self.key), '1')\n self.cc.delete(self.key)\n self.cc.update_sortedset(self.key, (self.key, 1))\n self.cc.inc_score(self.key, self.key, 2)\n v = self.cc.sortedset_members(self.key, withscores=True)\n self.assertEqual(v, [(self.key, 3)])\n", "method_code": " def inc(self, key, amount=1):\n \"\"\"inc command\n \"\"\"\n return self.__incrby(str(key), amount)\n ", "context": "class Cache(object):\n def inc(self, key, amount=1): ...\n def __getattr__(self, name): ...\n def get_connection(self, host='localhost', port=6379, db=0): ...\n def inject_connection(self, connection): ...\n def master_connection(self): ...\n def slave_connection(self): ...\n def valid(self, key): ...\n def pack(self, *args): ...\n def unpack(self, key): ...\n def set(self, name, value): ...\n def hinc(self, name, key, amount=1): ...\n def inc_score(self, name, value, amount=1): ...\n def get(self, name): ...\n def exists(self, name): ...\n def __contains__(self, item): ...\n def delete(self, name): ...\n def expire(self, name, expire): ...\n def expireat(self, name, timestamp): ...\n def persist(self, name): ...\n def move(self, name, db): ...\n def object(self, name, infotype='idletime'): ...\n def rename(self, name, newname): ...\n def renamenx(self, name, newname): ...\n def ttl(self, name): ...\n def type(self, name): ...\n def size(self, key): ...\n def append(self, name, value): ...\n def scan_db(self): ...\n def _update_hash(self, name, key, value): ...\n def hash(self, name, key=None, value=None): ...\n def hash_keys(self, name): ...\n def hash_values(self, name): ...\n def hash_items(self, name): ...\n def _hash_all(self, name): ...\n def lupdate(self, name, data): ...\n def rupdate(self, name, data): ...\n def list(self, name, skip=0, limit=1): ...\n def rpop(self, name): ...\n def lpop(self, name): ...\n def _pop_list_value(self, name, func): ...\n def _update_list(self, name, data, func): ...\n def _is_iterable(data): ...\n def members(self, name, count=1, with_all=False): ...\n def all(self, name): ...\n def sadd(self, name, member): ...\n def update_set(self, name, member): ...\n def contains(self, name, key): ...\n def move_set_member(self, src, dst, member): ...\n def pop_member(self, name, value=None): ...\n def _pop_sortedset(self, name, value): ...\n def _pop_set(self, name, value): ...\n def sortedset_members(self, name, skip=0, limit=1, min_score='-inf', max_score='inf', withscores=False): ...\n def remove_member_with_score(self, name, min_score=0, max_score=0): ...\n def remove_member_with_rank(self): ...\n def score(self, name, key): ...\n def zadd(self, name, value, score): ...\n def update_sortedset(self, name, value_list): ...\n def loads(self, obj): ...\n def dumps(self, obj): ...\n", "repository": "wecatch/smartcache", "test_name": "test_inc", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 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_000345.py"} {"focal_file": "smartcache/object_cache.py", "focal_class": null, "focal_method": "set", "tests": "import unittest\n\nclass Test_set(unittest.TestCase):\n def test_get_set(self):\n self.oc.set(self.key, self.key)\n self.assertEqual(self.oc.get(self.key), self.key)\n", "method_code": " def set(key, value, expire=24 * 3600):\n if not hash(key):\n raise ValueError('%s is not hashable' % key)\n if key not in Cache.__data:\n Cache.__data[key] = DataObject(key, value, expire)\n Cache.__data[key].set_value(value)\n ", "context": "class Cache(object):\n @staticmethod\n def set(key, value, expire=24 * 3600): ...\n def pack(*args): ...\n def unpack(key): ...\n def get(key): ...\n def __contains__(self, item): ...\n def exists(name): ...\n def delete(name): ...\n\n __data = {}\n", "repository": "wecatch/smartcache", "test_name": "test_get_set", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 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_000346.py"} {"focal_file": "tomita/parser.py", "focal_class": "TomitaParser", "focal_method": "parse", "tests": "import unittest\n\nclass Test_TomitaParser_parse(unittest.TestCase):\n @data_provider(persons_data_provider)\n def test_parse_persons(self, text: str, facts: List[DocumentFact]):\n parser = TomitaParser(appglobals.CONFIG_PERSONS)\n parsed_facts = parser.parse(text)\n self.assertEqual(parsed_facts, facts)\n", "method_code": " def parse(self, text: str) -> List[DocumentFact]:\n logger.debug('Start parse text')\n pipe = subprocess.Popen([self.bin, self.config], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, cwd=appglobals.CONFIGS_PATH)\n out, err = pipe.communicate(input=text.encode('utf-8'))\n facts = self.parse_facts(out)\n logger.debug('End parse text, found {0} facts'.format(len(facts)))\n return facts\n ", "context": "class TomitaParser(object):\n def parse(self, text: str) -> List[DocumentFact]: ...\n def __init__(self, config: str=None, tomita_bin: str=None): ...\n def parse_facts(self, response: bytes) -> List[DocumentFact]: ...\n\n self.bin = tomita_bin or appglobals.TOMITA_BIN\n self.config = config\n", "repository": "sgacode/tomita_parser_wrapper", "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_000347.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": "JulioCesarGM91/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_000348.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": "JulioCesarGM91/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_000349.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": "JulioCesarGM91/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_000350.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": "JulioCesarGM91/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_000351.py"} {"focal_file": "coursebuilder/common/schema_fields.py", "focal_class": "common.schema_fields.FieldRegistry", "focal_method": "add_property", "tests": "import unittest\n\nclass Test_common_schema_fields_FieldRegistry_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", "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": "JulioCesarGM91/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, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000352.py"} {"focal_file": "coursebuilder/common/schema_fields.py", "focal_class": "common.schema_fields.FieldArray", "focal_method": "add_property", "tests": "import unittest\n\nclass Test_common_schema_fields_FieldArray_add_property(unittest.TestCase):\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": "JulioCesarGM91/course-builder", "test_name": "test_mc_question_schema", "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_000353.py"} {"focal_file": "coursebuilder/common/schema_fields.py", "focal_class": "common.schema_fields.FieldRegistry", "focal_method": "validate", "tests": "import unittest\n\nclass Test_common_schema_fields_FieldRegistry_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": "JulioCesarGM91/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_000354.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": "JulioCesarGM91/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_000355.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": "JulioCesarGM91/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_000356.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": "JulioCesarGM91/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_000357.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": "JulioCesarGM91/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_000358.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": "JulioCesarGM91/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_000359.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": "JulioCesarGM91/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_000360.py"} {"focal_file": "community/git.py", "focal_class": null, "focal_method": "get_config_remote", "tests": "import unittest\n\nclass Test_get_config_remote(unittest.TestCase):\n def test_config_remote(self):\n remote = get_config_remote()\n self.assertEqual('url', remote[0][0])\n self.assertIn('/community', remote[0][1])\n", "method_code": "def get_config_remote(name='origin'):\n config = get_config()\n has_remote = False\n for key in config.sections():\n if key == 'remote \"%s\"' % name:\n return config.items(key)\n elif key.startswith('remote'):\n has_remote = True\n if has_remote:\n raise KeyError('No git remote called \"%s\"' % name)\n raise KeyError('No git remotes found')", "context": "def get_config_remote(name='origin'): ...\ndef get_config(): ...\ndef get_config_remote(name='origin'): ...\ndef get_remote_url(name='origin'): ...\ndef get_repo_slug(url): ...\ndef get_owner(): ...\ndef get_ihoster(url): ...\ndef get_irepo(url=None): ...\ndef get_parent_repo(url=None): ...\ndef get_parent_slug(url=None): ...\ndef get_org_name(): ...\ndef get_upstream_repo(): ...\ndef get_deploy_url(name=None, hoster=None): ...\ndef get_upstream_deploy_url(name=None, hoster='github'): ...\n", "repository": "coala/community", "test_name": "test_config_remote", "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_000361.py"} {"focal_file": "community/git.py", "focal_class": null, "focal_method": "get_remote_url", "tests": "import unittest\n\nclass Test_get_remote_url(unittest.TestCase):\n def test_remote_url(self):\n url = get_remote_url()\n self.assertIn('/community', url.pathname)\n self.assertEqual('community', url.name)\n self.assertIn(url.resource, ['gitlab.com', 'github.com'])\n", "method_code": "def get_remote_url(name='origin'):\n \"\"\"Obtain a parsed remote URL.\n\n Uses CI environment variables or git remotes.\n \"\"\"\n url = os.environ.get('REPOSITORY_URL')\n if not url:\n remote = get_config_remote(name)\n assert remote[0][0] == 'url'\n url = remote[0][1]\n try:\n url = giturlparse.parse(url)\n except giturlparse.parser.ParserError:\n url = giturlparse.parse(url + '.git')\n return url", "context": "def get_remote_url(name='origin'): ...\ndef get_config(): ...\ndef get_config_remote(name='origin'): ...\ndef get_remote_url(name='origin'): ...\ndef get_repo_slug(url): ...\ndef get_owner(): ...\ndef get_ihoster(url): ...\ndef get_irepo(url=None): ...\ndef get_parent_repo(url=None): ...\ndef get_parent_slug(url=None): ...\ndef get_org_name(): ...\ndef get_upstream_repo(): ...\ndef get_deploy_url(name=None, hoster=None): ...\ndef get_upstream_deploy_url(name=None, hoster='github'): ...\n", "repository": "coala/community", "test_name": "test_remote_url", "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_000362.py"} {"focal_file": "community/git.py", "focal_class": null, "focal_method": "get_org_name", "tests": "import unittest\n\nclass Test_get_org_name(unittest.TestCase):\n def test_org_name(self):\n org_name = get_org_name()\n self.assertTrue(org_name)\n", "method_code": "def get_org_name():\n global _org_name\n if _org_name:\n return _org_name\n repo = get_irepo()\n if os.environ.get('TRAVIS_PULL_REQUEST', 'false') == 'false':\n if repo.parent:\n repo = repo.parent\n _org_name = repo.full_name.split('/', 1)[0]\n return _org_name", "context": "def get_org_name(): ...\ndef get_config(): ...\ndef get_config_remote(name='origin'): ...\ndef get_remote_url(name='origin'): ...\ndef get_repo_slug(url): ...\ndef get_owner(): ...\ndef get_ihoster(url): ...\ndef get_irepo(url=None): ...\ndef get_parent_repo(url=None): ...\ndef get_parent_slug(url=None): ...\ndef get_org_name(): ...\ndef get_upstream_repo(): ...\ndef get_deploy_url(name=None, hoster=None): ...\ndef get_upstream_deploy_url(name=None, hoster='github'): ...\n", "repository": "coala/community", "test_name": "test_org_name", "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_000363.py"} {"focal_file": "community/git.py", "focal_class": null, "focal_method": "get_deploy_url", "tests": "import unittest\n\nclass Test_get_deploy_url(unittest.TestCase):\n def test_deploy_url(self):\n url = get_deploy_url()\n self.assertIn('/community', url)\n", "method_code": "def get_deploy_url(name=None, hoster=None):\n \"\"\"\n Obtain the http where deploys appear.\n When `name` is None, fetch current repo of current org,\n otherwise, fetch a specified repo of current org.\n \"\"\"\n if not name and os.environ.get('REPOSITORY_URL'):\n return os.environ.get('URL')\n url = get_remote_url()\n owner = url.owner\n path = name if name else url.name\n if hoster is not None:\n deploy_url = 'https://%s.%s.io/%s' % (owner, hoster, path)\n elif url.resource == 'github.com':\n deploy_url = 'https://%s.github.io/%s' % (owner, path)\n elif url.resource == 'gitlab.com':\n deploy_url = 'https://%s.gitlab.io/%s' % (owner, path)\n else:\n raise Exception('remote %s is not supported' % url)\n return deploy_url", "context": "def get_deploy_url(name=None, hoster=None): ...\ndef get_config(): ...\ndef get_config_remote(name='origin'): ...\ndef get_remote_url(name='origin'): ...\ndef get_repo_slug(url): ...\ndef get_owner(): ...\ndef get_ihoster(url): ...\ndef get_irepo(url=None): ...\ndef get_parent_repo(url=None): ...\ndef get_parent_slug(url=None): ...\ndef get_org_name(): ...\ndef get_upstream_repo(): ...\ndef get_deploy_url(name=None, hoster=None): ...\ndef get_upstream_deploy_url(name=None, hoster='github'): ...\n", "repository": "coala/community", "test_name": "test_deploy_url", "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_000364.py"} {"focal_file": "coala_quickstart/generation/Bears.py", "focal_class": null, "focal_method": "filter_relevant_bears", "tests": "import unittest\n\nclass Test_filter_relevant_bears(unittest.TestCase):\n def test_filter_relevant_bears_simple(self):\n res = filter_relevant_bears([('Python', 70), ('C', 20)], self.printer, self.arg_parser, {})\n self.assertIn('C', res)\n self.assertIn('Python', res)\n self.assertTrue(len(res['C']) > 0)\n self.assertTrue(len(res['Python']) > 0)\n\n def test_filter_relevant_bears_green_mode(self):\n from argparse import Namespace\n from coalib.settings.ConfigurationGathering import get_filtered_bears\n self.arg_parser.parse_args = unittest.mock.MagicMock(return_value=Namespace(green_mode=True))\n res = filter_relevant_bears([('Python', 70), ('C', 20)], self.printer, self.arg_parser, {})\n all_bears = get_filtered_bears(['Python', 'C'])[0]\n bears = all_bears['cli']\n important_bears = []\n for bear_set in list(IMPORTANT_BEAR_LIST.values()):\n for bear in bear_set:\n important_bears.append(bear)\n bear_objs = []\n for bear in bears:\n if bear.__name__ in important_bears:\n bear_objs.append(bear)\n bear_obj_dict = dict()\n for key in ['Python', 'C', 'All']:\n bear_obj_dict[key] = set()\n for bear in IMPORTANT_BEAR_LIST[key]:\n if bear in GREEN_MODE_INCOMPATIBLE_BEAR_LIST:\n continue\n bear_obj_dict[key].update([x for x in bear_objs if x.__name__ == bear])\n self.maxDiff = None\n self.assertEqual(res, bear_obj_dict)\n\n def test_filter_relevant_bears_with_extracted_info(self):\n languages = [('JavaScript', 70), ('Ruby', 20)]\n res_1 = filter_relevant_bears(languages, self.printer, self.arg_parser, {})\n for lang, _ in languages:\n self.assertIn(lang, res_1)\n self.assertTrue(len(res_1[lang]) > 0)\n res_2 = []\n with generate_files(context_filenames, context_file_contents, self.project_dir) as gen_files:\n extracted_info = collect_info(self.project_dir)\n res_2 = filter_relevant_bears(languages, self.printer, self.arg_parser, extracted_info)\n for lang, _ in languages:\n self.assertIn(lang, res_2)\n self.assertTrue(len(res_2[lang]) > 0)\n additional_bears_by_lang = {'JavaScript': ['ESLintBear', 'HappinessLintBear'], 'Ruby': [], 'All': []}\n for lang in res_1:\n additional_bears = [bear.name for bear in res_2[lang] if bear not in res_1[lang]]\n for bear in additional_bears_by_lang[lang]:\n self.assertIn(bear, additional_bears)\n\n def test_filter_relevant_bears_with_non_optional_settings(self):\n sys.argv.append('--no-filter-by-capabilities')\n with bear_test_module():\n languages = []\n res_1 = filter_relevant_bears(languages, self.printer, self.arg_parser, {})\n res_2 = []\n with generate_files(context_filenames, context_file_contents, self.project_dir):\n with simulate_console_inputs('Yes') as generator:\n extracted_info = collect_info(self.project_dir)\n res_2 = filter_relevant_bears(languages, self.printer, self.arg_parser, extracted_info)\n self.assertEqual(generator.last_input, 0)\n additional_bears_by_lang = {'All': ['NonOptionalSettingBear']}\n for lang in res_1:\n additional_bears = [bear.name for bear in res_2[lang] if bear not in res_1[lang]]\n for bear in additional_bears_by_lang[lang]:\n self.assertIn(bear, additional_bears)\n res_2 = []\n with generate_files(context_filenames, context_file_contents, self.project_dir):\n with simulate_console_inputs('Some random text which will not be accepted', 'No') as generator:\n extracted_info = collect_info(self.project_dir)\n res_2 = filter_relevant_bears(languages, self.printer, self.arg_parser, extracted_info)\n self.assertEqual(generator.last_input, 1)\n additional_bears_by_lang = {'All': []}\n for lang in res_1:\n additional_bears = [bear.name for bear in res_2[lang] if bear not in res_1[lang]]\n for bear in additional_bears_by_lang[lang]:\n self.assertIn(bear, additional_bears)\n\n def test_filter_relevant_bears_with_capabilities(self):\n import coala_quickstart.generation.Bears as Bears\n Bears.IMPORTANT_BEARS_LIST = {}\n with bear_test_module():\n languages = []\n capability_to_select = 'Smell'\n cap_number = sorted(ALL_CAPABILITIES).index(capability_to_select) + 1\n res = []\n with simulate_console_inputs('1000', str(cap_number)) as generator:\n res = filter_relevant_bears(languages, self.printer, self.arg_parser, {})\n self.assertEqual(generator.last_input, 1)\n expected_results = {'All': set(['SmellCapabilityBear'])}\n for lang, lang_bears in expected_results.items():\n for bear in lang_bears:\n res_bears = [b.name for b in res[lang]]\n self.assertIn(bear, res_bears)\n\n def test_filter_relevant_bears_gruntfile_present(self):\n import coala_quickstart.generation.Bears as Bears\n Bears.IMPORTANT_BEARS_LIST = {'JavaScript': 'DoesNotExistBear', 'Python': 'DoesNotExistAsWellBear'}\n sys.argv.append('--no-filter-by-capabilities')\n with bear_test_module():\n languages = [('JavaScript', 70), ('Python', 20)]\n res = {}\n with generate_files(['Gruntfile.js'], [gruntfile], self.project_dir) as gen_files:\n extracted_info = collect_info(self.project_dir)\n res = filter_relevant_bears(languages, self.printer, self.arg_parser, extracted_info)\n expected_results = {'JavaScript': set(['SomeLinterBear'])}\n for lang, lang_bears in expected_results.items():\n for bear in lang_bears:\n res_bears = [b.name for b in res[lang]]\n self.assertIn(bear, res_bears)\n\n def test_filter_bears_ci_mode(self):\n sys.argv.append('--ci')\n with bear_test_module():\n languages = []\n res_1 = filter_relevant_bears(languages, self.printer, self.arg_parser, {})\n res_2 = []\n with generate_files(context_filenames, context_file_contents, self.project_dir):\n with simulate_console_inputs('Yes') as generator:\n extracted_info = collect_info(self.project_dir)\n res_2 = filter_relevant_bears(languages, self.printer, self.arg_parser, extracted_info)\n self.assertEqual(generator.last_input, -1)\n additional_bears_by_lang = {'All': []}\n for lang in res_1:\n additional_bears = [bear.name for bear in res_2[lang] if bear not in res_1[lang]]\n for bear in additional_bears_by_lang[lang]:\n self.assertIn(bear, additional_bears)\n", "method_code": "def filter_relevant_bears(used_languages, printer, arg_parser, extracted_info, log_printer=None):\n \"\"\"\n From the bear dict, filter the bears per relevant language.\n\n :param used_languages:\n A list of tuples with language name as the first element\n and percentage usage as the second element; sorted by\n percentage usage.\n :param printer:\n ``ConsolePrinter`` object to be used for console interactions.\n :param arg_parser:\n ``argparse.ArgumentParser`` object containing the arguments\n passed.\n :param extracted_info:\n list of information extracted from ``InfoExtractor`` classes.\n :return:\n A dict with language name as key and bear classes as value.\n \"\"\"\n args = arg_parser.parse_args() if arg_parser else None\n used_languages.append(('All', 100))\n bears_by_lang = {lang: set(inverse_dicts(*get_filtered_bears([lang], log_printer, arg_parser, silent=True)).keys()) for lang, _ in used_languages}\n all_lang_bears = bears_by_lang['All']\n bears_by_lang = {lang: bears_by_lang[lang] - bears_by_lang['All'] for lang, _ in used_languages}\n bears_by_lang['All'] = all_lang_bears\n selected_bears = {}\n candidate_bears = copy.copy(bears_by_lang)\n to_propose_bears = {}\n REQUIRED_BEAR_LIST = IMPORTANT_BEAR_LIST\n if args.green_mode:\n from coala_quickstart.Constants import GREEN_MODE_COMPATIBLE_BEAR_LIST, GREEN_MODE_INCOMPATIBLE_BEAR_LIST\n REQUIRED_BEAR_LIST = concatenate(IMPORTANT_BEAR_LIST, GREEN_MODE_COMPATIBLE_BEAR_LIST)\n NEW_REQUIRED_BEAR_LIST = {}\n for lang in REQUIRED_BEAR_LIST:\n NEW_REQUIRED_BEAR_LIST[lang] = set()\n for bear in REQUIRED_BEAR_LIST[lang]:\n if bear not in GREEN_MODE_INCOMPATIBLE_BEAR_LIST:\n NEW_REQUIRED_BEAR_LIST[lang].add(bear)\n REQUIRED_BEAR_LIST = NEW_REQUIRED_BEAR_LIST\n for lang, lang_bears in candidate_bears.items():\n if lang_bears and lang in REQUIRED_BEAR_LIST:\n selected_bears[lang] = set()\n for bear in lang_bears:\n if bear.__name__ in REQUIRED_BEAR_LIST[lang]:\n selected_bears[lang].add(bear)\n if lang_bears and lang not in REQUIRED_BEAR_LIST and (not args.green_mode):\n selected_bears[lang] = set(lang_bears)\n candidate_bears[lang] = set([bear for bear in lang_bears if lang in selected_bears and bear not in selected_bears[lang]])\n if args.green_mode:\n return selected_bears\n if not args.no_filter_by_capabilities:\n user_selected_capabilities = set()\n if not args.non_interactive:\n user_selected_capabilities = ask_to_select_capabilties(list(ALL_CAPABILITIES), list(DEFAULT_CAPABILTIES), printer)\n desired_capabilities = user_selected_capabilities if user_selected_capabilities else DEFAULT_CAPABILTIES\n for lang, lang_bears in candidate_bears.items():\n capable_bears = get_bears_with_given_capabilities(lang_bears, desired_capabilities)\n candidate_bears[lang] = capable_bears\n lint_task_info = extracted_info.get('LintTaskInfo', [])\n project_dependency_info = extracted_info.get('ProjectDependencyInfo', [])\n for lang, lang_bears in candidate_bears.items():\n matching_linter_bears = get_matching_linter_bears(lang_bears, lint_task_info)\n to_propose_bears[lang] = matching_linter_bears\n for lang, lang_bears in candidate_bears.items():\n matching_dep_bears = get_bears_with_matching_dependencies(lang_bears, project_dependency_info)\n if to_propose_bears.get(lang):\n to_propose_bears[lang].update(matching_dep_bears)\n else:\n to_propose_bears[lang] = matching_dep_bears\n for lang, lang_bears in to_propose_bears.items():\n for bear in lang_bears:\n settings = bear.get_non_optional_settings()\n if settings:\n user_input_reqd = False\n for setting in settings:\n if not is_autofill_possible(setting, lang, bear, extracted_info):\n user_input_reqd = True\n break\n if user_input_reqd:\n if args and (not args.non_interactive) and prompt_to_activate(bear, printer):\n selected_bears[lang].add(bear)\n else:\n selected_bears[lang].add(bear)\n else:\n selected_bears[lang].add(bear)\n if not args.no_filter_by_capabilities:\n satisfied_capabilities = get_bears_capabilties(selected_bears)\n remaining_capabilities = {lang: [cap for cap in desired_capabilities if lang in satisfied_capabilities and cap not in satisfied_capabilities[lang]] for lang in candidate_bears}\n filtered_bears = {}\n for lang, lang_bears in candidate_bears.items():\n filtered_bears[lang] = get_bears_with_given_capabilities(lang_bears, remaining_capabilities[lang])\n filtered_bears = remove_bears_with_conflicting_capabilties(filtered_bears)\n for lang, lang_bears in filtered_bears.items():\n if not selected_bears.get(lang):\n selected_bears[lang] = lang_bears\n else:\n selected_bears[lang].update(lang_bears)\n return selected_bears", "context": "def filter_relevant_bears(used_languages, printer, arg_parser, extracted_info, log_printer=None): ...\ndef filter_relevant_bears(used_languages, printer, arg_parser, extracted_info, log_printer=None): ...\ndef get_non_optional_settings(bears): ...\ndef get_non_optional_settings_bears(bears): ...\ndef remove_unusable_bears(bears, unusable_bears): ...\ndef print_relevant_bears(printer, relevant_bears, label='relevant'): ...\ndef generate_requirements_map(bears): ...\ndef get_bears_with_matching_dependencies(bears, dependency_info): ...\ndef get_matching_linter_bears(bears, lint_tasks_info): ...\ndef get_bears_with_given_capabilities(bears, capabilities): ...\ndef get_bears_capabilties(bears_by_lang): ...\ndef generate_capabilties_map(bears_by_lang): ...\ndef remove_bears_with_conflicting_capabilties(bears_by_lang): ...\ndef is_version_newer(semver1, semver2): ...\ndef prompt_to_activate(bear, printer): ...\ndef ask_to_select_capabilties(all_capabilities, default_capabilities, console_printer): ...\n", "repository": "coala/coala-quickstart", "test_name": "test_filter_relevant_bears_simple", "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, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000365.py"} {"focal_file": "coala_quickstart/generation/Bears.py", "focal_class": null, "focal_method": "print_relevant_bears", "tests": "import unittest\n\nclass Test_print_relevant_bears(unittest.TestCase):\n def test_print_relevant_bears(self):\n with retrieve_stdout() as custom_stdout:\n print_relevant_bears(self.printer, filter_relevant_bears([('Python', 70), ('Unknown', 30)], self.printer, self.arg_parser, {}))\n self.assertIn('PycodestyleBear', custom_stdout.getvalue())\n", "method_code": "def print_relevant_bears(printer, relevant_bears, label='relevant'):\n \"\"\"\n Prints the relevant bears in sections separated by language.\n\n :param printer:\n A ``ConsolePrinter`` object used for console interactions.\n :param relevant_bears:\n A dict with language name as key and bear classes as value.\n \"\"\"\n if label == 'relevant':\n printer.print(BEAR_HELP)\n printer.print('\\nBased on the languages used in project the following bears have been identified to be %s:' % label)\n for language in relevant_bears:\n printer.print(' [' + language + ']', color='green')\n for bear in relevant_bears[language]:\n printer.print(' ' + bear.name, color='cyan')\n printer.print('')", "context": "def print_relevant_bears(printer, relevant_bears, label='relevant'): ...\ndef filter_relevant_bears(used_languages, printer, arg_parser, extracted_info, log_printer=None): ...\ndef get_non_optional_settings(bears): ...\ndef get_non_optional_settings_bears(bears): ...\ndef remove_unusable_bears(bears, unusable_bears): ...\ndef print_relevant_bears(printer, relevant_bears, label='relevant'): ...\ndef generate_requirements_map(bears): ...\ndef get_bears_with_matching_dependencies(bears, dependency_info): ...\ndef get_matching_linter_bears(bears, lint_tasks_info): ...\ndef get_bears_with_given_capabilities(bears, capabilities): ...\ndef get_bears_capabilties(bears_by_lang): ...\ndef generate_capabilties_map(bears_by_lang): ...\ndef remove_bears_with_conflicting_capabilties(bears_by_lang): ...\ndef is_version_newer(semver1, semver2): ...\ndef prompt_to_activate(bear, printer): ...\ndef ask_to_select_capabilties(all_capabilities, default_capabilities, console_printer): ...\n", "repository": "coala/coala-quickstart", "test_name": "test_print_relevant_bears", "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_000366.py"} {"focal_file": "coala_quickstart/generation/FileGlobs.py", "focal_class": null, "focal_method": "get_project_files", "tests": "import unittest\n\nclass Test_get_project_files(unittest.TestCase):\n def test_get_project_files(self):\n orig_cwd = os.getcwd()\n os.chdir(os.path.dirname(os.path.realpath(__file__)))\n os.makedirs('file_globs_testfiles', exist_ok=True)\n os.chdir('file_globs_testfiles')\n os.makedirs('src', exist_ok=True)\n os.makedirs('ignore_dir', exist_ok=True)\n open(os.path.join('src', 'file.c'), 'w').close()\n open('root.c', 'w').close()\n open(os.path.join('ignore_dir', 'src.c'), 'w').close()\n open(os.path.join('ignore_dir', 'src.js'), 'w').close()\n with retrieve_stdout() as custom_stdout, simulate_console_inputs('ignore_dir/**'):\n res, _ = get_project_files(self.log_printer, self.printer, os.getcwd(), self.file_path_completer)\n self.assertIn(GLOB_HELP, custom_stdout.getvalue())\n self.assertIn(os.path.normcase(os.path.join(os.getcwd(), 'src', 'file.c')), res)\n self.assertIn(os.path.normcase(os.path.join(os.getcwd(), 'root.c')), res)\n self.assertNotIn(os.path.normcase(os.path.join(os.getcwd(), 'ignore_dir/src.c')), res)\n self.assertNotIn(os.path.normcase(os.path.join(os.getcwd(), 'ignore_dir/src.js')), res)\n os.chdir(orig_cwd)\n\n def test_get_project_files_gitignore(self):\n orig_cwd = os.getcwd()\n os.chdir(os.path.dirname(os.path.realpath(__file__)))\n os.makedirs('file_globs_gitignore_testfiles', exist_ok=True)\n os.chdir('file_globs_gitignore_testfiles')\n with open('.gitignore', 'w') as f:\n f.write('\\n# Start of gitignore\\nbuild\\nignore.c\\n/tests\\n/upload.c\\n/*.py\\n*.pyc\\n__pycache__\\n# End of gitignore')\n os.makedirs('another_folder', exist_ok=True)\n os.chdir('another_folder')\n with open('.gitignore', 'w') as f:\n f.write('\\n# Start of gitignore\\n*.js\\n# End of gitignore')\n os.chdir(os.path.dirname(os.path.realpath(__file__)))\n os.chdir('file_globs_gitignore_testfiles')\n os.makedirs('data', exist_ok=True)\n os.chdir('data')\n os.makedirs('sample', exist_ok=True)\n os.chdir('sample')\n with open('.gitignore', 'w') as f:\n f.write('\\n# Start of gitignore\\n*.html\\n# End of gitignore')\n os.chdir(os.path.dirname(os.path.realpath(__file__)))\n os.chdir('file_globs_gitignore_testfiles')\n files = [os.path.join('src', 'main.c'), os.path.join('src', 'main.h'), os.path.join('src', 'lib', 'ssl.c'), os.path.join('src', 'tests', 'main.c'), os.path.join('src', 'main.py'), os.path.join('src', 'upload.c'), os.path.join('another_folder', 'another_file.c'), os.path.join('data', 'sample', 'index.css'), os.path.join('data', 'example.py'), '.coafile']\n ignored_files = [os.path.join('build', 'main.c'), os.path.join('tests', 'run.c'), os.path.join('src', 'build', 'main.c'), 'ignore.c', os.path.join('src', 'ignore.c'), 'globexp.py', 'upload.c', os.path.join('src', 'main.pyc'), os.path.join('another_folder', 'script.js'), os.path.join('data', 'sample', 'index.html'), 'run.pyc']\n for file in files + ignored_files:\n os.makedirs(os.path.dirname(os.path.abspath(file)), exist_ok=True)\n open(file, 'w').close()\n files += ['.gitignore']\n files += [os.path.join('another_folder', '.gitignore')]\n files += [os.path.join('data', 'sample', '.gitignore')]\n gitignore_dir_list = [os.getcwd(), os.path.join(os.getcwd(), 'another_folder'), os.path.join(os.getcwd(), 'data', 'sample')]\n globs = list(get_gitignore_glob(os.getcwd(), gitignore_dir_list))\n returned_files = collect_files([os.path.join(os.getcwd(), '**')], self.log_printer, ignored_file_paths=globs)\n files = [os.path.normcase(os.path.abspath(file)) for file in files]\n ignored_files = [os.path.abspath(file) for file in ignored_files]\n self.maxDiff = None\n self.assertEqual(sorted(files), sorted(returned_files))\n with suppress_stdout():\n self.assertEqual(sorted(get_project_files(self.log_printer, self.printer, os.getcwd(), self.file_path_completer)[0]), sorted(files))\n os.remove(os.path.join('another_folder', '.gitignore'))\n os.remove(os.path.join('data', 'sample', '.gitignore'))\n os.remove('.gitignore')\n os.chdir(orig_cwd)\n\n def test_get_project_files_ci_mode(self):\n orig_cwd = os.getcwd()\n os.chdir(os.path.dirname(os.path.realpath(__file__)) + os.sep + 'file_globs_ci_testfiles')\n with suppress_stdout():\n res, _ = get_project_files(self.log_printer, self.printer, os.getcwd(), self.file_path_completer, True)\n paths = [os.path.join(os.getcwd(), 'src', 'file.c'), os.path.join(os.getcwd(), 'root.c'), os.path.join(os.getcwd(), 'ignore_dir', 'src.c'), os.path.join(os.getcwd(), 'ignore_dir', 'src.js')]\n for path in paths:\n self.assertIn(os.path.normcase(path), res)\n os.chdir(orig_cwd)\n", "method_code": "def get_project_files(log_printer, printer, project_dir, file_path_completer, non_interactive=False):\n \"\"\"\n Gets the list of files matching files in the user's project directory\n after prompting for glob expressions.\n\n :param log_printer:\n A ``LogPrinter`` object.\n :param printer:\n A ``ConsolePrinter`` object.\n :param file_path_completer:\n A ``file_path_completer`` object.\n :param non_interactive\n Whether coala-quickstart is in non-interactive mode\n :return:\n A list of file paths matching the files.\n \"\"\"\n file_globs = ['**']\n ignore_globs = None\n gitignore_dir_list = []\n for dir_name, subdir_name, file_list in os.walk(project_dir):\n if os.path.isfile(os.path.join(dir_name, '.gitignore')):\n gitignore_dir_list += [dir_name]\n if gitignore_dir_list:\n printer.print('The contents of your .gitignore file for the project will be automatically loaded as the files to ignore.', color='green')\n ignore_globs = get_gitignore_glob(project_dir, gitignore_dir_list)\n if non_interactive and (not ignore_globs):\n ignore_globs = []\n if ignore_globs is None:\n printer.print(GLOB_HELP)\n file_path_completer.activate(seed_dir=project_dir)\n ignore_globs = ask_question('Which files do you want coala to ignore inside the project directory?', printer=printer, typecast=list)\n file_path_completer.deactivate()\n printer.print()\n ignore_globs = list(ignore_globs)\n escaped_project_dir = glob_escape(project_dir)\n file_path_globs = [os.path.join(escaped_project_dir, glob_exp) for glob_exp in file_globs]\n ignore_path_globs = [os.path.join(escaped_project_dir, glob_exp) for glob_exp in ignore_globs]\n ignore_path_globs.append(os.path.join(escaped_project_dir, '.git/**'))\n file_paths = collect_files(file_path_globs, log_printer, ignored_file_paths=ignore_path_globs)\n return (file_paths, ignore_globs)", "context": "def get_project_files(log_printer, printer, project_dir, file_path_completer, non_interactive=False): ...\ndef get_project_files(log_printer, printer, project_dir, file_path_completer, non_interactive=False): ...\n", "repository": "coala/coala-quickstart", "test_name": "test_get_project_files", "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_000367.py"} {"focal_file": "coala_quickstart/generation/Project.py", "focal_class": null, "focal_method": "get_used_languages", "tests": "import unittest\n\nclass Test_get_used_languages(unittest.TestCase):\n def test_get_used_languages(self):\n file_lists = [['/tmp/file.py', '/tmp/file.py'], ['/tmp/file.py', '/tmp/test.cpp'], ['/tmp/file.py'], ['/tmp/file.py', '/tmp/unknown.extension'], ['/tmp/unknown.extension'], []]\n results = [[('Python', 100)], [('Python', 50), ('C++', 50)], [('Python', 100)], [('Python', 50)], [], []]\n for file_list, expected_result in zip(file_lists, results):\n result = get_used_languages(file_list)\n self.assertEqual(sorted(result), sorted(expected_result))\n", "method_code": "def get_used_languages(file_paths):\n \"\"\"\n Identifies the most used languages in the user's project directory\n from the files matched from the given glob expression.\n\n :param file_paths:\n A list of absolute file paths in the user's project directory.\n :return:\n A tuple iterator containing a language name as the first value\n and percentage usage in the project as the second value.\n \"\"\"\n return sorted(language_percentage(file_paths).items(), key=operator.itemgetter(1), reverse=True)", "context": "def get_used_languages(file_paths): ...\ndef valid_path(path: StringConverter): ...\ndef language_percentage(file_paths): ...\ndef get_used_languages(file_paths): ...\ndef ask_to_select_languages(languages, printer, non_interactive): ...\ndef print_used_languages(printer, results, non_interactive=True): ...\n", "repository": "coala/coala-quickstart", "test_name": "test_get_used_languages", "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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000368.py"} {"focal_file": "coala_quickstart/generation/Project.py", "focal_class": null, "focal_method": "print_used_languages", "tests": "import unittest\n\nclass Test_print_used_languages(unittest.TestCase):\n def test_print_used_languages(self):\n with retrieve_stdout() as custom_stdout:\n print_used_languages(self.printer, [('Python', 100)])\n res = custom_stdout.getvalue()\n self.assertIn('Python', res)\n self.assertIn('100%', res)\n print_used_languages(self.printer, [('Python', 100)], False)\n res = custom_stdout.getvalue()\n self.assertIn('Python', res)\n self.assertIn('100%', res)\n ask_to_select_languages([('Python', 100)], self.printer, True)\n res = custom_stdout.getvalue()\n self.assertIn('Python', res)\n self.assertIn('100%', res)\n with retrieve_stdout() as custom_stdout:\n print_used_languages(self.printer, [('Python', 75), ('C++', 25)])\n self.assertIn('75%\\n', custom_stdout.getvalue())\n", "method_code": "def print_used_languages(printer, results, non_interactive=True):\n \"\"\"\n Prints the sorted list of used languages along with each language's\n percentage use.\n\n :param printer:\n A ``ConsolePrinter`` object used for console interactions.\n :param results:\n A list of tuples containing a language name as the first value\n and percentage usage in the project as the second value.\n :param non_interactive:\n Variable that defines whether quickstart is in non_interactive\n mode or not.\n \"\"\"\n if non_interactive:\n printer.print('The following languages have been automatically detected:\\n')\n else:\n printer.print('The following languages have been selected by you:\\n')\n for lang, percent in results:\n formatted_line = '{:>25}: {:>2}%'.format(lang, int(percent))\n printer.print(formatted_line, color='cyan')\n printer.print()", "context": "def print_used_languages(printer, results, non_interactive=True): ...\ndef valid_path(path: StringConverter): ...\ndef language_percentage(file_paths): ...\ndef get_used_languages(file_paths): ...\ndef ask_to_select_languages(languages, printer, non_interactive): ...\ndef print_used_languages(printer, results, non_interactive=True): ...\n", "repository": "coala/coala-quickstart", "test_name": "test_print_used_languages", "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, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000369.py"} {"focal_file": "coala_quickstart/generation/Project.py", "focal_class": null, "focal_method": "ask_to_select_languages", "tests": "import unittest\n\nclass Test_ask_to_select_languages(unittest.TestCase):\n def test_ask_to_select_languages(self):\n languages = [('lang1', 50), ('lang2', 25), ('language3', 25)]\n res = []\n with simulate_console_inputs('1 2') as generator:\n res = ask_to_select_languages(languages, self.printer, False)\n self.assertEqual(generator.last_input, 0)\n self.assertEqual(res, [('lang1', 50), ('lang2', 25)])\n with simulate_console_inputs('6', '1') as generator:\n res = ask_to_select_languages(languages, self.printer, False)\n self.assertEqual(generator.last_input, 1)\n self.assertEqual(res, [('lang1', 50)])\n with simulate_console_inputs('\\n') as generator:\n res = ask_to_select_languages(languages, self.printer, False)\n self.assertEqual(generator.last_input, 0)\n self.assertEqual(res, [('lang1', 50), ('lang2', 25), ('language3', 25)])\n", "method_code": "def ask_to_select_languages(languages, printer, non_interactive):\n if non_interactive:\n print_used_languages(printer, languages, non_interactive)\n return languages\n only_languages = []\n percentages = []\n max_length = -1\n for language in languages:\n only_languages.append(language[0])\n percentages.append(language[1])\n if len(language[0]) > max_length:\n max_length = len(language[0])\n total_options = len(only_languages) + 1\n printer.print(ASK_TO_SELECT_LANG, color='yellow')\n for idx, lang in enumerate(only_languages):\n num_spaces = max_length - len(lang)\n spaces = ''\n for i in range(num_spaces):\n spaces += ' '\n printer.print(' {}. {}{} {:>2}%'.format(idx + 1, lang, spaces, int(percentages[idx])))\n selected_numbers = []\n try:\n selected_numbers = list(map(int, re.split('\\\\D+', input())))\n except Exception:\n selected_numbers = [total_options]\n selected_languages = []\n for num in selected_numbers:\n if num >= 0 and num < total_options:\n selected_languages.append(languages[int(num) - 1])\n elif num == total_options:\n selected_languages = languages\n else:\n printer.print('{} is not a valid option. Please choose the right option numbers'.format(str(num)))\n return ask_to_select_languages(languages, printer, False)\n print_used_languages(printer, selected_languages, False)\n return selected_languages", "context": "def ask_to_select_languages(languages, printer, non_interactive): ...\ndef valid_path(path: StringConverter): ...\ndef language_percentage(file_paths): ...\ndef get_used_languages(file_paths): ...\ndef ask_to_select_languages(languages, printer, non_interactive): ...\ndef print_used_languages(printer, results, non_interactive=True): ...\n", "repository": "coala/coala-quickstart", "test_name": "test_ask_to_select_languages", "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, 0, 0, 0], "pynose_source_file": "test_000370.py"} {"focal_file": "coala_quickstart/generation/SettingsClass.py", "focal_class": null, "focal_method": "collect_bear_settings", "tests": "import unittest\n\nclass Test_collect_bear_settings(unittest.TestCase):\n def test_collect_bear_settings(self):\n relevant_bears = {'test': {AllKindsOfSettingsDependentBear, AllKindsOfSettingsDependentDecoratedBear, AllKindsOfSettingsBaseBear, BearA, SomeLinterBear, LinterBearWithCreateArguments, LinterBearWithParameters}}\n bear_settings_obj = collect_bear_settings(relevant_bears)\n k = 0\n for index, i in enumerate(bear_settings_obj):\n if i.bear == AllKindsOfSettingsDependentBear:\n k = index\n break\n obj = bear_settings_obj[k].non_optional_settings\n self.assertCountEqual(obj.settings_bool, ['use_bear', 'use_bears'])\n self.assertCountEqual(obj.settings_others, ['config', 'max_line_lengths', 'no_line', 'configs', 'no_lines'])\n obj = bear_settings_obj[k].optional_settings\n self.assertCountEqual(obj.settings_bool, ['use_spaces', 'use_tabs', 'chars', 'use_space', 'use_tab'])\n self.assertCountEqual(obj.settings_others, ['max_line_lengths', 'no_chars', 'dependency_results', 'dependency_result', 'no_char', 'max_line_length'])\n for index, i in enumerate(bear_settings_obj):\n if i.bear == AllKindsOfSettingsDependentDecoratedBear:\n k = index\n break\n obj = bear_settings_obj[k].non_optional_settings\n self.assertCountEqual(obj.settings_bool, ['use_bear', 'use_bears'])\n self.assertCountEqual(obj.settings_others, ['config', 'max_line_lengths', 'no_line', 'configs', 'no_lines'])\n obj = bear_settings_obj[k].optional_settings\n self.assertCountEqual(obj.settings_bool, ['use_spaces', 'use_tabs', 'chars', 'use_space', 'use_tab'])\n self.assertCountEqual(obj.settings_others, ['max_line_lengths', 'no_chars', 'dependency_results', 'dependency_result', 'no_char', 'max_line_length'])\n for index, i in enumerate(bear_settings_obj):\n if i.bear == AllKindsOfSettingsBaseBear:\n k = index\n break\n obj = bear_settings_obj[k].non_optional_settings\n self.assertCountEqual(obj.settings_bool, ['use_bear'])\n self.assertCountEqual(obj.settings_others, ['config', 'max_line_lengths', 'no_line'])\n obj = bear_settings_obj[k].optional_settings\n self.assertCountEqual(obj.settings_bool, ['use_space', 'use_tab'])\n self.assertCountEqual(obj.settings_others, ['max_line_length', 'no_char', 'dependency_result'])\n for index, i in enumerate(bear_settings_obj):\n if i.bear == BearA:\n k = index\n break\n obj = bear_settings_obj[k].non_optional_settings\n self.assertCountEqual(obj.settings_bool, ['use_spaces'])\n self.assertCountEqual(obj.settings_others, [])\n obj = bear_settings_obj[k].optional_settings\n self.assertCountEqual(obj.settings_bool, [])\n self.assertCountEqual(obj.settings_others, ['a'])\n for index, i in enumerate(bear_settings_obj):\n if i.bear == SomeLinterBear:\n k = index\n break\n obj = bear_settings_obj[k].non_optional_settings\n self.assertCountEqual(obj.settings_bool, [])\n self.assertCountEqual(obj.settings_others, [])\n obj = bear_settings_obj[k].optional_settings\n self.assertCountEqual(obj.settings_bool, [])\n self.assertCountEqual(obj.settings_others, [])\n for index, i in enumerate(bear_settings_obj):\n if i.bear == LinterBearWithParameters:\n k = index\n break\n obj = bear_settings_obj[k].non_optional_settings\n self.assertCountEqual(obj.settings_bool, [])\n self.assertCountEqual(obj.settings_others, ['nonopsetting'])\n obj = bear_settings_obj[k].optional_settings\n self.assertCountEqual(obj.settings_bool, ['someoptionalsetting'])\n self.assertCountEqual(obj.settings_others, [])\n for index, i in enumerate(bear_settings_obj):\n if i.bear == LinterBearWithCreateArguments:\n k = index\n break\n obj = bear_settings_obj[k].non_optional_settings\n self.assertCountEqual(obj.settings_bool, ['yes'])\n self.assertCountEqual(obj.settings_others, ['nonopsetting', 'rick'])\n obj = bear_settings_obj[k].optional_settings\n self.assertCountEqual(obj.settings_bool, ['someoptionalsetting'])\n self.assertCountEqual(obj.settings_others, ['makman2'])\n", "method_code": "def collect_bear_settings(bears):\n \"\"\"\n :param bears:\n Dict of candidate bears for the project for each language.\n :return:\n A BearSettings object.\n \"\"\"\n bear_settings_obj = []\n for language in bears:\n for bear in bears[language]:\n bear_settings_obj.append(BearSettings(bear))\n return bear_settings_obj", "context": "def collect_bear_settings(bears): ...\ndef in_annot(func, key): ...\ndef in_annot_recursive(bear, key): ...\ndef in_default_args(func, key): ...\ndef in_all_args(func, key): ...\ndef parse_dep_tree_optional(bear): ...\ndef collect_bear_settings(bears): ...\n", "repository": "coala/coala-quickstart", "test_name": "test_collect_bear_settings", "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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000371.py"} {"focal_file": "coala_quickstart/generation/SettingsFilling.py", "focal_class": null, "focal_method": "acquire_settings", "tests": "import unittest\n\nclass Test_acquire_settings(unittest.TestCase):\n def test_acquire_settings_error(self):\n with self.assertRaises(TypeError):\n acquire_settings(1, 2, 3)\n", "method_code": "def acquire_settings(log_printer, settings_dict, section):\n \"\"\"\n This method prompts the user for the given settings.\n\n :param log_printer:\n Printer responsible for logging the messages. This is needed to comply\n with the interface.\n :param settings_names_dict:\n A dictionary with the settings name as key of the following form\n\n ::\n\n {\n \"some_setting\": {\n \"help_text\": \"help string for the setting\",\n \"bears\": [SomeBear\", \"SomeOtherBear\"],\n \"type\": bool\n }\n\n :param section:\n The section the action corresponds to.\n :return:\n A dictionary with the settings name as key and the given value as\n value.\n \"\"\"\n if not isinstance(settings_dict, dict):\n raise TypeError('The settings_names_dict parameter has to be a dictionary.')\n result = {}\n for setting_name, setting_info in sorted(settings_dict.items(), key=lambda x: (join_names(x[1]['bears']), x[0])):\n if setting_name == 'language':\n value = section.name\n else:\n value = require_setting(setting_name, setting_info, section)\n result.update({setting_name: value} if value is not None else {})\n return result", "context": "def acquire_settings(log_printer, settings_dict, section): ...\ndef fill_section(section, acquire_settings, log_printer, bears, extracted_info): ...\ndef autofill_value(setting_key, section, bears, extracted_information): ...\ndef is_autofill_possible(setting_key, section, bears, extracted_info): ...\ndef resolve_anomaly(setting_name, help_string, associated_bears, values): ...\ndef require_setting(setting_name, setting_info, section): ...\ndef acquire_settings(log_printer, settings_dict, section): ...\n", "repository": "coala/coala-quickstart", "test_name": "test_acquire_settings_error", "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_000372.py"} {"focal_file": "coala_quickstart/generation/SettingsFilling.py", "focal_class": null, "focal_method": "fill_section", "tests": "import unittest\n\nclass Test_fill_section(unittest.TestCase):\n def test_fill_section(self):\n with simulate_console_inputs(0, 0):\n new_section = fill_section(self.section, acquire_settings, self.log_printer, [LocalTestBear, GlobalTestBear], {})\n self.assertEqual(int(new_section['local name']), 0)\n self.assertEqual(int(new_section['global name']), 0)\n self.assertEqual(new_section['key'].value, 'val')\n self.assertEqual(len(new_section.contents), 3)\n new_section = fill_section(self.section, acquire_settings, self.log_printer, [LocalTestBear, GlobalTestBear], {})\n self.assertTrue('local name' in new_section)\n self.assertTrue('global name' in new_section)\n self.assertEqual(new_section['key'].value, 'val')\n self.assertEqual(len(new_section.contents), 3)\n\n def test_fill_section_invalid_type(self):\n with simulate_console_inputs('fd', 'fd', 0, 0) as generator:\n new_section = fill_section(self.section, acquire_settings, self.log_printer, [LocalTestBear, GlobalTestBear], {})\n self.assertEqual(generator.last_input, 3)\n self.assertEqual(int(new_section['local name']), 0)\n self.assertEqual(int(new_section['global name']), 0)\n self.assertEqual(new_section['key'].value, 'val')\n self.assertEqual(len(new_section.contents), 3)\n", "method_code": "def fill_section(section, acquire_settings, log_printer, bears, extracted_info):\n \"\"\"\n Retrieves needed settings from given bears and asks the user for\n missing values.\n\n If a setting is requested by several bears, the help text from the\n latest bear will be taken.\n\n :param section: A section containing available settings. Settings\n will be added if some are missing.\n :param acquire_settings: The method to use for requesting settings. It will\n get a parameter which is a dictionary with the\n settings name as key and a list containing a\n description in [0] and the names of the bears\n who need this setting in all following indexes.\n :param log_printer: The log printer for logging.\n :param bears: All bear classes or instances.\n :param extracted_info: A list of information extracted from the project\n files by ``InfoExtractor`` classes.\n :return: The new section.\n \"\"\"\n prel_needed_settings = {}\n for bear in bears:\n needed = bear.get_non_optional_settings()\n for key in needed:\n if key in prel_needed_settings:\n prel_needed_settings[key]['bears'].append(bear.name)\n else:\n prel_needed_settings[key] = {'help_text': needed[key][0], 'bears': [bear.name], 'type': needed[key][1]}\n needed_settings = {}\n for setting, setting_info in prel_needed_settings.items():\n if setting not in section:\n needed_settings[setting] = setting_info\n satisfied_settings = []\n for setting in needed_settings.keys():\n setting_bears = needed_settings[setting]['bears']\n setting_help_text = needed_settings[setting]['help_text']\n to_fill_values = list(autofill_value(setting, section, setting_bears, extracted_info))\n if len(set(to_fill_values)) == 1:\n section[setting] = to_fill_values[0]\n satisfied_settings.append(setting)\n elif len(to_fill_values) > 1:\n section[setting] = resolve_anomaly(setting, setting_help_text, setting_bears, to_fill_values)\n satisfied_settings.append(setting)\n else:\n pass\n for setting in satisfied_settings:\n del needed_settings[setting]\n if len(needed_settings) > 0:\n new_vals = acquire_settings(log_printer, needed_settings, section)\n for setting, help_text in new_vals.items():\n section.append(Setting(setting, help_text))\n return section", "context": "def fill_section(section, acquire_settings, log_printer, bears, extracted_info): ...\ndef fill_section(section, acquire_settings, log_printer, bears, extracted_info): ...\ndef autofill_value(setting_key, section, bears, extracted_information): ...\ndef is_autofill_possible(setting_key, section, bears, extracted_info): ...\ndef resolve_anomaly(setting_name, help_string, associated_bears, values): ...\ndef require_setting(setting_name, setting_info, section): ...\ndef acquire_settings(log_printer, settings_dict, section): ...\n", "repository": "coala/coala-quickstart", "test_name": "test_fill_section", "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_000373.py"} {"focal_file": "coala_quickstart/generation/Settings.py", "focal_class": null, "focal_method": "write_info", "tests": "import unittest\n\nclass Test_write_info(unittest.TestCase):\n def test_write_info(self):\n result_date = date.today().strftime('%d %b %Y')\n result_comment = '# Generated by coala-quickstart on {date}.\\n'.format(date=result_date)\n write_info(self.writer)\n self.writer.close()\n with open(self.coafile, 'r') as f:\n line = f.readline()\n self.assertEqual(result_comment, line)\n", "method_code": "def write_info(writer):\n \"\"\"\n Writes the generator information and generation date in the coafile.\n\n :param writer:\n A ``ConfWriter`` object used for writing the information.\n \"\"\"\n generation_date = date.today().strftime('%d %b %Y')\n generation_comment = '# Generated by coala-quickstart on {date}.\\n'.format(date=generation_date)\n writer._ConfWriter__file.write(generation_comment)", "context": "def write_info(writer): ...\ndef generate_section(section_name, extensions_used, bears): ...\ndef generate_ignore_field(project_dir, languages, extset, ignore_globs, null_printer=None): ...\ndef generate_settings(project_dir, project_files, ignore_globs, relevant_bears, extracted_info, incomplete_sections=False, log_printer=None): ...\ndef write_info(writer): ...\ndef write_coafile(printer, project_dir, settings): ...\n", "repository": "coala/coala-quickstart", "test_name": "test_write_info", "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_000374.py"} {"focal_file": "coala_quickstart/generation/Utilities.py", "focal_class": null, "focal_method": "search_for_orig", "tests": "import unittest\n\nclass Test_search_for_orig(unittest.TestCase):\n def test_search_for_orig(self):\n self.assertEqual(types.MethodType(search_for_orig(self.third, 'first'), self), self.first)\n self.assertEqual(types.MethodType(search_for_orig(self.fourth, 'first'), self), self.first)\n self.assertEqual(search_for_orig(self.first, 'first'), None)\n self.assertEqual(search_for_orig(self.first, 'bar'), None)\n self.assertEqual(search_for_orig(self.first, 'first'), None)\n self.assertEqual(search_for_orig(foo, 'bar'), None)\n self.assertEqual(search_for_orig(foo, 'foo'), None)\n func = foo_bar(3)\n self.assertEqual(search_for_orig(func, 'bar'), None)\n", "method_code": "def search_for_orig(decorated, orig_name):\n \"\"\"\n Extracts out the original function if the function is decorated with\n one or more decorators.\n :param decorated:\n The decorated function object.\n :param orig_name:\n The name of the original function.\n :return:\n None or the original function object.\n \"\"\"\n if decorated.__closure__ is not None:\n for obj in (c.cell_contents for c in decorated.__closure__):\n if hasattr(obj, '__name__') and obj.__name__ == orig_name:\n return obj\n if hasattr(obj, '__closure__') and obj.__closure__:\n found = search_for_orig(obj, orig_name)\n return found", "context": "def search_for_orig(decorated, orig_name): ...\ndef is_glob_exp(line): ...\ndef parse_gitignore_line(line): ...\ndef get_gitignore_glob(project_dir, gitignore_dir_list, filename='.gitignore'): ...\ndef split_by_language(project_files): ...\ndef get_extensions(project_files): ...\ndef get_default_args(func): ...\ndef get_all_args(func): ...\ndef search_for_orig(decorated, orig_name): ...\ndef get_hashbang(file_path): ...\ndef get_language_from_hashbang(hashbang): ...\ndef concatenate(dict1, dict2): ...\ndef peek(iterable): ...\ndef contained_in(smaller, bigger): ...\ndef get_yaml_contents(project_data): ...\ndef dump_yaml_to_file(file, contents): ...\ndef append_to_contents(contents, key, values, settings_key): ...\n", "repository": "coala/coala-quickstart", "test_name": "test_search_for_orig", "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, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000375.py"} {"focal_file": "coala_quickstart/generation/Utilities.py", "focal_class": null, "focal_method": "get_default_args", "tests": "import unittest\n\nclass Test_get_default_args(unittest.TestCase):\n def test_get_default_args(self):\n self.assertEqual(get_default_args(AllKindsOfSettingsDependentBear.run), {'chars': False, 'dependency_results': {}, 'max_line_lengths': 1000, 'no_chars': 79, 'use_spaces': None, 'use_tabs': False})\n", "method_code": "def get_default_args(func):\n \"\"\"\n :param func: Function name.\n :return:\n A dict of function paramters as keys\n and default values as value if default values exist.\n \"\"\"\n signature = inspect.signature(func)\n return {k: v.default for k, v in signature.parameters.items() if v.default is not inspect.Parameter.empty}", "context": "def get_default_args(func): ...\ndef is_glob_exp(line): ...\ndef parse_gitignore_line(line): ...\ndef get_gitignore_glob(project_dir, gitignore_dir_list, filename='.gitignore'): ...\ndef split_by_language(project_files): ...\ndef get_extensions(project_files): ...\ndef get_default_args(func): ...\ndef get_all_args(func): ...\ndef search_for_orig(decorated, orig_name): ...\ndef get_hashbang(file_path): ...\ndef get_language_from_hashbang(hashbang): ...\ndef concatenate(dict1, dict2): ...\ndef peek(iterable): ...\ndef contained_in(smaller, bigger): ...\ndef get_yaml_contents(project_data): ...\ndef dump_yaml_to_file(file, contents): ...\ndef append_to_contents(contents, key, values, settings_key): ...\n", "repository": "coala/coala-quickstart", "test_name": "test_get_default_args", "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_000376.py"} {"focal_file": "coala_quickstart/generation/Utilities.py", "focal_class": null, "focal_method": "get_all_args", "tests": "import unittest\n\nclass Test_get_all_args(unittest.TestCase):\n def test_get_all_args(self):\n empty = inspect._empty\n self.assertEqual(get_all_args(AllKindsOfSettingsDependentBear.run), {'self': empty, 'file': empty, 'filename': empty, 'configs': empty, 'use_bears': empty, 'no_lines': empty, 'use_spaces': None, 'use_tabs': False, 'max_line_lengths': 1000, 'no_chars': 79, 'chars': False, 'dependency_results': {}})\n", "method_code": "def get_all_args(func):\n \"\"\"\n :param func: Function name.\n :return:\n A dict of function paramters as keys\n and default values as value.\n \"\"\"\n signature = inspect.signature(func)\n return {k: v.default for k, v in signature.parameters.items()}", "context": "def get_all_args(func): ...\ndef is_glob_exp(line): ...\ndef parse_gitignore_line(line): ...\ndef get_gitignore_glob(project_dir, gitignore_dir_list, filename='.gitignore'): ...\ndef split_by_language(project_files): ...\ndef get_extensions(project_files): ...\ndef get_default_args(func): ...\ndef get_all_args(func): ...\ndef search_for_orig(decorated, orig_name): ...\ndef get_hashbang(file_path): ...\ndef get_language_from_hashbang(hashbang): ...\ndef concatenate(dict1, dict2): ...\ndef peek(iterable): ...\ndef contained_in(smaller, bigger): ...\ndef get_yaml_contents(project_data): ...\ndef dump_yaml_to_file(file, contents): ...\ndef append_to_contents(contents, key, values, settings_key): ...\n", "repository": "coala/coala-quickstart", "test_name": "test_get_all_args", "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_000377.py"} {"focal_file": "coala_quickstart/generation/Utilities.py", "focal_class": null, "focal_method": "get_hashbang", "tests": "import unittest\n\nclass Test_get_hashbang(unittest.TestCase):\n def test_with_bash(self):\n with NamedTemporaryFile(mode='w+t', delete=False) as temp_file:\n temp_file.write('#!bin/bash\\n')\n temp_file.close()\n self.assertEqual(get_hashbang(temp_file.name), '#!bin/bash')\n\n def test_with_slash(self):\n with NamedTemporaryFile(mode='w+t', delete=False) as temp_file:\n temp_file.write('#!/bin/bash\\n')\n temp_file.close()\n self.assertEqual(get_hashbang(temp_file.name), '#!/bin/bash')\n\n def test_no_bang(self):\n with NamedTemporaryFile(mode='w+t', delete=False) as temp_file:\n temp_file.write('#bin/bash')\n temp_file.close()\n self.assertIsNone(get_hashbang(temp_file.name))\n\n def test_no_hash(self):\n with NamedTemporaryFile(mode='w+t', delete=False) as temp_file:\n temp_file.write('!bin/bash')\n temp_file.close()\n self.assertIsNone(get_hashbang(temp_file.name))\n", "method_code": "def get_hashbang(file_path):\n if not os.path.exists(file_path):\n return\n try:\n with open(file_path, 'r') as data:\n hashbang = data.readline()\n except UnicodeDecodeError:\n return\n hashbang = hashbang.strip()\n if not hashbang:\n return\n if not re.match(HASHBANG_REGEX, hashbang):\n return\n return hashbang", "context": "def get_hashbang(file_path): ...\ndef is_glob_exp(line): ...\ndef parse_gitignore_line(line): ...\ndef get_gitignore_glob(project_dir, gitignore_dir_list, filename='.gitignore'): ...\ndef split_by_language(project_files): ...\ndef get_extensions(project_files): ...\ndef get_default_args(func): ...\ndef get_all_args(func): ...\ndef search_for_orig(decorated, orig_name): ...\ndef get_hashbang(file_path): ...\ndef get_language_from_hashbang(hashbang): ...\ndef concatenate(dict1, dict2): ...\ndef peek(iterable): ...\ndef contained_in(smaller, bigger): ...\ndef get_yaml_contents(project_data): ...\ndef dump_yaml_to_file(file, contents): ...\ndef append_to_contents(contents, key, values, settings_key): ...\n", "repository": "coala/coala-quickstart", "test_name": "test_with_bash", "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_000378.py"} {"focal_file": "coala_quickstart/generation/Utilities.py", "focal_class": null, "focal_method": "get_language_from_hashbang", "tests": "import unittest\n\nclass Test_get_language_from_hashbang(unittest.TestCase):\n def test_get_language_from_hashbang(self):\n self.assertEqual(get_language_from_hashbang('#!/usr/bin/env python'), 'python')\n self.assertEqual(get_language_from_hashbang('#!bin/bash'), 'bash')\n self.assertEqual(get_language_from_hashbang('#!/bin/bash'), 'bash')\n", "method_code": "def get_language_from_hashbang(hashbang):\n assert hashbang\n if hashbang:\n hashbang_contents = hashbang.split(' ')\n try:\n return hashbang_contents[1]\n except IndexError:\n hashbang_element = hashbang_contents[0].split('/')\n return hashbang_element[len(hashbang_element) - 1]", "context": "def get_language_from_hashbang(hashbang): ...\ndef is_glob_exp(line): ...\ndef parse_gitignore_line(line): ...\ndef get_gitignore_glob(project_dir, gitignore_dir_list, filename='.gitignore'): ...\ndef split_by_language(project_files): ...\ndef get_extensions(project_files): ...\ndef get_default_args(func): ...\ndef get_all_args(func): ...\ndef search_for_orig(decorated, orig_name): ...\ndef get_hashbang(file_path): ...\ndef get_language_from_hashbang(hashbang): ...\ndef concatenate(dict1, dict2): ...\ndef peek(iterable): ...\ndef contained_in(smaller, bigger): ...\ndef get_yaml_contents(project_data): ...\ndef dump_yaml_to_file(file, contents): ...\ndef append_to_contents(contents, key, values, settings_key): ...\n", "repository": "coala/coala-quickstart", "test_name": "test_get_language_from_hashbang", "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_000379.py"} {"focal_file": "coala_quickstart/generation/Utilities.py", "focal_class": null, "focal_method": "split_by_language", "tests": "import unittest\n\nclass Test_split_by_language(unittest.TestCase):\n def test_split_by_language(self):\n with NamedTemporaryFile(delete=False, suffix='.py') as temp_file1, NamedTemporaryFile(delete=False, suffix='.txt') as temp_file2, NamedTemporaryFile(delete=False, suffix='.txt') as temp_file3:\n temp_file3.write(b'#!bin/python')\n temp_file3.close()\n langs = split_by_language([temp_file1.name, temp_file2.name, temp_file3.name])\n self.assertCountEqual(langs, {'all': [temp_file1.name, temp_file3.name], 'python': [temp_file1.name, temp_file3.name]})\n", "method_code": "def split_by_language(project_files):\n \"\"\"\n Splits the given files based on language. This ignores unknown extensions.\n\n :param project_files: A list of file paths.\n :return: A dict with language name as keys and a list of\n files coming under that language as values.\n \"\"\"\n lang_files = defaultdict(lambda: set())\n for file in project_files:\n name, ext = os.path.splitext(file)\n if ext in exts:\n for lang in exts[ext]:\n lang_files[lang.lower()].add(file)\n lang_files['all'].add(file)\n continue\n hashbang = get_hashbang(file)\n if not hashbang:\n continue\n language = get_language_from_hashbang(hashbang).lower()\n for ext in exts:\n for lang in exts[ext]:\n if language == lang.lower():\n lang_files[lang.lower()].add(file)\n lang_files['all'].add(file)\n return lang_files", "context": "def split_by_language(project_files): ...\ndef is_glob_exp(line): ...\ndef parse_gitignore_line(line): ...\ndef get_gitignore_glob(project_dir, gitignore_dir_list, filename='.gitignore'): ...\ndef split_by_language(project_files): ...\ndef get_extensions(project_files): ...\ndef get_default_args(func): ...\ndef get_all_args(func): ...\ndef search_for_orig(decorated, orig_name): ...\ndef get_hashbang(file_path): ...\ndef get_language_from_hashbang(hashbang): ...\ndef concatenate(dict1, dict2): ...\ndef peek(iterable): ...\ndef contained_in(smaller, bigger): ...\ndef get_yaml_contents(project_data): ...\ndef dump_yaml_to_file(file, contents): ...\ndef append_to_contents(contents, key, values, settings_key): ...\n", "repository": "coala/coala-quickstart", "test_name": "test_split_by_language", "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_000380.py"} {"focal_file": "coala_quickstart/generation/Utilities.py", "focal_class": null, "focal_method": "concatenate", "tests": "import unittest\n\nclass Test_concatenate(unittest.TestCase):\n def test_concatenate(self):\n dict1 = {'1': {'a', 'b', 'c'}, '2': {'d', 'e', 'f'}, '3': {'g', 'h', 'i'}}\n dict2 = {'4': {'j', 'k', 'l'}, '2': {'m', 'n', 'o'}, '5': {'p', 'q', 'r'}}\n result_dict = {'1': {'a', 'b', 'c'}, '2': {'d', 'e', 'f', 'm', 'n', 'o'}, '3': {'g', 'h', 'i'}, '4': {'j', 'k', 'l'}, '5': {'p', 'q', 'r'}}\n ret_val = concatenate(dict1, dict2)\n self.assertEqual(ret_val, result_dict)\n", "method_code": "def concatenate(dict1, dict2):\n \"\"\"\n Concatenates 2 dicts of the type:\n eg.\n >>> dict1 = {\n ... 'key1': {'value1', 'value2'},\n ... 'key2': {'value3', 'value4'}}\n >>> dict2 = {\n ... 'key2': {'value4', 'value5'},\n ... 'key3': {'value6', 'value7'}}\n >>> dict3 = concatenate(dict1, dict2)\n >>> for key in sorted(dict3):\n ... sorted(dict3[key])\n ...\n ['value1', 'value2']\n ['value3', 'value4', 'value5']\n ['value6', 'value7']\n\n :return:\n The concatenated dict.\n \"\"\"\n for key in dict1:\n if key in dict2:\n dict1[key] = dict1[key].union(dict2[key])\n for key in dict2:\n if key not in dict1:\n dict1[key] = dict2[key]\n return dict1", "context": "def concatenate(dict1, dict2): ...\ndef is_glob_exp(line): ...\ndef parse_gitignore_line(line): ...\ndef get_gitignore_glob(project_dir, gitignore_dir_list, filename='.gitignore'): ...\ndef split_by_language(project_files): ...\ndef get_extensions(project_files): ...\ndef get_default_args(func): ...\ndef get_all_args(func): ...\ndef search_for_orig(decorated, orig_name): ...\ndef get_hashbang(file_path): ...\ndef get_language_from_hashbang(hashbang): ...\ndef concatenate(dict1, dict2): ...\ndef peek(iterable): ...\ndef contained_in(smaller, bigger): ...\ndef get_yaml_contents(project_data): ...\ndef dump_yaml_to_file(file, contents): ...\ndef append_to_contents(contents, key, values, settings_key): ...\n", "repository": "coala/coala-quickstart", "test_name": "test_concatenate", "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_000381.py"} {"focal_file": "coala_quickstart/generation/Utilities.py", "focal_class": null, "focal_method": "peek", "tests": "import unittest\n\nclass Test_peek(unittest.TestCase):\n def test_peek(self):\n\n def give_gen():\n for i in range(1, 5):\n yield i\n\n def give_empty_gen():\n for i in range(1, 1):\n yield i\n obj = give_gen()\n for i in range(1, 5):\n num, new_obj = peek(obj)\n obj, new_obj = itertools.tee(obj)\n self.assertEqual(i, num)\n ret_val = peek(obj)\n obj = give_empty_gen()\n ret_val_1 = peek(obj)\n self.assertEqual(ret_val, None)\n self.assertEqual(ret_val_1, None)\n", "method_code": "def peek(iterable):\n \"\"\"\n Checks if an iterable is empty.\n :param iterable:\n The iterable python object.\n :return:\n None if an iterable is empty or else first item\n of the iterable object and the remaining iterator.\n \"\"\"\n try:\n first = next(iterable)\n except StopIteration:\n return None\n return (first, itertools.chain([first], iterable))", "context": "def peek(iterable): ...\ndef is_glob_exp(line): ...\ndef parse_gitignore_line(line): ...\ndef get_gitignore_glob(project_dir, gitignore_dir_list, filename='.gitignore'): ...\ndef split_by_language(project_files): ...\ndef get_extensions(project_files): ...\ndef get_default_args(func): ...\ndef get_all_args(func): ...\ndef search_for_orig(decorated, orig_name): ...\ndef get_hashbang(file_path): ...\ndef get_language_from_hashbang(hashbang): ...\ndef concatenate(dict1, dict2): ...\ndef peek(iterable): ...\ndef contained_in(smaller, bigger): ...\ndef get_yaml_contents(project_data): ...\ndef dump_yaml_to_file(file, contents): ...\ndef append_to_contents(contents, key, values, settings_key): ...\n", "repository": "coala/coala-quickstart", "test_name": "test_peek", "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, 1, 0, 0], "pynose_source_file": "test_000382.py"} {"focal_file": "coala_quickstart/generation/Utilities.py", "focal_class": null, "focal_method": "contained_in", "tests": "import unittest\n\nclass Test_contained_in(unittest.TestCase):\n def test_contained_in_1(self):\n start = SourcePosition('a.py', line=1, column=5)\n end = SourcePosition('a.py', line=5, column=1)\n smaller = SourceRange(start, end)\n start = SourcePosition('a.py', line=1, column=5)\n end = SourcePosition('a.py', line=5, column=2)\n bigger = SourceRange(start, end)\n self.assertTrue(contained_in(smaller, bigger))\n start = SourcePosition('a.py', line=1, column=4)\n end = SourcePosition('a.py', line=5, column=1)\n bigger = SourceRange(start, end)\n self.assertTrue(contained_in(smaller, bigger))\n start = SourcePosition('a.py', line=1, column=5)\n end = SourcePosition('a.py', line=5, column=1)\n bigger = SourceRange(start, end)\n self.assertTrue(contained_in(smaller, bigger))\n\n def test_contained_in_2(self):\n start = SourcePosition('a.py', line=1, column=5)\n end = SourcePosition('a.py', line=5, column=1)\n smaller = SourceRange(start, end)\n start = SourcePosition('a.py', line=1, column=9)\n end = SourcePosition('a.py', line=5, column=1)\n bigger = SourceRange(start, end)\n self.assertFalse(contained_in(smaller, bigger))\n start = SourcePosition('a.py', line=1, column=6)\n end = SourcePosition('a.py', line=4, column=2)\n bigger = SourceRange(start, end)\n self.assertFalse(contained_in(smaller, bigger))\n start = SourcePosition('b.py', line=1, column=5)\n end = SourcePosition('b.py', line=5, column=1)\n bigger = SourceRange(start, end)\n self.assertFalse(contained_in(smaller, bigger))\n\n def test_contained_in_3(self):\n start = SourcePosition('a.py', line=1, column=5)\n end = SourcePosition('a.py', line=5, column=1)\n smaller = SourceRange(start, end)\n start = SourcePosition('a.py', line=2, column=5)\n end = SourcePosition('a.py', line=5, column=1)\n bigger = SourceRange(start, end)\n self.assertFalse(contained_in(smaller, bigger))\n\n def test_contained_in_4(self):\n start = SourcePosition('a.py', line=3, column=5)\n end = SourcePosition('a.py', line=5, column=1)\n smaller = SourceRange(start, end)\n start = SourcePosition('a.py', line=1, column=5)\n end = SourcePosition('a.py', line=6, column=1)\n bigger = SourceRange(start, end)\n self.assertTrue(contained_in(smaller, bigger))\n start = SourcePosition('a.py', line=3, column=5)\n end = SourcePosition('a.py', line=6, column=1)\n bigger = SourceRange(start, end)\n self.assertTrue(contained_in(smaller, bigger))\n\n def test_contained_in_5(self):\n start = SourcePosition('a.py', line=3, column=5)\n end = SourcePosition('a.py', line=5, column=1)\n smaller = SourceRange(start, end)\n start = SourcePosition('a.py', line=2, column=5)\n end = SourcePosition('a.py', line=5, column=1)\n bigger = SourceRange(start, end)\n self.assertTrue(contained_in(smaller, bigger))\n start = SourcePosition('a.py', line=3, column=8)\n end = SourcePosition('a.py', line=7, column=1)\n bigger = SourceRange(start, end)\n self.assertFalse(contained_in(smaller, bigger))\n\n def test_contained_in_6(self):\n start = SourcePosition('a.py', line=3, column=5)\n end = SourcePosition('a.py', line=5, column=7)\n smaller = SourceRange(start, end)\n start = SourcePosition('a.py', line=3, column=5)\n end = SourcePosition('a.py', line=5, column=6)\n bigger = SourceRange(start, end)\n self.assertFalse(contained_in(smaller, bigger))\n start = SourcePosition('a.py', line=2, column=8)\n end = SourcePosition('a.py', line=5, column=1)\n bigger = SourceRange(start, end)\n self.assertFalse(contained_in(smaller, bigger))\n start = SourcePosition('a.py', line=2, column=None)\n end = SourcePosition('a.py', line=5, column=1)\n bigger = SourceRange(start, end)\n self.assertFalse(contained_in(smaller, bigger))\n", "method_code": "def contained_in(smaller, bigger):\n \"\"\"\n Takes in two SourceRange objects and checks whether\n the first one lies inside the other one.\n :param smaller:\n The SourceRange object that needs to be checked whether\n it is inside the other one.\n :param bigger:\n The SourceRange object that needs to be checked whether\n it contains the other one.\n :return:\n True if smaller is inside the bigger else false.\n \"\"\"\n smaller_file = smaller.start.file\n bigger_file = bigger.start.file\n smaller_start_line = smaller.start.line\n smaller_start_column = smaller.start.column\n smaller_end_line = smaller.end.line\n smaller_end_column = smaller.end.column\n bigger_start_line = bigger.start.line\n bigger_start_column = bigger.start.column\n bigger_end_line = bigger.end.line\n bigger_end_column = bigger.end.column\n if None in [smaller_start_line, smaller_start_column, smaller_end_line, smaller_end_column, bigger_start_line, bigger_start_column, bigger_end_line, bigger_end_column]:\n return False\n if not smaller_file == bigger_file:\n return False\n if smaller_start_line < bigger_start_line:\n return False\n if smaller_end_line > bigger_end_line:\n return False\n if smaller_start_line > bigger_start_line and smaller_end_line < bigger_end_line:\n return True\n same_start_line = smaller_start_line == bigger_start_line\n same_end_line = smaller_end_line == bigger_end_line\n if same_start_line and same_end_line:\n if smaller_start_column < bigger_start_column:\n return False\n if smaller_end_column > bigger_end_column:\n return False\n return True\n if same_start_line:\n if smaller_start_column < bigger_start_column:\n return False\n return True\n assert same_end_line\n if smaller_end_column > bigger_end_column:\n return False\n return True", "context": "def contained_in(smaller, bigger): ...\ndef is_glob_exp(line): ...\ndef parse_gitignore_line(line): ...\ndef get_gitignore_glob(project_dir, gitignore_dir_list, filename='.gitignore'): ...\ndef split_by_language(project_files): ...\ndef get_extensions(project_files): ...\ndef get_default_args(func): ...\ndef get_all_args(func): ...\ndef search_for_orig(decorated, orig_name): ...\ndef get_hashbang(file_path): ...\ndef get_language_from_hashbang(hashbang): ...\ndef concatenate(dict1, dict2): ...\ndef peek(iterable): ...\ndef contained_in(smaller, bigger): ...\ndef get_yaml_contents(project_data): ...\ndef dump_yaml_to_file(file, contents): ...\ndef append_to_contents(contents, key, values, settings_key): ...\n", "repository": "coala/coala-quickstart", "test_name": "test_contained_in_1", "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, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000383.py"} {"focal_file": "coala_quickstart/info_extraction/InfoExtractor.py", "focal_class": null, "focal_method": "extract_information", "tests": "import unittest\n\nclass Test_extract_information(unittest.TestCase):\n def test_multiple_information(self):\n target_filenames = ['target_file_1']\n target_file_contents = ['Some content.']\n with generate_files(target_filenames, target_file_contents, self.current_dir) as gen_files:\n uut = self.DummyMultiInfoExtractor(['target_file_**', 'another_target_file'], self.current_dir)\n extracted_info = uut.extract_information()\n self.assertEqual(len(extracted_info.keys()), len(target_filenames))\n self.assertEqual(extracted_info, uut.information)\n for tf in target_filenames:\n self.assertEqual(len(extracted_info[tf]), 2)\n self.assertEqual(len(extracted_info[tf]['DummyInfo']), 2)\n self.assertIsInstance(extracted_info[tf]['DummyInfo'][1], self.DummyInfo)\n self.assertEqual(len(extracted_info[tf]['AnotherDummyInfo']), 1)\n self.assertIsInstance(extracted_info[tf]['DummyInfo'][0], self.DummyInfo)\n\n def test_no_information_found(self):\n target_filenames = ['target_file_1']\n target_file_contents = ['Some content.']\n uut = self.NoInfoExtractor(['target_file_**', 'another_target_file'], self.current_dir)\n with generate_files(target_filenames, target_file_contents, self.current_dir) as gen_files:\n extracted_info = uut.extract_information()\n self.assertEqual(len(extracted_info.keys()), 0)\n self.assertEqual(extracted_info, uut.information)\n for tf in target_filenames:\n self.assertIsNone(extracted_info.get(tf))\n", "method_code": " def extract_information(self):\n \"\"\"\n Extracts the information, saves in the object and returns it.\n \"\"\"\n for fpath in self.target_files:\n with open(fpath, 'r') as f:\n pfile = self.parse_file(fpath, f.read())\n fname = os.path.relpath(fpath, self.directory)\n file_info = self.find_information(fname, pfile)\n if file_info:\n self._add_info(fname, file_info)\n return self.information\n ", "context": "class InfoExtractor():\n def extract_information(self): ...\n def __init__(self, target_globs, project_directory): ...\n def information(self): ...\n def parse_file(self, fname, file_content): ...\n def _add_info(self, fname, info_to_add): ...\n def find_information(self, fname, parsed_file): ...\n def retrieve_files(file_globs, directory): ...\n\n self.target_files = [os.path.join(project_directory, f) for f in target_files]\n self.directory = project_directory\n self._information = dict()\n\n supported_file_globs = tuple()\n spec_references = []\n supported_info_kinds = (Info,)\n", "repository": "coala/coala-quickstart", "test_name": "test_multiple_information", "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_000384.py"} {"focal_file": "coala_quickstart/info_extraction/InfoScope.py", "focal_class": "InfoScope", "focal_method": "check_belongs_to_scope", "tests": "import unittest\n\nclass Test_InfoScope_check_belongs_to_scope(unittest.TestCase):\n def test_check_belongs_to_scope(self):\n global_scope = InfoScope('global', sections=[], bears=[])\n section_scope = InfoScope('section', sections=['python'], bears=[])\n bear_scope_with_section = InfoScope('bear', sections=['python'], bears=['coalaBear'])\n bear_scope_without_section = InfoScope('bear', sections=[], bears=['coalaBear'])\n uut = global_scope\n self.assertTrue(uut.check_belongs_to_scope('any_random_section', 'any_random_bear'))\n self.assertTrue(uut.check_belongs_to_scope('', ''))\n uut = section_scope\n self.assertFalse(uut.check_belongs_to_scope('any_random_section', 'any_random_bear'))\n self.assertFalse(uut.check_belongs_to_scope('', ''))\n self.assertTrue(uut.check_belongs_to_scope('python', 'any_random_bear'))\n uut = bear_scope_with_section\n self.assertFalse(uut.check_belongs_to_scope('any_random_section', 'any_random_bear'))\n self.assertTrue(uut.check_belongs_to_scope('python', 'coalaBear'))\n self.assertFalse(uut.check_belongs_to_scope('', 'coalaBear'))\n uut = bear_scope_without_section\n self.assertFalse(uut.check_belongs_to_scope('any_random_section', 'any_random_bear'))\n self.assertTrue(uut.check_belongs_to_scope('python', 'coalaBear'))\n self.assertTrue(uut.check_belongs_to_scope('', 'coalaBear'))\n", "method_code": " def check_belongs_to_scope(self, section_name, bear_name):\n \"\"\"\n Checks if the given section_name and bear_name\n belong to the ``InfoScope`` or not.\n \"\"\"\n if self.level == 'global':\n return True\n elif self.level == 'section':\n if section_name in self.sections:\n return True\n elif self.sections:\n if section_name in self.sections and bear_name in self.bears:\n return True\n elif bear_name in self.bears:\n return True\n return False\n ", "context": "class InfoScope():\n def check_belongs_to_scope(self, section_name, bear_name): ...\n def __init__(self, level, sections=[], bears=[], section_match_method=None, allowed_sources=[], allowed_extractors=tuple()): ...\n def check_is_applicable_information(self, section, info): ...\n\n self.level = level\n self.section_match_method = section_match_method\n self.allowed_sources = allowed_sources\n self.allowed_extractors = allowed_extractors\n", "repository": "coala/coala-quickstart", "test_name": "test_check_belongs_to_scope", "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, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000385.py"} {"focal_file": "coala_quickstart/info_extraction/InfoScope.py", "focal_class": "InfoScope", "focal_method": "check_is_applicable_information", "tests": "import unittest\n\nclass Test_InfoScope_check_is_applicable_information(unittest.TestCase):\n def test_check_is_applicable_information(self):\n info_1 = InfoA('source_file_1', 'info_1_value', DummyInfoExtractor(['some_file'], os.getcwd()), extra_param='extra_param_value')\n info_2 = InfoA('source_file_2', 'info_2_value', NoInfoExtractor(['some_file'], os.getcwd()), extra_param='extra_param_value')\n uut = InfoScope('global', allowed_sources=['source_file_1'])\n self.assertTrue(uut.check_is_applicable_information(self.section, info_1))\n self.assertFalse(uut.check_is_applicable_information(self.section, info_2))\n uut = InfoScope('global', allowed_extractors=(DummyInfoExtractor,))\n self.assertTrue(uut.check_is_applicable_information(self.section, info_1))\n self.assertFalse(uut.check_is_applicable_information(self.section, info_2))\n uut = InfoScope('global', allowed_sources=['source_file_1'], allowed_extractors=(DummyInfoExtractor,))\n self.assertTrue(uut.check_is_applicable_information(self.section, info_1))\n self.assertFalse(uut.check_is_applicable_information(self.section, info_2))\n uut = InfoScope('global')\n self.assertTrue(uut.check_is_applicable_information(self.section, info_1))\n self.assertTrue(uut.check_is_applicable_information(self.section, info_2))\n uut = InfoScope('bear')\n self.assertTrue(uut.check_is_applicable_information(self.section, info_1))\n self.assertTrue(uut.check_is_applicable_information(self.section, info_2))\n", "method_code": " def check_is_applicable_information(self, section, info):\n \"\"\"\n Checks if the given ``Info`` instance contains\n information applicable to the ``InfoScope`` or not\n based on the attributes `allowed_sources` and\n `allowed_extractors`. If none of them is specified, True\n is returned.\n \"\"\"\n if self.section_match_method and section.get('files').value:\n if not self.section_match_method(section['files'], info):\n return False\n if not self.allowed_sources and (not self.allowed_extractors):\n return True\n elif self.allowed_sources and self.allowed_extractors:\n if info.source in self.allowed_sources and isinstance(info.extractor, self.allowed_extractors):\n return True\n elif info.source in self.allowed_sources or isinstance(info.extractor, self.allowed_extractors):\n return True\n return False\n ", "context": "class InfoScope():\n def check_is_applicable_information(self, section, info): ...\n def __init__(self, level, sections=[], bears=[], section_match_method=None, allowed_sources=[], allowed_extractors=tuple()): ...\n def check_belongs_to_scope(self, section_name, bear_name): ...\n\n self.level = level\n self.section_match_method = section_match_method\n self.allowed_sources = allowed_sources\n self.allowed_extractors = allowed_extractors\n", "repository": "coala/coala-quickstart", "test_name": "test_check_is_applicable_information", "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, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000386.py"} {"focal_file": "coala_quickstart/interaction/Logo.py", "focal_class": null, "focal_method": "print_side_by_side", "tests": "import unittest\n\nclass Test_print_side_by_side(unittest.TestCase):\n def test_print_side_by_side(self):\n with retrieve_stdout() as custom_stdout:\n print_side_by_side(self.printer, ['Left side content.'], ['Right side content', 'that is longer than the', 'left side.'], limit=80)\n self.assertIn('side content.\\x1b[0m \\x1b[34mRight side', custom_stdout.getvalue())\n", "method_code": "def print_side_by_side(printer, left=[], right=[], left_color='white', right_color='blue', limit=80):\n \"\"\"\n Prints the the given lines side by side. Example usage:\n\n >>> from pyprint.ConsolePrinter import ConsolePrinter\n >>> printer = ConsolePrinter()\n >>> print_side_by_side(\n ... printer,\n ... [\"Text content on the left\",\n ... \"side of the text.\"],\n ... [\"Right side should contain\",\n ... \"this.\"],\n ... left_color=None,\n ... right_color=None,\n ... limit=80)\n Text content on the left Right side should contain\n side of the text. this.\n\n If either side is longer than the other, empty lines will\n be added to the shorter side.\n\n :param printer:\n A ``ConsolePrinter`` object used for console interaction.\n :param left:\n The lines for the left portion of the text.\n :param right:\n The lines for the right portion of the text.\n :param left_color:\n The color to use for the left side of the text.\n :parm right_color:\n The color to use for the right side of the text.\n :param limit:\n The maximum line length limit.\n \"\"\"\n max_left_length = len(max(left, key=len))\n for line in range(len(left) - len(right)):\n right.append('')\n for line in range(len(right) - len(left)):\n left.append('')\n for left_line, right_line in zip(left, right):\n printer.print(left_line, color=left_color, end='')\n printer.print(' ' * (max_left_length - len(left_line) + 1), end='')\n printer.print(right_line, color=right_color)", "context": "def print_side_by_side(printer, left=[], right=[], left_color='white', right_color='blue', limit=80): ...\ndef print_side_by_side(printer, left=[], right=[], left_color='white', right_color='blue', limit=80): ...\ndef print_welcome_message(printer): ...\n", "repository": "coala/coala-quickstart", "test_name": "test_print_side_by_side", "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_000387.py"} {"focal_file": "coala_quickstart/interaction/Logo.py", "focal_class": null, "focal_method": "print_welcome_message", "tests": "import unittest\n\nclass Test_print_welcome_message(unittest.TestCase):\n def test_print_welcome_message(self):\n with retrieve_stdout() as custom_stdout:\n print_welcome_message(self.printer)\n self.assertIn('o88Oo', custom_stdout.getvalue())\n", "method_code": "def print_welcome_message(printer):\n \"\"\"\n Prints the coala bear logo with a welcome message side by side.\n\n :param printer:\n A ``ConsolePrinter`` object used for console interaction.\n \"\"\"\n max_length = 80 - len(max(COALA_BEAR_LOGO, key=len))\n text_lines = ['']\n for welcome_message in WELCOME_MESSAGES:\n text_lines += ['']\n text_lines += textwrap.wrap(welcome_message, max_length)\n print_side_by_side(printer, left=COALA_BEAR_LOGO, right=text_lines, limit=80)", "context": "def print_welcome_message(printer): ...\ndef print_side_by_side(printer, left=[], right=[], left_color='white', right_color='blue', limit=80): ...\ndef print_welcome_message(printer): ...\n", "repository": "coala/coala-quickstart", "test_name": "test_print_welcome_message", "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_000388.py"} {"focal_file": "cotest/ContextManagers.py", "focal_class": null, "focal_method": "subprocess_timeout", "tests": "import unittest\n\nclass Test_subprocess_timeout(unittest.TestCase):\n def test_subprocess_timeout(self):\n p = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(0.5);'], stderr=subprocess.PIPE)\n with subprocess_timeout(p, 0.2) as timedout:\n retval = p.wait()\n p.stderr.close()\n self.assertEqual(timedout.value, True)\n self.assertNotEqual(retval, 0)\n p = create_process_group([sys.executable, '-c', process_group_timeout_test_code])\n with subprocess_timeout(p, 0.5, kill_pg=True):\n retval = p.wait()\n self.assertEqual(timedout.value, True)\n self.assertNotEqual(retval, 0)\n p = subprocess.Popen([sys.executable, '-c', 'import time'])\n with subprocess_timeout(p, 0.5) as timedout:\n retval = p.wait()\n self.assertEqual(timedout.value, False)\n self.assertEqual(retval, 0)\n p = subprocess.Popen([sys.executable, '-c', 'import time'])\n with subprocess_timeout(p, 0) as timedout:\n retval = p.wait()\n self.assertEqual(timedout.value, False)\n self.assertEqual(retval, 0)\n", "method_code": "def subprocess_timeout(sub_process, seconds, kill_pg=False):\n \"\"\"\n Kill subprocess if the sub process takes more the than the timeout.\n\n :param sub_process: The sub process to run.\n :param seconds: The number of seconds to allow the test to run for. If\n set to 0 or a negative value, it waits indefinitely.\n Floats can be used to specify units smaller than\n seconds.\n :param kill_pg: Boolean whether to kill the process group or only this\n process. (not applicable for windows)\n \"\"\"\n timedout = MutableValue(False)\n if seconds <= 0:\n yield timedout\n return\n finished = threading.Event()\n if platform.system() == 'Windows':\n kill_pg = False\n\n def kill_it():\n finished.wait(seconds)\n if not finished.is_set():\n timedout.value = True\n if kill_pg:\n pgid = os.getpgid(sub_process.pid)\n os.kill(sub_process.pid, signal.SIGINT)\n if kill_pg:\n os.killpg(pgid, signal.SIGINT)\n thread = threading.Thread(name='timeout-killer', target=kill_it)\n try:\n thread.start()\n yield timedout\n finally:\n finished.set()\n thread.join()", "context": "@contextmanager\ndef subprocess_timeout(sub_process, seconds, kill_pg=False): ...\ndef subprocess_timeout(sub_process, seconds, kill_pg=False): ...\ndef replace_stdout(replacement): ...\ndef suppress_stdout(): ...\ndef retrieve_stdout(): ...\ndef simulate_console_inputs(*inputs): ...\ndef preserve_sys_path(): ...\n", "repository": "coala/CoTest", "test_name": "test_subprocess_timeout", "smells": [1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0], "smell_labels": ["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_000389.py"} {"focal_file": "cotest/ContextManagers.py", "focal_class": null, "focal_method": "suppress_stdout", "tests": "import unittest\n\nclass Test_suppress_stdout(unittest.TestCase):\n def test_suppress_stdout(self):\n\n def print_func():\n print('func')\n raise NotImplementedError\n\n def no_print_func():\n with suppress_stdout():\n print('func')\n raise NotImplementedError\n old_stdout = sys.stdout\n sys.stdout = False\n self.assertRaises(AttributeError, print_func)\n self.assertRaises(NotImplementedError, no_print_func)\n sys.stdout = old_stdout\n", "method_code": "def suppress_stdout():\n \"\"\"\n Suppresses everything going to stdout.\n \"\"\"\n with open(os.devnull, 'w') as devnull, replace_stdout(devnull):\n yield", "context": "@contextmanager\ndef suppress_stdout(): ...\ndef subprocess_timeout(sub_process, seconds, kill_pg=False): ...\ndef replace_stdout(replacement): ...\ndef suppress_stdout(): ...\ndef retrieve_stdout(): ...\ndef simulate_console_inputs(*inputs): ...\ndef preserve_sys_path(): ...\n", "repository": "coala/CoTest", "test_name": "test_suppress_stdout", "smells": [1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "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, 1, 0, 0, 0, 0], "pynose_source_file": "test_000390.py"} {"focal_file": "cotest/ContextManagers.py", "focal_class": null, "focal_method": "retrieve_stdout", "tests": "import unittest\n\nclass Test_retrieve_stdout(unittest.TestCase):\n def test_retrieve_stdout(self):\n with retrieve_stdout() as sio:\n print('test')\n self.assertEqual(sio.getvalue(), 'test\\n')\n", "method_code": "def retrieve_stdout():\n \"\"\"\n Yields a StringIO object from which one can read everything that was\n printed to stdout. (It won't be printed to the real stdout!)\n\n Example usage:\n\n with retrieve_stdout() as stdout:\n print(\"something\") # Won't print to the console\n what_was_printed = stdout.getvalue() # Save the value\n \"\"\"\n with closing(StringIO()) as sio, replace_stdout(sio):\n yield sio", "context": "@contextmanager\ndef retrieve_stdout(): ...\ndef subprocess_timeout(sub_process, seconds, kill_pg=False): ...\ndef replace_stdout(replacement): ...\ndef suppress_stdout(): ...\ndef retrieve_stdout(): ...\ndef simulate_console_inputs(*inputs): ...\ndef preserve_sys_path(): ...\n", "repository": "coala/CoTest", "test_name": "test_retrieve_stdout", "smells": [1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "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_000391.py"} {"focal_file": "cotest/ContextManagers.py", "focal_class": null, "focal_method": "simulate_console_inputs", "tests": "import unittest\n\nclass Test_simulate_console_inputs(unittest.TestCase):\n def test_simulate_console_inputs(self):\n with simulate_console_inputs(0, 1, 2) as generator:\n self.assertEqual(input(), 0)\n self.assertEqual(generator.last_input, 0)\n generator.inputs.append(3)\n self.assertEqual(input(), 1)\n self.assertEqual(input(), 2)\n self.assertEqual(input(), 3)\n self.assertEqual(generator.last_input, 3)\n", "method_code": "def simulate_console_inputs(*inputs):\n \"\"\"\n Does some magic to simulate the given inputs to any calls to the `input`\n builtin. This yields back an InputGenerator object so you can check\n which input was already used and append any additional inputs you want.\n Example:\n\n with simulate_console_inputs(0, 1, 2) as generator:\n assert(input() == 0)\n assert(generator.last_input == 0)\n generator.inputs.append(3)\n assert(input() == 1)\n assert(input() == 2)\n assert(input() == 3)\n assert(generator.last_input == 3)\n\n :param inputs: Any inputs to simulate. An IndexError will be raised if\n input is called more often then the number of provided\n inputs.\n \"\"\"\n\n class InputGenerator:\n\n def __init__(self, inputs):\n self.last_input = -1\n self.inputs = inputs\n\n def generate_input(self, prompt=''):\n print(prompt, end='')\n self.last_input += 1\n return self.inputs[self.last_input]\n input_generator = InputGenerator(list(inputs))\n _input = builtins.__dict__['input']\n builtins.__dict__['input'] = input_generator.generate_input\n try:\n yield input_generator\n finally:\n builtins.__dict__['input'] = _input", "context": "@contextmanager\ndef simulate_console_inputs(*inputs): ...\ndef subprocess_timeout(sub_process, seconds, kill_pg=False): ...\ndef replace_stdout(replacement): ...\ndef suppress_stdout(): ...\ndef retrieve_stdout(): ...\ndef simulate_console_inputs(*inputs): ...\ndef preserve_sys_path(): ...\n", "repository": "coala/CoTest", "test_name": "test_simulate_console_inputs", "smells": [1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "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_000392.py"} {"focal_file": "cotest/ContextManagers.py", "focal_class": null, "focal_method": "preserve_sys_path", "tests": "import unittest\n\nclass Test_preserve_sys_path(unittest.TestCase):\n def test_preserve_sys_path(self):\n old_sys_path = copy.copy(sys.path)\n with preserve_sys_path():\n sys.path = 5\n self.assertEqual(old_sys_path, sys.path)\n", "method_code": "def preserve_sys_path():\n _path = copy.copy(sys.path)\n try:\n yield\n finally:\n sys.path = _path", "context": "@contextmanager\ndef preserve_sys_path(): ...\ndef subprocess_timeout(sub_process, seconds, kill_pg=False): ...\ndef replace_stdout(replacement): ...\ndef suppress_stdout(): ...\ndef retrieve_stdout(): ...\ndef simulate_console_inputs(*inputs): ...\ndef preserve_sys_path(): ...\n", "repository": "coala/CoTest", "test_name": "test_preserve_sys_path", "smells": [1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "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": "src/main/python/dfr/image_hashing.py", "focal_class": null, "focal_method": "get_image_signature1", "tests": "import unittest\n\nclass Test_get_image_signature1(unittest.TestCase):\n def test_signature1(self):\n\n def get_sig(filename):\n return [int(x * 100) for x in get_image_signature1('src/test/images/' + filename)]\n self.assertEqual(get_sig('all_white_rgb.png'), [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100])\n self.assertEqual(get_sig('all_black_rgb.png'), [100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n self.assertEqual(get_sig('all_red.png'), [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n self.assertEqual(get_sig('all_green.png'), [100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n self.assertEqual(get_sig('all_blue.png'), [100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100])\n self.assertEqual(get_sig('red_green_blue.png'), [66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 33, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 33, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 33])\n self.assertEqual(get_sig('all_white_gray.png'), [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100])\n self.assertEqual(get_sig('all_black_gray.png'), [100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n self.assertEqual(get_sig('white_2_grays_and_black.png'), [25, 0, 0, 0, 0, 0, 25, 0, 0, 0, 0, 0, 0, 25, 0, 25])\n self.assertEqual(get_sig('python-logo-master-v3-TM.png'), [0, 0, 0, 3, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 89, 0, 0, 0, 0, 0, 0, 6, 2, 0, 0, 0, 0, 0, 2, 0, 86, 0, 0, 0, 0, 1, 0, 5, 0, 0, 0, 1, 0, 0, 0, 0, 86])\n", "method_code": "def get_image_signature1(filename):\n \"\"\"\n based on the color histogram\n \"\"\"\n image = Image.open(filename)\n histo = image.histogram()\n bands = -1\n if len(histo) in [3 * 256, 4 * 256]:\n bands = 3\n elif len(histo) == 256:\n bands = 1\n assert bands > 0, \"Can't get histogram for %s; histogram size is %d\" % (filename, len(histo))\n subparts = 16\n width = 256 / subparts\n value = []\n for band in range(bands):\n cstart = 256 * band\n cend = 256 * (band + 1)\n band_total = float(sum(histo[cstart:cend]))\n raw_values = [-1] * 256\n for j in range(cstart, cend):\n raw_values[j - cstart] = float(histo[j]) / band_total\n values_for_band = []\n for j in range(subparts):\n values_for_band.append(sum(raw_values[j * width:(j + 1) * width]))\n value += values_for_band\n assert -1 not in value\n return value", "context": "def get_image_signature1(filename): ...\ndef shell_quote(str): ...\ndef get_image_signature1(filename): ...\ndef get_image_signatures2(filenames): ...\ndef get_image_signature3(filename): ...\ndef get_image_signature4(filename): ...\ndef get_image_signature5(filename): ...\n", "repository": "rfalke/decreasefileredundency", "test_name": "test_signature1", "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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000394.py"} {"focal_file": "src/main/python/dfr/image_hashing.py", "focal_class": null, "focal_method": "get_image_signatures2", "tests": "import unittest\n\nclass Test_get_image_signatures2(unittest.TestCase):\n def test_signature2(self):\n signatures = get_image_signatures2(['src/test/images/all_black_rgb.png', 'does not exists', 'Makefile', 'src/test/images/all_white_rgb.png', 'src/test/images/pattern1.png'])\n if signatures is not None:\n self.assertEqual(signatures, ['ffffffffffffffff', None, None, '0000000000000000', 'f8f8f8ffff1f1f1f'])\n\n def test_signature2_for_coverage(self):\n CAUSE_UNEQUAL_LINES.append(1)\n get_image_signatures2(['src/test/images/all_black_rgb.png'])\n self.assert_no_exception()\n", "method_code": "def get_image_signatures2(filenames):\n filedescr, inname = tempfile.mkstemp()\n os.close(filedescr)\n try:\n out = open(inname, 'w')\n for i in range(len(filenames)):\n out.write('%d %s\\n' % (i, filenames[i]))\n out.close()\n filedescr, outname = tempfile.mkstemp()\n os.close(filedescr)\n try:\n os.system('src/main/perl/get_sig2.pl <%s >%s 2>/dev/null' % (shell_quote(inname), shell_quote(outname)))\n hashs = []\n with open(outname) as infile:\n for line in infile.readlines():\n id, hash = line.strip().split(' ', 1)\n id = int(id)\n assert len(hashs) == id\n if hash == 'FAILED':\n hashs.append(None)\n else:\n assert len(hash) == 16\n hashs.append(hash)\n if len(hashs) == 0:\n return None\n if len(hashs) != len(filenames) or CAUSE_UNEQUAL_LINES:\n raise KeyboardInterrupt()\n return hashs\n finally:\n os.remove(outname)\n finally:\n os.remove(inname)", "context": "def get_image_signatures2(filenames): ...\ndef shell_quote(str): ...\ndef get_image_signature1(filename): ...\ndef get_image_signatures2(filenames): ...\ndef get_image_signature3(filename): ...\ndef get_image_signature4(filename): ...\ndef get_image_signature5(filename): ...\n", "repository": "rfalke/decreasefileredundency", "test_name": "test_signature2", "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_000395.py"} {"focal_file": "src/main/python/dfr/image_hashing.py", "focal_class": null, "focal_method": "get_image_signature3", "tests": "import unittest\n\nclass Test_get_image_signature3(unittest.TestCase):\n def test_signature3(self):\n\n def assert_sig3(filename, expected):\n sig = get_image_signature3(filename)\n self.assertEqual('%016x' % sig, expected)\n assert_sig3('src/test/images/big/Organigramm_deut_2_Seewiesen-1_png.png', '0f042da70d87cfa7')\n assert_sig3('src/test/images/big/free-your-mind-Seite2.bmp', '37a733b533b737b7')\n assert_sig3('src/test/images/pattern1.png', '5d227f22a27f225d')\n assert_sig3('src/test/images/big/bird_bird_bird_png_format_by_chimonk-d37tayt.png', '622a4d0eab9b95d9')\n assert_sig3('src/test/images/big/sample_03.jpeg', '779ba5b1334b1993')\n assert_sig3('src/test/images/big/NENG1614.bmp', '799d2d52b8a5a4bb')\n assert_sig3('src/test/images/pattern2.png', '7fff7fffffff7fff')\n assert_sig3('src/test/images/white_2_grays_and_black.png', '80ff80ff80ff80ff')\n assert_sig3('src/test/images/big/Sunflower_Metalhead64_edited.png', '87070f0787878f8f')\n assert_sig3('src/test/images/big/nice-map-big.jpeg', '88eda7a64d637cec')\n assert_sig3('src/test/images/big/globe_west_2048.jpeg', 'b1f8e0fcf26e78b9')\n assert_sig3('src/test/images/big/Nice-Bee.jpeg', 'cd3ac3371dab6360')\n assert_sig3('src/test/images/big/Intercom_PCB_mit_Best.Druck.gif', 'da68e4deda68e4de')\n assert_sig3('src/test/images/python-logo-master-v3-TM.png', 'eb49b795afe1bbff')\n assert_sig3('src/test/images/red_green_blue.png', 'f0f8f0f8f0f8f0f8')\n assert_sig3('src/test/images/pattern3.png', 'ff7fff7f7f7fff7f')\n assert_sig3('src/test/images/all_black_gray.png', 'ffffffffffffffff')\n assert_sig3('src/test/images/all_black_rgb.png', 'ffffffffffffffff')\n assert_sig3('src/test/images/all_blue.png', 'ffffffffffffffff')\n assert_sig3('src/test/images/all_green.png', 'ffffffffffffffff')\n assert_sig3('src/test/images/all_red.png', 'ffffffffffffffff')\n assert_sig3('src/test/images/all_white_gray.png', 'ffffffffffffffff')\n assert_sig3('src/test/images/all_white_rgb.png', 'ffffffffffffffff')\n", "method_code": "def get_image_signature3(filename):\n \"\"\"\n from http://folk.uio.no/davidjo/DifferenceHash.py\n\nA program to calculate a hash of an image based on visual characteristics.\nAuthor: David J. Oftedal.\n\nThanks to Dr. Neal Krawetz:\nhttp://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html\nfor the algorithm which formed the inspiration for this algorithm.\n \"\"\"\n the_image = Image.open(filename)\n the_image = the_image.convert('L')\n the_image = the_image.resize((8, 8), Image.ANTIALIAS)\n previous_pixel = the_image.getpixel((0, 7))\n difference_hash = 0\n for row in xrange(0, 8, 2):\n for col in xrange(8):\n difference_hash <<= 1\n pixel = the_image.getpixel((col, row))\n difference_hash |= 1 * (pixel >= previous_pixel)\n previous_pixel = pixel\n row += 1\n for col in xrange(7, -1, -1):\n difference_hash <<= 1\n pixel = the_image.getpixel((col, row))\n difference_hash |= 1 * (pixel >= previous_pixel)\n previous_pixel = pixel\n return difference_hash", "context": "def get_image_signature3(filename): ...\ndef shell_quote(str): ...\ndef get_image_signature1(filename): ...\ndef get_image_signatures2(filenames): ...\ndef get_image_signature3(filename): ...\ndef get_image_signature4(filename): ...\ndef get_image_signature5(filename): ...\n", "repository": "rfalke/decreasefileredundency", "test_name": "test_signature3", "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_000396.py"} {"focal_file": "src/main/python/dfr/image_hashing.py", "focal_class": null, "focal_method": "get_image_signature4", "tests": "import unittest\n\nclass Test_get_image_signature4(unittest.TestCase):\n def test_signature4(self):\n\n def assert_sig4(filename, expected):\n sig = get_image_signature4(filename)\n self.assertEqual('%016x' % sig, expected)\n assert_sig4('src/test/images/pattern2.png', '00000000ffffffff')\n assert_sig4('src/test/images/big/sample_03.jpeg', '000185bdfbc38d8b')\n assert_sig4('src/test/images/big/globe_west_2048.jpeg', '00387c7c787e3c00')\n assert_sig4('src/test/images/big/Intercom_PCB_mit_Best.Druck.gif', '007c7c00007c7c60')\n assert_sig4('src/test/images/pattern1.png', '0f0f0f0ff0f0f0f0')\n assert_sig4('src/test/images/big/NENG1614.bmp', '38382f1e9cbff4fc')\n assert_sig4('src/test/images/red_green_blue.png', '3838383838383838')\n assert_sig4('src/test/images/big/Organigramm_deut_2_Seewiesen-1_png.png', '8727008080e3e7ef')\n assert_sig4('src/test/images/big/free-your-mind-Seite2.bmp', '97c1b381818d81ff')\n assert_sig4('src/test/images/big/bird_bird_bird_png_format_by_chimonk-d37tayt.png', 'e3446760a8f9f0f2')\n assert_sig4('src/test/images/big/Nice-Bee.jpeg', 'eff8f0c080d7f93c')\n assert_sig4('src/test/images/white_2_grays_and_black.png', 'f0f0f0f0f0f0f0f0')\n assert_sig4('src/test/images/big/nice-map-big.jpeg', 'fef7f7ef0f0f0004')\n assert_sig4('src/test/images/python-logo-master-v3-TM.png', 'ff9f818181ffffff')\n assert_sig4('src/test/images/big/Sunflower_Metalhead64_edited.png', 'ffc783818183c3ff')\n assert_sig4('src/test/images/pattern3.png', 'ffffffff00000000')\n assert_sig4('src/test/images/all_black_gray.png', 'ffffffffffffffff')\n assert_sig4('src/test/images/all_black_rgb.png', 'ffffffffffffffff')\n assert_sig4('src/test/images/all_blue.png', 'ffffffffffffffff')\n assert_sig4('src/test/images/all_green.png', 'ffffffffffffffff')\n assert_sig4('src/test/images/all_red.png', 'ffffffffffffffff')\n assert_sig4('src/test/images/all_white_gray.png', 'ffffffffffffffff')\n assert_sig4('src/test/images/all_white_rgb.png', 'ffffffffffffffff')\n", "method_code": "def get_image_signature4(filename):\n \"\"\"\n from http://folk.uio.no/davidjo/AverageHash.py\n\nA program to calculate a hash of an image based on visual characteristics.\nAuthor: David J. Oftedal.\n\nThanks to Dr. Neal Krawetz:\nhttp://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html\nfor the algorithm which formed the inspiration for this algorithm.\n \"\"\"\n the_image = Image.open(filename)\n the_image = the_image.convert('L')\n the_image = the_image.resize((8, 8), Image.ANTIALIAS)\n average_value = ImageStat.Stat(the_image).mean[0]\n average_hash = 0\n for row in xrange(8):\n for col in xrange(8):\n average_hash <<= 1\n value = the_image.getpixel((col, row))\n average_hash |= 1 * (value >= average_value)\n return average_hash", "context": "def get_image_signature4(filename): ...\ndef shell_quote(str): ...\ndef get_image_signature1(filename): ...\ndef get_image_signatures2(filenames): ...\ndef get_image_signature3(filename): ...\ndef get_image_signature4(filename): ...\ndef get_image_signature5(filename): ...\n", "repository": "rfalke/decreasefileredundency", "test_name": "test_signature4", "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_000397.py"} {"focal_file": "src/main/python/dfr/image_hashing.py", "focal_class": null, "focal_method": "get_image_signature5", "tests": "import unittest\n\nclass Test_get_image_signature5(unittest.TestCase):\n def test_signature5(self):\n\n def assert_sig5_or_none(filename, expected):\n sig = get_image_signature5(filename)\n if sig is not None:\n self.assertEqual('%016x' % sig, expected)\n assert_sig5_or_none('src/test/images/big/nice-map-big.jpeg', '3929ca47ab8c956b')\n self.assertEqual(get_image_signature5('src/test/images/big/Intercom_PCB_mit_Best.Druck.gif'), None)\n self.assertEqual(get_image_signature5('Makefile'), None)\n self.assertEqual(get_image_signature5('does not exist'), None)\n", "method_code": "def get_image_signature5(filename):\n \"\"\"\nFrom https://github.com/mk-fg/image-deduplication-tool\n\nUses pHash.\n \"\"\"\n if PHASH_LIB is None:\n return None\n phash = ctypes.c_uint64()\n if PHASH_LIB.ph_dct_imagehash(filename, ctypes.pointer(phash)):\n return None\n return phash.value", "context": "def get_image_signature5(filename): ...\ndef shell_quote(str): ...\ndef get_image_signature1(filename): ...\ndef get_image_signatures2(filenames): ...\ndef get_image_signature3(filename): ...\ndef get_image_signature4(filename): ...\ndef get_image_signature5(filename): ...\n", "repository": "rfalke/decreasefileredundency", "test_name": "test_signature5", "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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000398.py"} {"focal_file": "src/main/python/dfr/support.py", "focal_class": null, "focal_method": "abspath", "tests": "import unittest\n\nclass Test_abspath(unittest.TestCase):\n def test_abspath(self):\n self.assertTrue(abspath('.').startswith('/'))\n", "method_code": "def abspath(path):\n return os.path.realpath(os.path.abspath(path))", "context": "def abspath(path): ...\ndef abspath(path): ...\ndef chunker(seq, size): ...\ndef format_bytes_split(num): ...\ndef format_bytes(num): ...\ndef format_time_delta(sec): ...\ndef add_common_command_line_arguments(parser): ...\ndef globs_to_regexp(globs): ...\n", "repository": "rfalke/decreasefileredundency", "test_name": "test_abspath", "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_000399.py"} {"focal_file": "src/main/python/dfr/support.py", "focal_class": null, "focal_method": "chunker", "tests": "import unittest\n\nclass Test_chunker(unittest.TestCase):\n def test_chunker(self):\n self.assertEqual(list(chunker([], 2)), [])\n self.assertEqual(list(chunker([1], 2)), [[1]])\n self.assertEqual(list(chunker([1, 2], 2)), [[1, 2]])\n self.assertEqual(list(chunker([1, 2, 3], 2)), [[1, 2], [3]])\n self.assertEqual(list(chunker([1, 2, 3, 4], 2)), [[1, 2], [3, 4]])\n", "method_code": "def chunker(seq, size):\n return (seq[pos:pos + size] for pos in xrange(0, len(seq), size))", "context": "def chunker(seq, size): ...\ndef abspath(path): ...\ndef chunker(seq, size): ...\ndef format_bytes_split(num): ...\ndef format_bytes(num): ...\ndef format_time_delta(sec): ...\ndef add_common_command_line_arguments(parser): ...\ndef globs_to_regexp(globs): ...\n", "repository": "rfalke/decreasefileredundency", "test_name": "test_chunker", "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_000400.py"} {"focal_file": "src/main/python/dfr/support.py", "focal_class": null, "focal_method": "format_bytes", "tests": "import unittest\n\nclass Test_format_bytes(unittest.TestCase):\n def test_format_bytes(self):\n self.assertEqual(format_bytes(0), '0')\n self.assertEqual(format_bytes(1), '1')\n self.assertEqual(format_bytes(2), '2')\n self.assertEqual(format_bytes(999), '999')\n self.assertEqual(format_bytes(1000), '1,000')\n self.assertEqual(format_bytes(1023), '1,023')\n self.assertEqual(format_bytes(1024), '1,024 (1.0 KiB)')\n self.assertEqual(format_bytes(2048), '2,048 (2.0 KiB)')\n self.assertEqual(format_bytes(414747471), '414,747,471 (395.5 MiB)')\n self.assertEqual(format_bytes(34418050942), '34,418,050,942 (32.1 GiB)')\n self.assertEqual(format_bytes(2000 * 2 ** 40), '2,199,023,255,552,000 (2000.0 TiB)')\n self.assertEqual(format_bytes(2 * 10 ** 15), '2,000,000,000,000,000 (1819.0 TiB)')\n", "method_code": "def format_bytes(num):\n str = ' '.join(format_bytes_split(num))\n return str.strip()", "context": "def format_bytes(num): ...\ndef abspath(path): ...\ndef chunker(seq, size): ...\ndef format_bytes_split(num): ...\ndef format_bytes(num): ...\ndef format_time_delta(sec): ...\ndef add_common_command_line_arguments(parser): ...\ndef globs_to_regexp(globs): ...\n", "repository": "rfalke/decreasefileredundency", "test_name": "test_format_bytes", "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_000401.py"} {"focal_file": "src/main/python/dfr/support.py", "focal_class": null, "focal_method": "format_time_delta", "tests": "import unittest\n\nclass Test_format_time_delta(unittest.TestCase):\n def test_format_time_delta(self):\n self.assertEqual(format_time_delta(0), '0s')\n self.assertEqual(format_time_delta(59), '59s')\n self.assertEqual(format_time_delta(60), '1m 0s')\n self.assertEqual(format_time_delta(71), '1m 11s')\n self.assertEqual(format_time_delta(3600), '1h 0m')\n self.assertEqual(format_time_delta(24 * 3600), '1d 0h')\n", "method_code": "def format_time_delta(sec):\n sec = int(sec)\n min = sec / 60\n sec = sec % 60\n hour = min / 60\n min = min % 60\n day = hour / 24\n hour = hour % 24\n if day:\n return '%dd %dh' % (day, hour)\n if hour:\n return '%dh %dm' % (hour, min)\n elif min:\n return '%dm %ds' % (min, sec)\n else:\n return '%ds' % sec", "context": "def format_time_delta(sec): ...\ndef abspath(path): ...\ndef chunker(seq, size): ...\ndef format_bytes_split(num): ...\ndef format_bytes(num): ...\ndef format_time_delta(sec): ...\ndef add_common_command_line_arguments(parser): ...\ndef globs_to_regexp(globs): ...\n", "repository": "rfalke/decreasefileredundency", "test_name": "test_format_time_delta", "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_000402.py"} {"focal_file": "src/main/python/dfr/support.py", "focal_class": null, "focal_method": "add_common_command_line_arguments", "tests": "import unittest\n\nclass Test_add_common_command_line_arguments(unittest.TestCase):\n def test_add_common_command_line_arguments(self):\n parser = argparse.ArgumentParser()\n add_common_command_line_arguments(parser)\n default_db = parser.parse_args([]).db[0]\n self.assertTrue(default_db.startswith('/'))\n self.assertTrue(default_db.endswith('files.sdb'))\n self.assertEqual(parser.parse_args(['--db-file', 'foo']).db[0], 'foo')\n self.assertEqual(parser.parse_args(['--db-file=foo']).db[0], 'foo')\n", "method_code": "def add_common_command_line_arguments(parser):\n\n def get_default_db_file():\n home = os.path.expanduser('~')\n return os.path.join(home, '.dfr', 'files.sdb')\n default_db_file = get_default_db_file()\n parser.add_argument('--db-file', metavar='FILE', dest='db', nargs=1, default=[default_db_file], help='the db file (default: ' + default_db_file + ')')", "context": "def add_common_command_line_arguments(parser): ...\ndef abspath(path): ...\ndef chunker(seq, size): ...\ndef format_bytes_split(num): ...\ndef format_bytes(num): ...\ndef format_time_delta(sec): ...\ndef add_common_command_line_arguments(parser): ...\ndef globs_to_regexp(globs): ...\n", "repository": "rfalke/decreasefileredundency", "test_name": "test_add_common_command_line_arguments", "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_000403.py"} {"focal_file": "src/main/python/dfr/support.py", "focal_class": null, "focal_method": "globs_to_regexp", "tests": "import unittest\n\nclass Test_globs_to_regexp(unittest.TestCase):\n def test_globs_to_regexp(self):\n self.assertEqual(globs_to_regexp(['*']), '(.*\\\\Z(?ms))')\n self.assertEqual(globs_to_regexp(['.git', 'CSV']), '(\\\\.git\\\\Z(?ms))|(CSV\\\\Z(?ms))')\n self.assertEqual(globs_to_regexp(['*(', '[0-9]', '*foo*']), '(.*\\\\(\\\\Z(?ms))|([0-9]\\\\Z(?ms))|(.*foo.*\\\\Z(?ms))')\n", "method_code": "def globs_to_regexp(globs):\n \"\"\"The globs are ORed.\"\"\"\n assert globs\n patterns = ['(' + fnmatch.translate(x) + ')' for x in globs]\n pattern = '|'.join(patterns)\n return pattern", "context": "def globs_to_regexp(globs): ...\ndef abspath(path): ...\ndef chunker(seq, size): ...\ndef format_bytes_split(num): ...\ndef format_bytes(num): ...\ndef format_time_delta(sec): ...\ndef add_common_command_line_arguments(parser): ...\ndef globs_to_regexp(globs): ...\n", "repository": "rfalke/decreasefileredundency", "test_name": "test_globs_to_regexp", "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_000404.py"} {"focal_file": "scripts/symbol.py", "focal_class": null, "focal_method": "assert_toolchain_found", "tests": "import unittest\n\nclass Test_assert_toolchain_found(unittest.TestCase):\n @unittest.skipIf(ANDROID_BUILD_TOP == '.', 'Test only supported in an Android tree.')\n def test_toolchains_found(self):\n self.assert_toolchain_found('arm')\n self.assert_toolchain_found('arm64')\n self.assert_toolchain_found('mips')\n self.assert_toolchain_found('x86')\n self.assert_toolchain_found('x86_64')\n", "method_code": " def assert_toolchain_found(self, abi):\n global ARCH\n ARCH = abi\n FindToolchain()\n ", "context": "class FindToolchainTests(unittest.TestCase):\n def assert_toolchain_found(self, abi): ...\n def test_toolchains_found(self): ...\n", "repository": "AospExtended/platform_development", "test_name": "", "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": [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000405.py"} {"focal_file": "vndk/tools/sourcedr/ninja/ninja.py", "focal_class": null, "focal_method": "append_raw", "tests": "import unittest\n\nclass Test_append_raw(unittest.TestCase):\n def test_append_raw(self):\n s = ninja.EvalStringBuilder().append_raw('a').getvalue()\n self.assertTrue(s)\n self.assertEqual('a', ninja.eval_string(s, ninja.EvalEnv()))\n\n def test_append_raw_concat(self):\n sb = ninja.EvalStringBuilder()\n sb.append_raw('a')\n sb.append_raw('b')\n s = sb.getvalue()\n self.assertTrue(s)\n self.assertEqual('ab', ninja.eval_string(s, ninja.EvalEnv()))\n", "method_code": " def append_raw(self, text):\n descs = self._segs[0]\n if descs and descs[-1] == 't':\n self._segs[-1] += text\n else:\n self._segs[0] += 't'\n self._segs.append(text)\n return self\n ", "context": "class EvalStringBuilder(object):\n def append_raw(self, text): ...\n def __init__(self): ...\n def append_var(self, varname): ...\n def getvalue(self): ...\n\n self._segs = ['']\n", "repository": "AospExtended/platform_development", "test_name": "test_append_raw", "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_000406.py"} {"focal_file": "vndk/tools/sourcedr/ninja/ninja.py", "focal_class": null, "focal_method": "append_var", "tests": "import unittest\n\nclass Test_append_var(unittest.TestCase):\n def test_append_var(self):\n s = ninja.EvalStringBuilder().append_var('key').getvalue()\n self.assertTrue(s)\n", "method_code": " def append_var(self, varname):\n self._segs[0] += 'v'\n self._segs.append(varname)\n return self\n ", "context": "class EvalStringBuilder(object):\n def append_var(self, varname): ...\n def __init__(self): ...\n def append_raw(self, text): ...\n def getvalue(self): ...\n\n self._segs = ['']\n", "repository": "AospExtended/platform_development", "test_name": "test_append_var", "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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000407.py"} {"focal_file": "vndk/tools/sourcedr/ninja/ninja.py", "focal_class": null, "focal_method": "lex_match", "tests": "import unittest\n\nclass Test_lex_match(unittest.TestCase):\n def test_lex_match(self):\n lexer = ninja.Lexer(['ident'])\n with self.assertRaises(ninja.ParseError):\n lexer.lex_match({ninja.TK.PIPE})\n", "method_code": " def lex_match(self, match_set):\n token = self.lex()\n if token.kind not in match_set:\n self.raise_error()\n return token\n ", "context": "class Lexer(object):\n def lex_match(self, match_set): ...\n def __init__(self, lines_iterable, path='', encoding='utf-8'): ...\n def raise_error(self, reason=None): ...\n def _read_next_line(self): ...\n def _ensure_line(self): ...\n def _ensure_non_comment_line(self): ...\n def _skip_space(self): ...\n def peek(self): ...\n def lex(self): ...\n def _lex_string_or_path(self, matcher, result_kind): ...\n def lex_path(self): ...\n def lex_string(self): ...\n\n self.encoding = encoding\n self.path = path\n self._line_iter = iter(lines_iterable)\n self._line_buf = None\n self._line = 0\n self._line_pos = 0\n self._line_end = 0\n self._line_start = True\n self._next_token = None\n self._next_pos = None\n\n _COMMENT_MATCHER = re.compile('[ \\\\t]*(?:#[^\\\\n]*)?(?=\\\\n)')\n _SPACE_MATCHER = re.compile('[ \\\\t]+')\n _SIMPLE_TOKEN_MATCHER = TokenMatcher([(TK.COMMENT, '#[^\\\\n]*'), (TK.NEWLINE, '[\\\\r\\\\n]'), (TK.SPACE, '[ \\\\t]+'), (TK.ESC_NEWLINE, '\\\\$[\\\\r\\\\n]'), (TK.IDENT, '[\\\\w_.-]+'), (TK.PIPE2, '\\\\|\\\\|'), (TK.PIPE, '\\\\|'), (TK.COLON, ':'), (TK.ASSIGN, '=')])\n _PATH_TOKEN_MATCHER = TokenMatcher([(STR_TK.END, '[ \\\\t\\\\n|:]'), (STR_TK.CHARS, '[^ \\\\t\\\\n|:$]+'), (STR_TK.ESC_CHAR, '\\\\$[^\\\\n{\\\\w_-]'), (STR_TK.ESC_NEWLINE, '\\\\$\\\\n[ \\\\t]*'), (STR_TK.VAR, '\\\\$[\\\\w_-]+'), (STR_TK.CURVE_VAR, '\\\\$\\\\{[\\\\w_.-]+\\\\}')])\n _STR_TOKEN_MATCHER = TokenMatcher([(STR_TK.END, '\\\\n+'), (STR_TK.CHARS, '[^\\\\n$]+'), (STR_TK.ESC_CHAR, '\\\\$[^\\\\n{\\\\w_-]'), (STR_TK.ESC_NEWLINE, '\\\\$\\\\n[ \\\\t]*'), (STR_TK.VAR, '\\\\$[\\\\w_-]+'), (STR_TK.CURVE_VAR, '\\\\$\\\\{[\\\\w_.-]+\\\\}')])\n", "repository": "AospExtended/platform_development", "test_name": "test_lex_match", "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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000408.py"} {"focal_file": "vndk/tools/sourcedr/ninja/ninja.py", "focal_class": null, "focal_method": "lex_path", "tests": "import unittest\n\nclass Test_lex_path(unittest.TestCase):\n def test_lex_path_char(self):\n lexer = ninja.Lexer(['path1 path2'])\n tok = lexer.lex_path()\n self.assertEqual(ninja.TK.PATH, tok.kind)\n self.assertEqual(1, tok.line)\n self.assertEqual(1, tok.column)\n self.assertEqual(('t', 'path1'), tok.value)\n tok = lexer.lex_path()\n self.assertEqual(ninja.TK.PATH, tok.kind)\n self.assertEqual(1, tok.line)\n self.assertEqual(7, tok.column)\n self.assertEqual(('t', 'path2'), tok.value)\n\n def test_lex_path_var(self):\n lexer = ninja.Lexer(['$a'])\n tok = lexer.lex_path()\n self.assertIs(type(tok.value), ninja.EvalString)\n self.assertEqual(('v', 'a'), tok.value)\n lexer = ninja.Lexer(['${a}'])\n tok = lexer.lex_path()\n self.assertIs(type(tok.value), ninja.EvalString)\n self.assertEqual(('v', 'a'), tok.value)\n lexer = ninja.Lexer(['path/${a}'])\n tok = lexer.lex_path()\n self.assertIs(type(tok.value), ninja.EvalString)\n self.assertEqual(('tv', 'path/', 'a'), tok.value)\n", "method_code": " def lex_path(self):\n return self._lex_string_or_path(self._PATH_TOKEN_MATCHER, TK.PATH)\n ", "context": "class Lexer(object):\n def lex_path(self): ...\n def __init__(self, lines_iterable, path='', encoding='utf-8'): ...\n def raise_error(self, reason=None): ...\n def _read_next_line(self): ...\n def _ensure_line(self): ...\n def _ensure_non_comment_line(self): ...\n def _skip_space(self): ...\n def peek(self): ...\n def lex(self): ...\n def lex_match(self, match_set): ...\n def _lex_string_or_path(self, matcher, result_kind): ...\n def lex_string(self): ...\n\n self.encoding = encoding\n self.path = path\n self._line_iter = iter(lines_iterable)\n self._line_buf = None\n self._line = 0\n self._line_pos = 0\n self._line_end = 0\n self._line_start = True\n self._next_token = None\n self._next_pos = None\n\n _COMMENT_MATCHER = re.compile('[ \\\\t]*(?:#[^\\\\n]*)?(?=\\\\n)')\n _SPACE_MATCHER = re.compile('[ \\\\t]+')\n _SIMPLE_TOKEN_MATCHER = TokenMatcher([(TK.COMMENT, '#[^\\\\n]*'), (TK.NEWLINE, '[\\\\r\\\\n]'), (TK.SPACE, '[ \\\\t]+'), (TK.ESC_NEWLINE, '\\\\$[\\\\r\\\\n]'), (TK.IDENT, '[\\\\w_.-]+'), (TK.PIPE2, '\\\\|\\\\|'), (TK.PIPE, '\\\\|'), (TK.COLON, ':'), (TK.ASSIGN, '=')])\n _PATH_TOKEN_MATCHER = TokenMatcher([(STR_TK.END, '[ \\\\t\\\\n|:]'), (STR_TK.CHARS, '[^ \\\\t\\\\n|:$]+'), (STR_TK.ESC_CHAR, '\\\\$[^\\\\n{\\\\w_-]'), (STR_TK.ESC_NEWLINE, '\\\\$\\\\n[ \\\\t]*'), (STR_TK.VAR, '\\\\$[\\\\w_-]+'), (STR_TK.CURVE_VAR, '\\\\$\\\\{[\\\\w_.-]+\\\\}')])\n _STR_TOKEN_MATCHER = TokenMatcher([(STR_TK.END, '\\\\n+'), (STR_TK.CHARS, '[^\\\\n$]+'), (STR_TK.ESC_CHAR, '\\\\$[^\\\\n{\\\\w_-]'), (STR_TK.ESC_NEWLINE, '\\\\$\\\\n[ \\\\t]*'), (STR_TK.VAR, '\\\\$[\\\\w_-]+'), (STR_TK.CURVE_VAR, '\\\\$\\\\{[\\\\w_.-]+\\\\}')])\n", "repository": "AospExtended/platform_development", "test_name": "test_lex_path_char", "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, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000409.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": "defnngj/flasky", "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_000410.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": "defnngj/flasky", "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_000411.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": "defnngj/flasky", "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_000412.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": "defnngj/flasky", "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_000413.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": "defnngj/flasky", "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_000414.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": "defnngj/flasky", "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_000415.py"} {"focal_file": "app/models.py", "focal_class": "User", "focal_method": "to_json", "tests": "import unittest\n\nclass Test_User_to_json(unittest.TestCase):\n def test_to_json(self):\n u = User(email='john@example.com', password='cat')\n db.session.add(u)\n db.session.commit()\n json_user = u.to_json()\n expected_keys = ['url', 'username', 'member_since', 'last_seen', 'posts', 'followed_posts', 'post_count']\n self.assertEqual(sorted(json_user.keys()), sorted(expected_keys))\n self.assertTrue('api/v1.0/users/' in json_user['url'])\n", "method_code": " def to_json(self):\n json_user = {'url': url_for('api.get_user', id=self.id, _external=True), 'username': self.username, 'member_since': self.member_since, 'last_seen': self.last_seen, 'posts': url_for('api.get_user_posts', id=self.id, _external=True), 'followed_posts': url_for('api.get_user_followed_posts', id=self.id, _external=True), 'post_count': self.posts.count()}\n return json_user\n ", "context": "class User(UserMixindb.Model):\n def to_json(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 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 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": "defnngj/flasky", "test_name": "test_to_json", "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_000416.py"} {"focal_file": "embedding.py", "focal_class": null, "focal_method": "deserialize_embedding", "tests": "import unittest\n\nclass Test_deserialize_embedding(unittest.TestCase):\n def test_deserialize(self):\n s = '[42.124]'\n emb = embedding.deserialize_embedding(s)\n self.assertEqual(len(emb), 1)\n self.assertEqual(emb[0], 42.124)\n", "method_code": "def deserialize_embedding(s):\n \"\"\"deserialize a string to an array of numbers\"\"\"\n s = s[1:-1]\n entries = s.split(',')\n res = []\n for emb in entries:\n if len(emb) == 0:\n print('warning empty component found in serialized embedding')\n continue\n f = float(emb)\n res.append(f)\n return res", "context": "def deserialize_embedding(s): ...\ndef serialize_embedding(emb): ...\ndef deserialize_embedding(s): ...\ndef mult_embedding_numpy_matrix(m1, m2): ...\ndef cos_distance_theano_matrix(m1): ...\ndef cos_distance_numpy_vector(v1, v2): ...\ndef cos_distance_numpy_matrix(m1): ...\ndef cos_distance_numpy_matrix2(m1): ...\ndef cos_distance_numpy_two_matrices(m1, m2): ...\ndef get_closest_embedding(dist, emb_index=None): ...\ndef get_sort_indices_desc(dist): ...\ndef get_sort_indices_asc(dist): ...\ndef apply_sort_indices(dist, indices): ...\ndef euclid_distance_numpy_vector(v1, v2): ...\n", "repository": "neerbek/taboo-core", "test_name": "test_deserialize", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000417.py"} {"focal_file": "embedding.py", "focal_class": null, "focal_method": "cos_distance_theano_matrix", "tests": "import unittest\n\nclass Test_cos_distance_theano_matrix(unittest.TestCase):\n def test_cos_distance_theano_matrix1(self):\n x = T.dmatrix('x')\n self.cos_distance_matrix1(theano.function([x], embedding.cos_distance_theano_matrix(x)))\n\n def test_cos_distance_theano_matrix2(self):\n x = T.dmatrix('x')\n self.cos_distance_matrix2(theano.function([x], embedding.cos_distance_theano_matrix(x)))\n\n def test_cos_distance_theano_matrix3(self):\n x = T.dmatrix('x')\n self.cos_distance_matrix3(theano.function([x], embedding.cos_distance_theano_matrix(x)))\n", "method_code": "def cos_distance_theano_matrix(m1):\n \"\"\"Theano impl of cos_distance_numpy_matrix\n See cos_distance_numpy_matrix\"\"\"\n d = T.sum(m1 * m1, axis=1)\n d = T.sqrt(d)\n res = m1 / d[:, None]\n res = T.dot(res, T.transpose(res))\n res = T.extra_ops.fill_diagonal(res, 0)\n return res", "context": "def cos_distance_theano_matrix(m1): ...\ndef serialize_embedding(emb): ...\ndef deserialize_embedding(s): ...\ndef mult_embedding_numpy_matrix(m1, m2): ...\ndef cos_distance_theano_matrix(m1): ...\ndef cos_distance_numpy_vector(v1, v2): ...\ndef cos_distance_numpy_matrix(m1): ...\ndef cos_distance_numpy_matrix2(m1): ...\ndef cos_distance_numpy_two_matrices(m1, m2): ...\ndef get_closest_embedding(dist, emb_index=None): ...\ndef get_sort_indices_desc(dist): ...\ndef get_sort_indices_asc(dist): ...\ndef apply_sort_indices(dist, indices): ...\ndef euclid_distance_numpy_vector(v1, v2): ...\n", "repository": "neerbek/taboo-core", "test_name": "test_cos_distance_theano_matrix1", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 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, 1], "pynose_source_file": "test_000418.py"} {"focal_file": "embedding.py", "focal_class": null, "focal_method": "cos_distance_numpy_matrix", "tests": "import unittest\n\nclass Test_cos_distance_numpy_matrix(unittest.TestCase):\n def test_cos_distance_numpy_matrix4(self):\n rng = RandomState(8726)\n m = rng.uniform(-1000, 1000, size=12 * 6)\n m = m.reshape(12, 6)\n d = embedding.cos_distance_numpy_matrix(m)\n d.shape\n for i in range(m.shape[0] - 1):\n for j in range(i + 1, m.shape[0]):\n angle = embedding.cos_distance_numpy_vector(m[i, :], m[j, :])\n self.assertAlmostEqual(angle, d[i, j], places=5, msg='similarity meaurre unequal for {}, {}'.format(i, j))\n", "method_code": "def cos_distance_numpy_matrix(m1):\n \"\"\"Assumes that the rows are embeddings.\n Returns a matrix of cosine angle for each pair of embeddings\"\"\"\n d1 = numpy.sum(m1 * m1, axis=1)\n d1 = numpy.sqrt(d1)\n n1 = m1 / d1[:, None]\n res = numpy.dot(n1, numpy.transpose(n1))\n numpy.fill_diagonal(res, 0)\n return res", "context": "def cos_distance_numpy_matrix(m1): ...\ndef serialize_embedding(emb): ...\ndef deserialize_embedding(s): ...\ndef mult_embedding_numpy_matrix(m1, m2): ...\ndef cos_distance_theano_matrix(m1): ...\ndef cos_distance_numpy_vector(v1, v2): ...\ndef cos_distance_numpy_matrix(m1): ...\ndef cos_distance_numpy_matrix2(m1): ...\ndef cos_distance_numpy_two_matrices(m1, m2): ...\ndef get_closest_embedding(dist, emb_index=None): ...\ndef get_sort_indices_desc(dist): ...\ndef get_sort_indices_asc(dist): ...\ndef apply_sort_indices(dist, indices): ...\ndef euclid_distance_numpy_vector(v1, v2): ...\n", "repository": "neerbek/taboo-core", "test_name": "test_cos_distance_numpy_matrix4", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000419.py"} {"focal_file": "embedding.py", "focal_class": null, "focal_method": "apply_sort_indices", "tests": "import unittest\n\nclass Test_apply_sort_indices(unittest.TestCase):\n def test_indices(self):\n rng = RandomState(1234)\n weights = rng.uniform(0, 1, size=6 * 6)\n weights = weights.reshape(6, 6)\n self.assertTrue(self.are_columns_sorted(weights) is False)\n t2 = embedding.get_sort_indices_desc(weights)\n self.assertEqual((6, 6), t2.shape)\n t3 = embedding.apply_sort_indices(weights, t2)\n self.assertEqual((6, 6), t3.shape)\n self.assertTrue(self.are_columns_sorted(t3))\n\n def test_indices2(self):\n rng = RandomState(473526)\n l = 200\n weights = rng.uniform(0, 1, size=l * l)\n weights = weights.reshape(l, l)\n self.assertTrue(self.are_columns_sorted(weights) is False)\n t2 = embedding.get_sort_indices_desc(weights)\n self.assertEqual((l, l), t2.shape)\n t3 = embedding.apply_sort_indices(weights, t2)\n self.assertEqual((l, l), t3.shape)\n self.assertTrue(self.are_columns_sorted(t3))\n", "method_code": "def apply_sort_indices(dist, indices):\n \"\"\"Returns a sorted copy of dist, where each column is ordered according to indices\"\"\"\n l = dist.shape[1]\n res = []\n for i in range(l):\n tmp = dist[:, i][indices[:, i]]\n res.append(tmp)\n t3 = numpy.array(res)\n t3 = t3.T\n return t3", "context": "def apply_sort_indices(dist, indices): ...\ndef serialize_embedding(emb): ...\ndef deserialize_embedding(s): ...\ndef mult_embedding_numpy_matrix(m1, m2): ...\ndef cos_distance_theano_matrix(m1): ...\ndef cos_distance_numpy_vector(v1, v2): ...\ndef cos_distance_numpy_matrix(m1): ...\ndef cos_distance_numpy_matrix2(m1): ...\ndef cos_distance_numpy_two_matrices(m1, m2): ...\ndef get_closest_embedding(dist, emb_index=None): ...\ndef get_sort_indices_desc(dist): ...\ndef get_sort_indices_asc(dist): ...\ndef apply_sort_indices(dist, indices): ...\ndef euclid_distance_numpy_vector(v1, v2): ...\n", "repository": "neerbek/taboo-core", "test_name": "test_indices", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 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, 1, 0, 0], "pynose_source_file": "test_000420.py"} {"focal_file": "rnn_model/FlatTrainer.py", "focal_class": null, "focal_method": "train", "tests": "import unittest\n\nclass Test_train(unittest.TestCase):\n def test_train(self):\n rnnWrapper = RNNWrapper2()\n rnnWrapper.create_rnn()\n randFunction = TrainTest.getRandFunction(rnnWrapper)\n rnnWrapper.create_data()\n rnnWrapper.trainParam.batchSize = 50\n valContainer = rnnWrapper.cloneModel(False)\n rnn_model.FlatTrainer.train(rnnWrapper.trainParam, rnnWrapper.model, valContainer=valContainer, n_epochs=2, trainReportFrequency=1, validationFrequency=1)\n print(type(rnnWrapper), type(rnnWrapper.model), type(rnnWrapper.modelEvaluator))\n print('rand1', randFunction(rnnWrapper.trainParam.valX)[0:4, :])\n rnnWrapper.model = rnnWrapper.cloneModel(True)\n rnnWrapper.model.load(filename='save_running.txt')\n valContainer = rnnWrapper.cloneModel(False)\n rnnWrapper.modelEvaluator = rnn_model.FlatTrainer.ModelEvaluator(rnnWrapper.model, rnnWrapper.trainParam)\n acc = rnnWrapper.modelEvaluator.accuracyFunction(rnnWrapper.trainParam.valX, rnnWrapper.trainParam.valY)\n self.assertEqual(0.44, numpy.around(acc, 4))\n rnn_model.FlatTrainer.train(rnnWrapper.trainParam, rnnWrapper.model, valContainer, n_epochs=5, validationFrequency=1, epoch=3)\n acc = rnnWrapper.modelEvaluator.accuracyFunction(rnnWrapper.trainParam.valX, rnnWrapper.trainParam.valY)\n self.assertEqual(0.48, numpy.around(acc, 4))\n rnnWrapper.model = rnnWrapper.cloneModel(False)\n valContainer = rnnWrapper.cloneModel(False)\n rnn_model.FlatTrainer.train(rnnWrapper.trainParam, rnnWrapper.model, valContainer, n_epochs=7, validationFrequency=3, trainReportFrequency=2, epoch=6)\n acc = rnnWrapper.modelEvaluator.accuracyFunction(rnnWrapper.trainParam.valX, rnnWrapper.trainParam.valY)\n self.assertEqual(0.38, numpy.around(acc, 4))\n acc = rnnWrapper.modelEvaluator.accuracyFunction(rnnWrapper.trainParam.valX, rnnWrapper.trainParam.valY)\n self.assertEqual(0.38, numpy.around(acc, 4))\n rnnWrapper.modelEvaluator = rnn_model.FlatTrainer.ModelEvaluator(rnnWrapper.model, rnnWrapper.trainParam)\n acc = rnnWrapper.modelEvaluator.accuracyFunction(rnnWrapper.trainParam.valX, rnnWrapper.trainParam.valY)\n self.assertEqual(0.38, numpy.around(acc, 4))\n acc = rnnWrapper.modelEvaluator.accuracyFunction(rnnWrapper.trainParam.valX, rnnWrapper.trainParam.valY)\n self.assertEqual(0.38, numpy.around(acc, 4))\n acc = rnnWrapper.modelEvaluator.accuracyFunction(rnnWrapper.trainParam.valX, rnnWrapper.trainParam.valY)\n self.assertEqual(0.38, numpy.around(acc, 4))\n rnnWrapper.model = rnnWrapper.cloneModel(True)\n rnnWrapper.modelEvaluator = rnn_model.FlatTrainer.ModelEvaluator(rnnWrapper.model, rnnWrapper.trainParam)\n acc = rnnWrapper.modelEvaluator.accuracyFunction(rnnWrapper.trainParam.valX, rnnWrapper.trainParam.valY)\n self.assertEqual(0.5, numpy.around(acc, 4))\n acc = rnnWrapper.modelEvaluator.accuracyFunction(rnnWrapper.trainParam.valX, rnnWrapper.trainParam.valY)\n self.assertEqual(0.44, numpy.around(acc, 4))\n acc = rnnWrapper.modelEvaluator.accuracyFunction(rnnWrapper.trainParam.valX, rnnWrapper.trainParam.valY)\n self.assertEqual(0.36, numpy.around(acc, 4))\n acc = rnnWrapper.modelEvaluator.accuracyFunction(rnnWrapper.trainParam.valX, rnnWrapper.trainParam.valY)\n print('test done')\n", "method_code": "def train(trainParam, rnnContainer, valContainer, n_epochs=1, trainReportFrequency=1, validationFrequency=1, file_prefix='save', rng=RandomState(1234), epoch=0, runOnly=False):\n it = 0\n n = trainParam.getDataCount()\n if trainParam.batchSize == 0:\n trainParam.batchSize = n\n nTrainBatches = int(numpy.ceil(n / trainParam.batchSize))\n modelEvaluator = ModelEvaluator(rnnContainer, trainParam)\n rnnContainer.addTrainUpdates(trainParam, modelEvaluator, extraOutputs=[modelEvaluator.accuracy(), modelEvaluator.cost()])\n performanceMeasurer = FlatPerformanceMeasurer(epoch)\n print('calculating validation score')\n rnnContainer.updateClone(valContainer)\n valModelEvaluator = ModelEvaluator(valContainer, trainParam)\n valX, valY = trainParam.getValidationData()\n performanceMeasurer = measure(valX, valY, trainParam.validBatchSize, valModelEvaluator, epoch)\n performanceMeasurer.report(msg='{} Epoch {}. On validation set: (this is new best): '.format(datetime.now().strftime('%d%m%y %H:%M'), epoch))\n if runOnly:\n return\n performanceMeasurerBest = performanceMeasurer\n performanceMeasurerBest.epoch = epoch\n performanceMeasurerBest.runningEpoch = epoch\n while n_epochs == -1 or epoch < n_epochs:\n X, Y = trainParam.getDataPermuted(rng)\n epoch += 1\n trainCost = 0\n trainAcc = 0\n trainCount = 0\n for minibatchIndex in range(nTrainBatches):\n xIn, yIn = trainParam.getMiniBatch(minibatchIndex, X, Y)\n currentSize = xIn.shape[0]\n if currentSize == 0:\n print('empty train iteration')\n continue\n values = rnnContainer.doTrain(xIn, yIn)\n trainAcc += values[0] * currentSize\n trainCost += values[1] * currentSize\n trainCount += currentSize\n it += 1\n if it % trainReportFrequency == 0:\n minibatchZeros = numpy.sum(yIn[:, 0]) / yIn.shape[0]\n minibatchAcc = values[0]\n print('{} Epoch {}. On train set : Node count {}, avg cost {:.6f}, avg acc {:.4f}%'.format(datetime.now().strftime('%d%m%y %H:%M'), epoch, trainCount, trainCost / trainCount, trainAcc / trainCount * 100.0))\n print('minibatch {}/{}, On train set: batch acc {:.4f} % ({:.4f} %)'.format(minibatchIndex + 1, nTrainBatches, minibatchAcc * 100.0, minibatchZeros * 100.0))\n if it % validationFrequency == 0:\n rnnContainer.updateClone(valContainer)\n valX, valY = trainParam.getValidationData()\n performanceMeasurer = measure(valX, valY, trainParam.validBatchSize, valModelEvaluator, epoch)\n performanceMeasurer.report(msg='{} Epoch {}. On validation set: Best ({}, {:.6f}, {:.4f}%). Current: '.format(datetime.now().strftime('%d%m%y %H:%M'), epoch, performanceMeasurerBest.epoch, performanceMeasurerBest.cost * 1.0, performanceMeasurerBest.accuracy * 100.0))\n cm = performanceMeasurer.confusionMatrix\n if valX.shape[0] != cm[0] + cm[1] + cm[2] + cm[3]:\n raise Exception('Expected total_node_count to be equal to sum', valX.shape[0], cm[0] + cm[1] + cm[2] + cm[3])\n print('Confusion Matrix validation (tp,fp,tn,fn)', cm[0], cm[1], cm[2], cm[3])\n if performanceMeasurerBest.accuracy < performanceMeasurer.accuracy:\n saveBest(model=rnnContainer, filePrefix=file_prefix, epoch=epoch, performanceMeasurer=performanceMeasurer, performanceMeasurerBest=performanceMeasurerBest)\n performanceMeasurerBest = performanceMeasurer\n performanceMeasurerBest.runningEpoch = epoch\n elif performanceMeasurerBest.runningEpoch + 1 < epoch:\n saveRunning(model=rnnContainer, filePrefix=file_prefix, epoch=epoch, performanceMeasurer=performanceMeasurer, performanceMeasurerBest=performanceMeasurerBest)\n performanceMeasurerBest.runningEpoch = epoch\n saveRunning(model=rnnContainer, filePrefix=file_prefix, epoch=epoch, performanceMeasurer=performanceMeasurer, performanceMeasurerBest=performanceMeasurerBest)", "context": "def train(trainParam, rnnContainer, valContainer, n_epochs=1, trainReportFrequency=1, validationFrequency=1, file_prefix='save', rng=RandomState(1234), epoch=0, runOnly=False): ...\ndef getMatrixShape(x): ...\ndef measure(X, Y, batchSize, modelEvaluator, epoch=-1): ...\ndef train(trainParam, rnnContainer, valContainer, n_epochs=1, trainReportFrequency=1, validationFrequency=1, file_prefix='save', rng=RandomState(1234), epoch=0, runOnly=False): ...\ndef saveRunning(model, filePrefix, epoch, performanceMeasurer, performanceMeasurerBest): ...\ndef saveBest(model, filePrefix, epoch, performanceMeasurer, performanceMeasurerBest): ...\ndef save(model, filename, epoch, performanceMeasurer, performanceMeasurerBest): ...\n", "repository": "neerbek/taboo-core", "test_name": "test_train", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0], "pynose_source_file": "test_000421.py"} {"focal_file": "similarity/load_trees.py", "focal_class": null, "focal_method": "get_trees", "tests": "import unittest\n\nclass Test_get_trees(unittest.TestCase):\n def test_no_empty_trees(self):\n all_trees = self.get_trees()\n self.assertEqual(2001, len(all_trees))\n for t in all_trees:\n self.assertNotEqual(0, load_trees.count_non_leaf_nodes(t), 'expected count to be bigger than 0')\n", "method_code": "def get_trees(file, max_count=-1):\n filename = file\n count = 0\n trees = []\n fn = 'get_trees'\n Warnings.warnRootNodeWord = 0\n with ai_util.AIFileWrapper(filename) as aifileWrapper:\n for line in aifileWrapper.fd:\n line = aifileWrapper.toStrippedString(line)\n if max_count > -1 and count > max_count:\n break\n tree = get_tree(line, fn)\n if tree.is_leaf():\n print('tree is one word. Ignoring')\n continue\n trees.append(tree)\n count += 1\n if count % 2000 == 0:\n print('Extracted: ', count)\n print(fn + ' done reading {}. Count={}. Roots with words count {}'.format(filename, count, Warnings.warnRootNodeWord))\n return trees", "context": "def get_trees(file, max_count=-1): ...\ndef clone_tree(node, parent=None): ...\ndef as_array(node): ...\ndef read_rep(l, index, node): ...\ndef output(node): ...\ndef output_sentence_impl(node): ...\ndef output_sentence(node): ...\ndef output_lenrep(node): ...\ndef parse_line(l, index, node): ...\ndef get_tree(line, fn='get_tree'): ...\ndef get_trees(file, max_count=-1): ...\ndef put_trees(filename, trees): ...\ndef get_fraction(trees, report=False): ...\ndef escape_sentence(l2): ...\ndef unescape_sentence(l2): ...\ndef count_leaf_nodes(node, count=0): ...\ndef count_non_leaf_nodes(node, count=0): ...\ndef count_nodes(node, count=0): ...\ndef cleanTreesByLength(trees, sentenceCutoffLow=5, sentenceCutoffHigh=200): ...\ndef cleanTreesByBadChars(trees): ...\n", "repository": "neerbek/taboo-core", "test_name": "test_no_empty_trees", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000422.py"} {"focal_file": "similarity/load_trees.py", "focal_class": null, "focal_method": "clone_tree", "tests": "import unittest\n\nclass Test_clone_tree(unittest.TestCase):\n def test_clone(self):\n n = load_trees.Node()\n n.syntax = '2'\n n2 = n.add_child()\n n2.syntax = 'n2'\n n21 = n2.add_child()\n n21.syntax = 'n21'\n n211 = n21.add_child()\n n211.syntax = 'n211'\n n22 = n2.add_child()\n n22.syntax = 'n22'\n n221 = n22.add_child()\n n221.syntax = 'n221'\n n222 = n22.add_child()\n n222.syntax = 'n222'\n n1 = n.add_child()\n n1.syntax = 'n1'\n n_clone = load_trees.clone_tree(n)\n a1 = load_trees.as_array(n)\n a2 = load_trees.as_array(n_clone)\n for i in range(len(a1)):\n self.assertEqual(a1[i].syntax, a2[i].syntax, 'expected nodes to share values')\n", "method_code": "def clone_tree(node, parent=None):\n if node == None:\n return None\n n = Node()\n n.parent = parent\n n.word = node.word\n n.syntax = node.syntax\n n.representation = node.representation\n n.left = clone_tree(node.left, n)\n n.right = clone_tree(node.right, n)\n n.update_count = node.update_count\n return n", "context": "def clone_tree(node, parent=None): ...\ndef clone_tree(node, parent=None): ...\ndef as_array(node): ...\ndef read_rep(l, index, node): ...\ndef output(node): ...\ndef output_sentence_impl(node): ...\ndef output_sentence(node): ...\ndef output_lenrep(node): ...\ndef parse_line(l, index, node): ...\ndef get_tree(line, fn='get_tree'): ...\ndef get_trees(file, max_count=-1): ...\ndef put_trees(filename, trees): ...\ndef get_fraction(trees, report=False): ...\ndef escape_sentence(l2): ...\ndef unescape_sentence(l2): ...\ndef count_leaf_nodes(node, count=0): ...\ndef count_non_leaf_nodes(node, count=0): ...\ndef count_nodes(node, count=0): ...\ndef cleanTreesByLength(trees, sentenceCutoffLow=5, sentenceCutoffHigh=200): ...\ndef cleanTreesByBadChars(trees): ...\n", "repository": "neerbek/taboo-core", "test_name": "test_clone", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000423.py"} {"focal_file": "rnn_model/learn.py", "focal_class": null, "focal_method": "gd", "tests": "import unittest\n\nclass Test_gd(unittest.TestCase):\n def test_gd(self):\n lr = 0.4\n n_loops = 5000\n rnnWrapper = RNNWrapper()\n rnnWrapper.create_rnn()\n updates = learn.gd(params=rnnWrapper.params, grads=rnnWrapper.grads, lr=lr)\n rnnWrapper.add_updates(updates)\n rnnWrapper.create_data()\n x_val = rnnWrapper.x_val\n y_val = rnnWrapper.y_val\n z_val = rnnWrapper.z_val\n for i in range(n_loops):\n rnnWrapper.do_train(x_val, y_val, z_val)\n self.assertEqual(0.1, rnnWrapper.validate_model(x_val, y_val, z_val), 'Mismatch in final expected gd error ratio')\n", "method_code": "def gd(params, grads, lr):\n updates = {}\n for param, grad in zip(params, grads):\n updates[param] = param - lr * grad\n return updates", "context": "def gd(params, grads, lr): ...\ndef adagrad(params, grads, lr, epsilon=1e-08): ...\ndef gd(params, grads, lr): ...\ndef gd_momentum(params, grads, lr, mc): ...\n", "repository": "neerbek/taboo-core", "test_name": "test_gd", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000424.py"} {"focal_file": "rnn_model/learn.py", "focal_class": null, "focal_method": "adagrad", "tests": "import unittest\n\nclass Test_adagrad(unittest.TestCase):\n def test_adaGrad(self):\n lr = 0.025\n n_loops = 2200\n rnnWrapper = RNNWrapper()\n rnnWrapper.create_rnn()\n updates = learn.adagrad(params=rnnWrapper.params, grads=rnnWrapper.grads, lr=lr)\n rnnWrapper.add_updates(updates)\n rnnWrapper.create_data()\n x_val = rnnWrapper.x_val\n y_val = rnnWrapper.y_val\n z_val = rnnWrapper.z_val\n for i in range(n_loops):\n rnnWrapper.do_train(x_val, y_val, z_val)\n self.assertEqual(0.04, rnnWrapper.validate_model(x_val, y_val, z_val), 'Mismatch in final expected adagrad error ratio')\n", "method_code": "def adagrad(params, grads, lr, epsilon=1e-08):\n updates = {}\n for param, grad in zip(params, grads):\n value = param.get_value(borrow=True)\n accu = theano.shared(numpy.zeros(value.shape, dtype=value.dtype), broadcastable=param.broadcastable, name=param.name + '_accu')\n accu_new = accu + grad ** 2\n updates[accu] = accu_new\n updates[param] = param - lr * grad / T.sqrt(accu_new + epsilon)\n return updates", "context": "def adagrad(params, grads, lr, epsilon=1e-08): ...\ndef adagrad(params, grads, lr, epsilon=1e-08): ...\ndef gd(params, grads, lr): ...\ndef gd_momentum(params, grads, lr, mc): ...\n", "repository": "neerbek/taboo-core", "test_name": "test_adaGrad", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000425.py"} {"focal_file": "rnn_model/learn.py", "focal_class": null, "focal_method": "gd_momentum", "tests": "import unittest\n\nclass Test_gd_momentum(unittest.TestCase):\n def test_gd_momentum(self):\n lr = 0.75\n mc = 0.0009\n n_loops = 3000\n rnnWrapper = RNNWrapper()\n rnnWrapper.create_rnn()\n updates = learn.gd_momentum(params=rnnWrapper.params, grads=rnnWrapper.grads, lr=lr, mc=mc)\n rnnWrapper.add_updates(updates)\n rnnWrapper.create_data()\n x_val = rnnWrapper.x_val\n y_val = rnnWrapper.y_val\n z_val = rnnWrapper.z_val\n for i in range(n_loops):\n rnnWrapper.do_train(x_val, y_val, z_val)\n self.assertEqual(0.04, rnnWrapper.validate_model(x_val, y_val, z_val), 'Mismatch in final expected error')\n\n def test_gd_momentum_nodropout(self):\n lr = 0.75\n mc = 0.0009\n n_loops = 3000\n rnnWrapper = RNNWrapper()\n rnnWrapper.retain_probability = 1\n rnnWrapper.create_rnn()\n updates = learn.gd_momentum(params=rnnWrapper.params, grads=rnnWrapper.grads, lr=lr, mc=mc)\n rnnWrapper.add_updates(updates)\n rnnWrapper.create_data()\n x_val = rnnWrapper.x_val\n y_val = rnnWrapper.y_val\n z_val = rnnWrapper.z_val\n for i in range(n_loops):\n rnnWrapper.do_train(x_val, y_val, z_val)\n self.assertEqual(0.08, rnnWrapper.validate_model(x_val, y_val, z_val), 'Mismatch in final expected error')\n", "method_code": "def gd_momentum(params, grads, lr, mc):\n updates = {}\n for param, grad in zip(params, grads):\n value = param.get_value(borrow=True)\n param_prev = theano.shared(numpy.zeros(value.shape, dtype=value.dtype), broadcastable=param.broadcastable, name=param.name + '_prev')\n updates[param] = param - lr * grad - mc * param_prev\n updates[param_prev] = param\n return updates", "context": "def gd_momentum(params, grads, lr, mc): ...\ndef adagrad(params, grads, lr, epsilon=1e-08): ...\ndef gd(params, grads, lr): ...\ndef gd_momentum(params, grads, lr, mc): ...\n", "repository": "neerbek/taboo-core", "test_name": "test_gd_momentum", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000426.py"} {"focal_file": "server_enron.py", "focal_class": null, "focal_method": "run_rnn", "tests": "import unittest\n\nclass Test_run_rnn(unittest.TestCase):\n def test_run_rnn1(self):\n initialize_model()\n server_enron.request = Request()\n res = server_enron.run_rnn()\n if not isinstance(res, Response):\n self.assertTrue(False, 'expected Response class')\n print(res.status)\n self.assertTrue(res.status_code == 500)\n\n def test_run_rnn2(self):\n initialize_model()\n server_enron.request = Request()\n server_enron.request.args.args['text'] = example_text\n res = server_enron.run_rnn()\n if not isinstance(res, str):\n self.assertTrue(False, 'expected string response')\n d = json.loads(res)\n self.assertTrue(len(d) == 1)\n self.assertTrue(d['predictions'] != None)\n\n def test_run_rnn3(self):\n initialize_model()\n server_enron.request = Request()\n server_enron.request.args.args['text'] = 'Sentence fragments are representative of their quoted statement'\n res = server_enron.run_rnn()\n if not isinstance(res, str):\n self.assertTrue(False, 'expected string response')\n print(res)\n d = json.loads(res)\n self.assertTrue(len(d) == 1)\n print(d['predictions'])\n self.assertEqual(1, d['predictions'][0]['prediction'], 'expected first result to be sensitive')\n", "method_code": "def run_rnn():\n print('run_rnn')\n text = request.args.get('text')\n if text is None or len(text) == 0:\n return response_error('No text received')\n else:\n print('parsing text')\n indexed_sentences = server_rnn_helper.get_indexed_sentences(text)\n parserStatistics = rnn_enron.ParserStatistics()\n trees = server_rnn_helper.get_nltk_trees(0, indexed_sentences, parserStatistics)\n for t in trees:\n t.replace_nodenames('0')\n rnn_enron.initializeTrees(trees, serverState.server_rnn_state.LT)\n print('getting predictions')\n server_rnn.get_predictions(serverState.rnn, indexed_sentences)\n for s in indexed_sentences:\n s.pred = s.pred == 4\n res = server_enron_helper.index_sentences_to_predictions(indexed_sentences)\n return response_success(res)", "context": "@app.route('/run_model/rnn')\ndef run_rnn(): ...\ndef is_none(l): ...\ndef is_positive(l): ...\ndef hello_world(): ...\ndef run_rnn(): ...\ndef run_keyword(): ...\ndef load_model_data(): ...\ndef load_model_data_from_file(): ...\ndef train_rnn_impl(trainer, n_epochs): ...\ndef train_rnn(): ...\ndef train_keyword(): ...\ndef get_examples(): ...\ndef response_error(msg): ...\ndef toJSON(e): ...\ndef response_success(value, root_tag=None): ...\n", "repository": "neerbek/taboo-core", "test_name": "test_run_rnn1", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0], "pynose_source_file": "test_000427.py"} {"focal_file": "server_enron.py", "focal_class": null, "focal_method": "run_keyword", "tests": "import unittest\n\nclass Test_run_keyword(unittest.TestCase):\n def test_run_keyword1(self):\n initialize_model()\n server_enron.request = Request()\n res = server_enron.run_keyword()\n if not isinstance(res, Response):\n self.assertTrue(False, 'expected Response class')\n print(res.status)\n self.assertTrue(res.status_code == 500)\n\n def test_run_keyword2(self):\n initialize_model()\n server_enron.request = Request()\n server_enron.request.args.args['text'] = example_text\n res = server_enron.run_keyword()\n if not isinstance(res, str):\n self.assertTrue(False, 'expected string response')\n d = json.loads(res)\n self.assertTrue(len(d) == 1)\n self.assertTrue(d['predictions'] != None)\n self.assertTrue(len(d['predictions']) == 1)\n\n def test_run_keyword3(self):\n initialize_model()\n server_enron.request = Request()\n server_enron.request.args.args['text'] = example_text2\n res = server_enron.run_keyword()\n if not isinstance(res, str):\n self.assertTrue(False, 'expected string response')\n d = json.loads(res)\n self.assertTrue(len(d) == 1)\n self.assertTrue(d['predictions'] != None)\n self.assertEqual(1, len(d['predictions']), 'expected a prediction')\n", "method_code": "def run_keyword():\n print('run_keyword')\n text = request.args.get('text')\n if text is None or len(text) == 0:\n return response_error('No text received')\n else:\n print('getting predictions')\n indexed_sentences = inference_enron.get_predictions(text, keywordState.indicators)\n res = server_enron_helper.index_sentences_to_predictions(indexed_sentences)\n return response_success(res)", "context": "@app.route('/run_model/keyword')\ndef run_keyword(): ...\ndef is_none(l): ...\ndef is_positive(l): ...\ndef hello_world(): ...\ndef run_rnn(): ...\ndef run_keyword(): ...\ndef load_model_data(): ...\ndef load_model_data_from_file(): ...\ndef train_rnn_impl(trainer, n_epochs): ...\ndef train_rnn(): ...\ndef train_keyword(): ...\ndef get_examples(): ...\ndef response_error(msg): ...\ndef toJSON(e): ...\ndef response_success(value, root_tag=None): ...\n", "repository": "neerbek/taboo-core", "test_name": "test_run_keyword1", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0], "pynose_source_file": "test_000428.py"} {"focal_file": "server_enron.py", "focal_class": null, "focal_method": "train_keyword", "tests": "import unittest\n\nclass Test_train_keyword(unittest.TestCase):\n def test_load_keyword1(self):\n initialize_model()\n server_enron.request = Request()\n server_enron.request.args.args['cut_off'] = '0.9'\n res = server_enron.train_keyword()\n if not isinstance(res, str):\n self.assertTrue(False, 'expected string response')\n d = json.loads(res)\n self.assertTrue(len(d) == 1)\n self.assertTrue(d['msg'] != None)\n", "method_code": "def train_keyword():\n print('train_keyword')\n cut_off = request.args.get('cut_off')\n if is_none([cut_off]):\n return response_error('Training keywords needs cutoff')\n cut_off = float(cut_off)\n keywordState.initialize(serverState.server_rnn_state, cut_off)\n print('train_keyword DONE')\n sys.stdout.flush()\n return response_success(ResponseString('keyword training completed'))", "context": "@app.route('/train_model/keyword')\ndef train_keyword(): ...\ndef is_none(l): ...\ndef is_positive(l): ...\ndef hello_world(): ...\ndef run_rnn(): ...\ndef run_keyword(): ...\ndef load_model_data(): ...\ndef load_model_data_from_file(): ...\ndef train_rnn_impl(trainer, n_epochs): ...\ndef train_rnn(): ...\ndef train_keyword(): ...\ndef get_examples(): ...\ndef response_error(msg): ...\ndef toJSON(e): ...\ndef response_success(value, root_tag=None): ...\n", "repository": "neerbek/taboo-core", "test_name": "test_load_keyword1", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000429.py"} {"focal_file": "server_enron.py", "focal_class": null, "focal_method": "load_model_data", "tests": "import unittest\n\nclass Test_load_model_data(unittest.TestCase):\n def test_load_model(self):\n initialize_model()\n req = Request()\n server_enron.request = req\n res = server_enron.load_model_data()\n if not isinstance(res, Response):\n self.assertTrue(False, 'expected Response class')\n self.assertTrue(res.status_code == 500)\n\n def test_load_model2(self):\n initialize_model()\n req = Request()\n req.args.args['labelfile'] = 'tests/resources/enron_labels_test.txt'\n req.args.args['data_dir'] = os.path.join(os.getcwd(), 'tests/resources/enron_shortdata_test')\n req.args.args['data_label'] = '201'\n req.args.args['total_ratio'] = '1'\n req.args.args['train_ratio'] = '0.6'\n req.args.args['dev_ratio'] = '0.75'\n server_enron.request = req\n res = server_enron.load_model_data()\n if not isinstance(res, str):\n self.assertTrue(False, 'expected string response')\n d = json.loads(res)\n self.assertTrue(d['msg'] != None)\n self.assertTrue(len(server_enron.serverState.train_trees) == 11)\n", "method_code": "def load_model_data():\n print('train_data loading')\n labelfile = request.args.get('labelfile')\n data_dir = request.args.get('data_dir')\n data_label = request.args.get('data_label')\n total_ratio_str = request.args.get('total_ratio')\n train_ratio_str = request.args.get('train_ratio')\n dev_ratio_str = request.args.get('dev_ratio')\n if is_none([data_dir, labelfile, data_label, total_ratio_str, train_ratio_str, dev_ratio_str]):\n return response_error('Load data needs parameters labelfile, data_dir, data_label, total_ratio, train_ratio, dev_ratio')\n total_ratio = float(total_ratio_str)\n train_ratio = float(train_ratio_str)\n dev_ratio = float(dev_ratio_str)\n if not is_positive([total_ratio, train_ratio, dev_ratio]):\n return response_error('Load data needs parameters total_ratio, train_ratio, dev_ratio to be postive numbers (below 1)')\n doc2 = server_enron_helper.load_labeled_documents(labelfile, data_dir, data_label)\n print('***totalratio:', len(doc2), total_ratio, train_ratio, dev_ratio)\n total_index = int(len(doc2) * total_ratio)\n train_index = int(total_index * train_ratio)\n dev_index = int(len(doc2) * dev_ratio)\n print('***totalindex:', total_index, train_index, dev_index)\n parserStatistics = rnn_enron.ParserStatistics()\n train_trees = server_rnn_helper.get_trees(doc2[:train_index], serverState.server_rnn_state.LT, parserStatistics)\n dev_trees = server_rnn_helper.get_trees(doc2[train_index:dev_index], serverState.server_rnn_state.LT, parserStatistics)\n test_trees = server_rnn_helper.get_trees(doc2[dev_index:], serverState.server_rnn_state.LT, parserStatistics)\n print('***trees loaded')\n serverState.train_trees = train_trees\n serverState.valid_trees = dev_trees\n serverState.test_trees = test_trees\n print('train_data DONE loading')\n sys.stdout.flush()\n return response_success(ResponseString('load completed'))", "context": "@app.route('/train_data')\ndef load_model_data(): ...\ndef is_none(l): ...\ndef is_positive(l): ...\ndef hello_world(): ...\ndef run_rnn(): ...\ndef run_keyword(): ...\ndef load_model_data(): ...\ndef load_model_data_from_file(): ...\ndef train_rnn_impl(trainer, n_epochs): ...\ndef train_rnn(): ...\ndef train_keyword(): ...\ndef get_examples(): ...\ndef response_error(msg): ...\ndef toJSON(e): ...\ndef response_success(value, root_tag=None): ...\n", "repository": "neerbek/taboo-core", "test_name": "test_load_model", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000430.py"} {"focal_file": "server_enron.py", "focal_class": null, "focal_method": "train_rnn_impl", "tests": "import unittest\n\nclass Test_train_rnn_impl(unittest.TestCase):\n def test_train_rnn1(self):\n initialize_model()\n server_enron.request = Request()\n trainer = server_rnn.Trainer()\n server_enron.serverState.server_rnn_state.load_trees(trainer, max_tree_count=100)\n server_enron.train_rnn_impl(trainer, 1)\n", "method_code": "def train_rnn_impl(trainer, n_epochs):\n trainer.train(state=serverState.server_rnn_state, rnnWrapper=serverState.rnn, n_epochs=n_epochs, rng=serverState.rng)", "context": "def train_rnn_impl(trainer, n_epochs): ...\ndef is_none(l): ...\ndef is_positive(l): ...\ndef hello_world(): ...\ndef run_rnn(): ...\ndef run_keyword(): ...\ndef load_model_data(): ...\ndef load_model_data_from_file(): ...\ndef train_rnn_impl(trainer, n_epochs): ...\ndef train_rnn(): ...\ndef train_keyword(): ...\ndef get_examples(): ...\ndef response_error(msg): ...\ndef toJSON(e): ...\ndef response_success(value, root_tag=None): ...\n", "repository": "neerbek/taboo-core", "test_name": "test_train_rnn1", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 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, 1], "pynose_source_file": "test_000431.py"} {"focal_file": "server_enron.py", "focal_class": null, "focal_method": "train_rnn", "tests": "import unittest\n\nclass Test_train_rnn(unittest.TestCase):\n def test_train_rnn2(self):\n initialize_model()\n server_enron.request = Request()\n trainer = server_rnn.Trainer()\n server_enron.serverState.server_rnn_state.load_trees(trainer, max_tree_count=100)\n req = Request()\n server_enron.request = req\n res = server_enron.train_rnn()\n if not isinstance(res, Response):\n self.assertTrue(False, 'expected Response class')\n self.assertTrue(res.status_code == 500)\n\n def test_train_rnn3(self):\n initialize_model()\n server_enron.request = Request()\n trainer = server_rnn.Trainer()\n server_enron.serverState.server_rnn_state.load_trees(trainer, max_tree_count=100)\n req = Request()\n req.args.args['learning_rate'] = '0.001'\n req.args.args['L1_reg'] = '0.001'\n req.args.args['L2_reg'] = '0.001'\n req.args.args['n_epochs'] = '1'\n req.args.args['batch_size'] = '50'\n req.args.args['retain_probability'] = '0.8'\n server_enron.request = req\n res = server_enron.train_rnn()\n if not isinstance(res, str):\n self.assertTrue(False, 'expected string response')\n d = json.loads(res)\n print(res)\n self.assertTrue(len(d) == 1)\n", "method_code": "def train_rnn():\n print('train_rnn')\n print('loading model')\n trainer = server_rnn.Trainer()\n learning_rate = request.args.get('learning_rate')\n L1_reg = request.args.get('L1_reg')\n L2_reg = request.args.get('L2_reg')\n n_epochs = request.args.get('n_epochs')\n batch_size = request.args.get('batch_size')\n retain_probability = request.args.get('retain_probability')\n if is_none([learning_rate, L1_reg, L2_reg, n_epochs, batch_size, retain_probability]):\n return response_error('Training needs parameters learning_rate, L1_reg, L2_reg, n_epochs, batch_size, retain_probability')\n trainer.retain_probability = float(retain_probability)\n trainer.batch_size = int(batch_size)\n trainer.L2_reg = float(L2_reg)\n trainer.L1_reg = float(L1_reg)\n trainer.learning_rate = float(learning_rate)\n n_epochs = int(n_epochs)\n trainer.update_batch_size(serverState.server_rnn_state)\n if not is_positive([trainer.learning_rate, n_epochs, trainer.batch_size]):\n return response_error('Training needs parameters learning_rate, n_epochs, batch_size to be above zero')\n train_rnn_impl(trainer, n_epochs)\n print('train RNN DONE')\n sys.stdout.flush()\n return response_success(ResponseString('training completed'))", "context": "@app.route('/train_model/rnn')\ndef train_rnn(): ...\ndef is_none(l): ...\ndef is_positive(l): ...\ndef hello_world(): ...\ndef run_rnn(): ...\ndef run_keyword(): ...\ndef load_model_data(): ...\ndef load_model_data_from_file(): ...\ndef train_rnn_impl(trainer, n_epochs): ...\ndef train_rnn(): ...\ndef train_keyword(): ...\ndef get_examples(): ...\ndef response_error(msg): ...\ndef toJSON(e): ...\ndef response_success(value, root_tag=None): ...\n", "repository": "neerbek/taboo-core", "test_name": "test_train_rnn2", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0], "pynose_source_file": "test_000432.py"} {"focal_file": "server_enron.py", "focal_class": null, "focal_method": "get_examples", "tests": "import unittest\n\nclass Test_get_examples(unittest.TestCase):\n def test_get_examples(self):\n initialize_model()\n server_enron.request = Request()\n res = server_enron.get_examples()\n if not isinstance(res, str):\n self.assertTrue(False, 'expected string response')\n d = json.loads(res)\n self.assertTrue(len(d) == 1)\n for p in d['predictions']:\n print(p['prediction'], p['text'])\n", "method_code": "def get_examples():\n train = serverState.server_rnn_state.train_trees\n rng = serverState.rng\n train = rng.choice(train, 50, replace=False)\n res = []\n for s in train:\n y_target = np.argmax(s.label)\n txt = load_trees.output_sentence(s)\n txt = load_trees.unescape_sentence(txt) + '\\n'\n if len(txt) < 22 or len(txt) > 140:\n continue\n sent = server_rnn_helper.IndexSentence(0, txt)\n sent.y_target = y_target\n sent.endIndex = len(txt)\n res.append(sent)\n res = res[:10]\n parserStatistics = rnn_enron.ParserStatistics()\n trees = server_rnn_helper.get_nltk_trees(0, res, parserStatistics)\n for t in trees:\n t.replace_nodenames('0')\n rnn_enron.initializeTrees(trees, serverState.server_rnn_state.LT)\n server_rnn.get_predictions(serverState.rnn, res)\n indexed_sentences = []\n count = 0\n for s in res:\n if len(indexed_sentences) == 5:\n break\n if s.y_target == s.pred:\n sent = server_rnn_helper.IndexSentence(0, s.sentence)\n print('s.pred', s.pred)\n sent.pred = s.pred == 4\n sent.endIndex = s.endIndex\n indexed_sentences.append(sent)\n count += 1\n print('visited:', count)\n for s in indexed_sentences:\n print(s.pred, len(s.sentence), s.sentence)\n sys.stdout.flush()\n l = server_enron_helper.index_sentences_to_predictions(indexed_sentences)\n return response_success(l)", "context": "@app.route('/examples')\ndef get_examples(): ...\ndef is_none(l): ...\ndef is_positive(l): ...\ndef hello_world(): ...\ndef run_rnn(): ...\ndef run_keyword(): ...\ndef load_model_data(): ...\ndef load_model_data_from_file(): ...\ndef train_rnn_impl(trainer, n_epochs): ...\ndef train_rnn(): ...\ndef train_keyword(): ...\ndef get_examples(): ...\ndef response_error(msg): ...\ndef toJSON(e): ...\ndef response_success(value, root_tag=None): ...\n", "repository": "neerbek/taboo-core", "test_name": "test_get_examples", "smells": [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0], "pynose_source_file": "test_000433.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": "andersenqvist/logistics-wizard-controller", "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_000434.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": "andersenqvist/logistics-wizard-controller", "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_000435.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": "andersenqvist/logistics-wizard-controller", "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_000436.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": "andersenqvist/logistics-wizard-controller", "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_000437.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": "andersenqvist/logistics-wizard-controller", "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_000438.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": "andersenqvist/logistics-wizard-controller", "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_000439.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": "andersenqvist/logistics-wizard-controller", "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_000440.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": "andersenqvist/logistics-wizard-controller", "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_000441.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": "andersenqvist/logistics-wizard-controller", "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_000442.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": "andersenqvist/logistics-wizard-controller", "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_000443.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": "andersenqvist/logistics-wizard-controller", "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_000444.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": "andersenqvist/logistics-wizard-controller", "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_000445.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": "andersenqvist/logistics-wizard-controller", "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_000446.py"} {"focal_file": "pathfinding/load_map.py", "focal_class": null, "focal_method": "read_tiles", "tests": "import unittest\n\nclass Test_read_tiles(unittest.TestCase):\n def test_read_tiles(self):\n f = StringIO('ab\\ncd')\n self.assertEquals(set(load_map.read_tiles(f)), set([((0, 0), 'c'), ((0, 1), 'a'), ((1, 0), 'd'), ((1, 1), 'b')]))\n", "method_code": "def read_tiles(f):\n \"\"\"Read file `f` and yield (position, char) tuples\"\"\"\n lines = f.read().splitlines()\n for y, line in enumerate(reversed(lines)):\n for x, char in enumerate(line):\n yield ((x, y), char)", "context": "def read_tiles(f): ...\ndef read_tiles(f): ...\ndef file_to_tile(f, start=START, blank=BLANK, wall=WALL, target=TARGET, heuristic=metrics.manhattan): ...\n", "repository": "vvanirudh/python-pathfinding", "test_name": "test_read_tiles", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 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_000447.py"} {"focal_file": "pathfinding/load_map.py", "focal_class": null, "focal_method": "file_to_tile", "tests": "import unittest\n\nclass Test_file_to_tile(unittest.TestCase):\n def test_file_to_tile(self):\n f = StringIO(load_map.START + load_map.TARGET)\n start, end = load_map.file_to_tile(f)\n self.assertEquals(start.pos, (0, 0))\n self.assertEquals(end.pos, (1, 0))\n", "method_code": "def file_to_tile(f, start=START, blank=BLANK, wall=WALL, target=TARGET, heuristic=metrics.manhattan):\n \"\"\"Take an input file `f` and return RectNodes start_node, target_node\n (if a target is not found, start_node, None will be returned instead \"\"\"\n walkable = {}\n start_pos = target_pos = None\n for pos, char in read_tiles(f):\n if char == wall:\n walkable[pos] = False\n elif char == target:\n target_pos = pos\n elif char == start:\n start_pos = pos\n elif char == blank:\n pass\n else:\n raise ValueError(\"Unknown tile type: '%s'\" % char)\n if start_pos is None:\n raise ValueError('No starting position in map')\n start_node = nodes.RectNode(start_pos, walkable=walkable, heuristic=heuristic)\n if target_pos is None:\n target_node = None\n else:\n target_node = nodes.RectNode(target_pos, walkable=walkable, heuristic=heuristic)\n return (start_node, target_node)", "context": "def file_to_tile(f, start=START, blank=BLANK, wall=WALL, target=TARGET, heuristic=metrics.manhattan): ...\ndef read_tiles(f): ...\ndef file_to_tile(f, start=START, blank=BLANK, wall=WALL, target=TARGET, heuristic=metrics.manhattan): ...\n", "repository": "vvanirudh/python-pathfinding", "test_name": "test_file_to_tile", "smells": [0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 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_000448.py"} {"focal_file": "price_watch/models.py", "focal_class": null, "focal_method": "get", "tests": "import unittest\n\nclass Test_get(unittest.TestCase):\n def test_report_get(self):\n res = self.testapp.get('/reports/{}'.format(self.report_key), status=200)\n self.assertIn(self.report_key, res.body)\n\n def test_page_get(self):\n res = self.testapp.get('/pages/about', status=200)\n self.assertIn(u'О проекте', res.text)\n\n def test_merchants_get(self):\n res = self.testapp.get('/merchants', status=200)\n self.assertIn(u'Московский магазин', res.json_body)\n", "method_code": " def get(self, namespace, key):\n \"\"\"Get instance from appropriate namespace by the key\"\"\"\n try:\n return self._root[namespace][key]\n except KeyError:\n return None\n ", "context": "class StorageManager(object):\n def get(self, namespace, key): ...\n def __init__(self, path=None, zodb_storage=None, connection=None): ...\n def __getitem__(self, namespace): ...\n def __resource_url__(self, request, info): ...\n def register(self, *instances): ...\n def delete(self, *instances): ...\n def delete_key(self, namespace, key): ...\n def get_all(self, namespace, objects_only=True): ...\n def close(self): ...\n def load_fixtures(self, path): ...\n def pack(self): ...\n\n self._root = self.connection.root()\n\n __name__ = None\n", "repository": "yentsun/price_watch", "test_name": "test_report_get", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 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_000449.py"} {"focal_file": "price_watch/models.py", "focal_class": null, "focal_method": "delete", "tests": "import unittest\n\nclass Test_delete(unittest.TestCase):\n def test_report_delete(self):\n res = self.testapp.delete('/reports/{}'.format(self.report_key), status=200)\n self.assertIn('deleted_report_key', res.body)\n self.testapp.get('/reports/{}'.format(self.report_key), status=404)\n", "method_code": " def delete(self, *instances):\n \"\"\"Delete instances from appropriate namespaces\"\"\"\n for instance in instances:\n instance.delete_from(self)\n ", "context": "class StorageManager(object):\n def delete(self, *instances): ...\n def __init__(self, path=None, zodb_storage=None, connection=None): ...\n def __getitem__(self, namespace): ...\n def __resource_url__(self, request, info): ...\n def register(self, *instances): ...\n def delete_key(self, namespace, key): ...\n def get(self, namespace, key): ...\n def get_all(self, namespace, objects_only=True): ...\n def close(self): ...\n def load_fixtures(self, path): ...\n def pack(self): ...\n\n self._root = self.connection.root()\n\n __name__ = None\n", "repository": "yentsun/price_watch", "test_name": "test_report_delete", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 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_000450.py"} {"focal_file": "price_watch/models.py", "focal_class": null, "focal_method": "patch", "tests": "import unittest\n\nclass Test_patch(unittest.TestCase):\n def test_merchant_patch(self):\n res = self.testapp.patch(u'/merchants/Московский магазин'.encode('utf-8'), [('title', 'Fred & Co.')], status=200)\n self.assertEqual('Fred & Co.', res.json_body['title'])\n self.testapp.get(u'/merchants/Московский магазин'.encode('utf-8'), status=404)\n res = self.testapp.get('/merchants/Fred & Co.', status=200)\n self.assertEqual('Fred & Co.', res.json_body['title'])\n", "method_code": " def patch(self, data, storage_manager):\n \"\"\"Update merchant from dict. Return `True` if new key created\"\"\"\n old_key = self.key\n if 'title' in data:\n self.title = data['title']\n if 'location' in data:\n self.location = data['location']\n if old_key != self.key:\n storage_manager.register(self)\n try:\n storage_manager.delete_key(self.namespace, old_key)\n except KeyError:\n pass\n ", "context": "class Merchant(Entity):\n def patch(self, data, storage_manager): ...\n def __init__(self, title, location=None): ...\n def add_product(self, product): ...\n def remove_product(self, product): ...\n def assemble(cls, storage_manager, title, location=None): ...\n\n self.title = title\n self.location = location\n self.products = list()\n\n _representation = u'{title}-{location}'\n namespace = 'merchants'\n _container_attr = 'products'\n", "repository": "yentsun/price_watch", "test_name": "test_merchant_patch", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000451.py"} {"focal_file": "price_watch/utilities.py", "focal_class": null, "focal_method": "multidict_to_list", "tests": "import unittest\n\nclass Test_multidict_to_list(unittest.TestCase):\n def test_multidict_to_list(self):\n from price_watch.utilities import multidict_to_list\n from webob.multidict import MultiDict\n multidict = MultiDict((('price_value', 55.6), ('url', 'http://howies.com/products/milk/4'), ('product_title', u'Молоко Красная Цена у/паст. 3.2% 1л'.encode('utf-8')), ('merchant_title', \"Howie's grocery\"), ('reporter_name', 'Jack'), ('price_value', 45.3), ('url', 'http://howies.com/products/milk/5'), ('product_title', u'Молоко Красная Цена у/паст. 1% 1л'.encode('utf-8')), ('merchant_title', \"Howie's grocery\"), ('reporter_name', 'Jack')))\n dict_list = multidict_to_list(multidict)\n self.assertEqual(2, len(dict_list))\n", "method_code": "def multidict_to_list(multidict):\n \"\"\"\n Convert Multidict object to a list of dicts. Dict tuples must have equal\n number of key/value pairs.\n \"\"\"\n dict_list = list()\n keys = multidict.dict_of_lists().keys()\n value_count = 0\n for key in keys:\n this_value_count = len(multidict.getall(key))\n if value_count is 0:\n value_count = this_value_count\n elif this_value_count != value_count:\n raise MultidictError()\n for index in range(0, value_count):\n new_dict = dict()\n for key in keys:\n new_dict[key] = multidict.getall(key)[index]\n dict_list.append(new_dict)\n return dict_list", "context": "def multidict_to_list(multidict): ...\ndef async_creation_runner(cache, somekey, creator, mutex): ...\ndef multidict_to_list(multidict): ...\n", "repository": "yentsun/price_watch", "test_name": "test_multidict_to_list", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000452.py"} {"focal_file": "daemon/openrazer_daemon/misc/effect_sync.py", "focal_class": null, "focal_method": "get_num_arguments", "tests": "import unittest\n\nclass Test_get_num_arguments(unittest.TestCase):\n def test_get_num_arguments(self):\n\n def func_2_args(x, y):\n return x + y\n num_args = self.effect_sync.get_num_arguments(func_2_args)\n self.assertEqual(num_args, 2)\n", "method_code": " def get_num_arguments(func):\n \"\"\"\n Get number of arguments in a function\n \n :param func: Function\n :type func: callable\n \n :return: Number of arguments\n :rtype: int\n \"\"\"\n func_sig = inspect.signature(func)\n return len(func_sig.parameters)\n ", "context": "class EffectSync(object):\n @staticmethod\n def get_num_arguments(func): ...\n def __init__(self, parent, device_number): ...\n def __del__(self): ...\n def close(self): ...\n def notify(self, msg): ...\n def run_effect(self, effect_name, *args): ...\n\n self._logger = logging.getLogger('razer.device{0}.effect_sync'.format(device_number))\n self._parent = parent\n", "repository": "openrazer/openrazer", "test_name": "test_get_num_arguments", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "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_000453.py"} {"focal_file": "daemon/openrazer_daemon/device.py", "focal_class": null, "focal_method": "register_parent", "tests": "import unittest\n\nclass Test_register_parent(unittest.TestCase):\n def test_device_register_parent(self):\n dbus_object = DummyDBusObject()\n parent_object = DummyParentObject()\n device_object = openrazer_daemon.device.Device(DEVICE1_ID, DEVICE1_SERIAL, dbus_object)\n device_object.register_parent(parent_object)\n self.assertEqual(device_object._parent, parent_object)\n", "method_code": " def register_parent(self, parent):\n \"\"\"\n Register the parent as an observer to be optionally notified (sends to other devices)\n \n :param parent: Observer\n :type parent: object\n \"\"\"\n self._parent = parent\n ", "context": "class Device(object):\n def register_parent(self, parent): ...\n def __init__(self, device_id, device_serial, device_dbus_object): ...\n def device_id(self): ...\n def serial(self): ...\n def dbus(self): ...\n def notify_parent(self, msg): ...\n def notify_child(self, msg): ...\n\n self._parent = None\n self._id = device_id\n self._serial = device_serial\n self._dbus = device_dbus_object\n", "repository": "openrazer/openrazer", "test_name": "test_device_register_parent", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000454.py"} {"focal_file": "daemon/openrazer_daemon/device.py", "focal_class": null, "focal_method": "notify_child", "tests": "import unittest\n\nclass Test_notify_child(unittest.TestCase):\n def test_device_notify_child(self):\n msg = ('test', 1)\n dbus_object = DummyDBusObject()\n device_object = openrazer_daemon.device.Device(DEVICE1_ID, DEVICE1_SERIAL, dbus_object)\n device_object.notify_child(msg)\n self.assertEqual(dbus_object.notify_msg, msg)\n", "method_code": " def notify_child(self, msg):\n \"\"\"\n Receive observer messages\n \n :param msg: Tuple with first element a string\n :type msg: tuple\n \"\"\"\n self._dbus.notify(msg)\n ", "context": "class Device(object):\n def notify_child(self, msg): ...\n def __init__(self, device_id, device_serial, device_dbus_object): ...\n def device_id(self): ...\n def serial(self): ...\n def dbus(self): ...\n def register_parent(self, parent): ...\n def notify_parent(self, msg): ...\n\n self._parent = None\n self._id = device_id\n self._serial = device_serial\n self._dbus = device_dbus_object\n", "repository": "openrazer/openrazer", "test_name": "test_device_notify_child", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000455.py"} {"focal_file": "daemon/openrazer_daemon/device.py", "focal_class": null, "focal_method": "notify_parent", "tests": "import unittest\n\nclass Test_notify_parent(unittest.TestCase):\n def test_device_notify_parent(self):\n msg = ('test', 1)\n dbus_object = DummyDBusObject()\n parent_object = DummyParentObject()\n device_object = openrazer_daemon.device.Device(DEVICE1_ID, DEVICE1_SERIAL, dbus_object)\n device_object.register_parent(parent_object)\n device_object.notify_parent(msg)\n self.assertEqual(parent_object.notify_msg, msg)\n self.assertEqual(parent_object.notify_device, device_object)\n", "method_code": " def notify_parent(self, msg):\n \"\"\"\n Notify observers with msg\n \n :param msg: Tuple with first element a string\n :type msg: tuple\n \"\"\"\n self._parent.notify(self, msg)\n ", "context": "class Device(object):\n def notify_parent(self, msg): ...\n def __init__(self, device_id, device_serial, device_dbus_object): ...\n def device_id(self): ...\n def serial(self): ...\n def dbus(self): ...\n def register_parent(self, parent): ...\n def notify_child(self, msg): ...\n\n self._parent = None\n self._id = device_id\n self._serial = device_serial\n self._dbus = device_dbus_object\n", "repository": "openrazer/openrazer", "test_name": "test_device_notify_parent", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000456.py"} {"focal_file": "daemon/openrazer_daemon/device.py", "focal_class": null, "focal_method": "add", "tests": "import unittest\n\nclass Test_add(unittest.TestCase):\n def test_add(self):\n dbus_object = DummyDBusObject()\n self.device_collection.add(DEVICE1_ID, DEVICE1_SERIAL, dbus_object)\n self.assertIn(DEVICE1_ID, self.device_collection._id_map)\n self.assertIn(DEVICE1_SERIAL, self.device_collection._serial_map)\n device_obj_from_id = self.device_collection._id_map[DEVICE1_ID]\n device_obj_from_serial = self.device_collection._serial_map[DEVICE1_SERIAL]\n self.assertIs(device_obj_from_id, device_obj_from_serial)\n", "method_code": " def add(self, device_id, device_serial, device_dbus):\n \"\"\"\n Add device to collection\n \n :param device_id: Device's USB ID\n :type device_id: str\n \n :param device_serial: Device's Serial String\n :type device_serial: str\n \n :param device_dbus: Device's DBus object\n :type device_dbus: openrazer_daemon.hardware.device_base.__RazerDevice\n \"\"\"\n device_object = Device(device_id, device_serial, device_dbus)\n device_object.register_parent(self)\n self._id_map[device_id] = device_object\n self._serial_map[device_serial] = device_object\n ", "context": "class DeviceCollection(object):\n def add(self, device_id, device_serial, device_dbus): ...\n def __init__(self): ...\n def remove(self, key): ...\n def get(self, item): ...\n def id_items(self): ...\n def serial_items(self): ...\n def serials(self): ...\n def __len__(self): ...\n def __getitem__(self, item): ...\n def __delitem__(self, key): ...\n def __contains__(self, item): ...\n def __iter__(self): ...\n def devices(self): ...\n def notify(self, active_child, msg): ...\n\n self._id_map = {}\n self._serial_map = {}\n", "repository": "openrazer/openrazer", "test_name": "test_add", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000457.py"} {"focal_file": "daemon/openrazer_daemon/device.py", "focal_class": null, "focal_method": "get", "tests": "import unittest\n\nclass Test_get(unittest.TestCase):\n def test_invalid_get(self):\n try:\n device = self.device_collection.get('INVALID')\n except IndexError:\n pass\n", "method_code": " def get(self, item):\n \"\"\"\n Get device object by ID or serial\n \n :param item: ID or serial\n :type item: str\n \n :return: Device object\n :rtype: Device\n \n :raises IndexError: If item not found\n \"\"\"\n return self.__getitem__(item)\n ", "context": "class DeviceCollection(object):\n def get(self, item): ...\n def __init__(self): ...\n def add(self, device_id, device_serial, device_dbus): ...\n def remove(self, key): ...\n def id_items(self): ...\n def serial_items(self): ...\n def serials(self): ...\n def __len__(self): ...\n def __getitem__(self, item): ...\n def __delitem__(self, key): ...\n def __contains__(self, item): ...\n def __iter__(self): ...\n def devices(self): ...\n def notify(self, active_child, msg): ...\n\n self._id_map = {}\n self._serial_map = {}\n", "repository": "openrazer/openrazer", "test_name": "test_invalid_get", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "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_000458.py"} {"focal_file": "daemon/openrazer_daemon/device.py", "focal_class": null, "focal_method": "remove", "tests": "import unittest\n\nclass Test_remove(unittest.TestCase):\n def test_remove(self):\n dbus_object = DummyDBusObject()\n self.device_collection.add(DEVICE1_ID, DEVICE1_SERIAL, dbus_object)\n self.assertIn(DEVICE1_ID, self.device_collection)\n self.device_collection.remove(DEVICE1_ID)\n self.assertNotIn(DEVICE1_ID, self.device_collection)\n self.device_collection.add(DEVICE1_ID, DEVICE1_SERIAL, dbus_object)\n self.assertIn(DEVICE1_ID, self.device_collection)\n self.device_collection.remove(DEVICE1_SERIAL)\n self.assertNotIn(DEVICE1_SERIAL, self.device_collection)\n", "method_code": " def remove(self, key):\n \"\"\"\n Remove object being referenced to by ident from collection\n \n :param key: ID or serial\n :type key: str\n \"\"\"\n self.__delitem__(key)\n ", "context": "class DeviceCollection(object):\n def remove(self, key): ...\n def __init__(self): ...\n def add(self, device_id, device_serial, device_dbus): ...\n def get(self, item): ...\n def id_items(self): ...\n def serial_items(self): ...\n def serials(self): ...\n def __len__(self): ...\n def __getitem__(self, item): ...\n def __delitem__(self, key): ...\n def __contains__(self, item): ...\n def __iter__(self): ...\n def devices(self): ...\n def notify(self, active_child, msg): ...\n\n self._id_map = {}\n self._serial_map = {}\n", "repository": "openrazer/openrazer", "test_name": "test_remove", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0], "smell_labels": ["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_000459.py"} {"focal_file": "daemon/openrazer_daemon/device.py", "focal_class": null, "focal_method": "serials", "tests": "import unittest\n\nclass Test_serials(unittest.TestCase):\n def test_serials(self):\n dbus_object1 = DummyDBusObject()\n dbus_object2 = DummyDBusObject()\n self.device_collection.add(DEVICE1_ID, DEVICE1_SERIAL, dbus_object1)\n self.device_collection.add(DEVICE2_ID, DEVICE2_SERIAL, dbus_object2)\n serials = self.device_collection.serials()\n self.assertIn(DEVICE1_SERIAL, serials)\n self.assertIn(DEVICE2_SERIAL, serials)\n", "method_code": " def serials(self):\n \"\"\"\n Get list of serials\n \n :return: Serial list\n :rtype: list of str\n \"\"\"\n return list(self._serial_map.keys())\n ", "context": "class DeviceCollection(object):\n def serials(self): ...\n def __init__(self): ...\n def add(self, device_id, device_serial, device_dbus): ...\n def remove(self, key): ...\n def get(self, item): ...\n def id_items(self): ...\n def serial_items(self): ...\n def __len__(self): ...\n def __getitem__(self, item): ...\n def __delitem__(self, key): ...\n def __contains__(self, item): ...\n def __iter__(self): ...\n def devices(self): ...\n def notify(self, active_child, msg): ...\n\n self._id_map = {}\n self._serial_map = {}\n", "repository": "openrazer/openrazer", "test_name": "test_serials", "smells": [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0], "smell_labels": ["AssertionRoulette", "ConditionalTestLogic", "ConstructorInitialization", "DefaultTest", "DuplicateAssertion", "EmptyTest", "ExceptionHandling", "GeneralFixture", "IgnoredTest", "LackCohesion", "MagicNumberTest", "ObscureInLineSetup", "RedundantAssertion", "RedundantPrint", "SleepyTest", "SuboptimalAssert", "TestMaverick", "UnknownTest"], "smells_isolated": [1, 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": "core/qm/qm.py", "focal_class": "QM", "focal_method": "to_binary", "tests": "import unittest\n\nclass Test_QM_to_binary(unittest.TestCase):\n def test_convert_binary(self):\n minterms = [1, 2, 3, 4, 5, 6, 15]\n qm = QM(minterms)\n conversion = qm.to_binary(minterms)\n expected_conversion = ['0001', '0010', '0011', '0100', '0101', '0110', '1111']\n self.assertEqual(conversion, expected_conversion)\n\n def test_length_convert_to_binary(self):\n minterms = [1, 2, 3, 4, 5, 6, 15]\n qm = QM(minterms)\n conversion = qm.to_binary(minterms)\n for term in conversion:\n self.assertEqual(len(term), 4)\n", "method_code": " def to_binary(self, minterms=[], nbits=0):\n \"\"\"\n Converts every element in minterms to its binary representation.\n \n Args:\n minterms: A list of minterms.\n nbits: is the the number of bits to be used for the representation\n if not specided the value defaults to the len of longest \n binary string in list \n \n Returns:\n A list containing the binary represenation of each minterm in minterms\n Each binary string nbits long\n \n Example:\n if minterms[]\n \"\"\"\n if nbits:\n mx = nbits\n else:\n mx = self.nbits\n bminterms = []\n for minterm in minterms:\n bstr = bin(minterm)[2:]\n bstr = (mx - len(bstr)) * '0' + bstr\n bminterms.append(bstr)\n return bminterms\n ", "context": "class QM():\n def to_binary(self, minterms=[], nbits=0): ...\n def __init__(self, minterms, dcares=[], chars=[]): ...\n def combine(self, min1, min2): ...\n def combine_groups(self, group1=[], group2=[]): ...\n def combine_generation(self, generation=[]): ...\n def group_minterms(self, mts=[]): ...\n def pis(self): ...\n def can_cover(self, pi, minterm): ...\n def primary_epis(self): ...\n def secondary_epis(self): ...\n def minimize(self): ...\n def to_char(self, term, chars): ...\n\n self.procedure = ''\n self.nbits = len(bin(max(minterms + dcares))[2:])\n self.minterms = self.to_binary(minterms)\n self.prime_implicants = []\n self.combined = []\n self.essential_prime_implicants = []\n self.coverage_table = {}\n self.chars = sorted(chars)\n", "repository": "Kumbong/quine_mccluskey", "test_name": "test_convert_binary", "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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000461.py"} {"focal_file": "core/qm/qm.py", "focal_class": "QM", "focal_method": "combine_groups", "tests": "import unittest\n\nclass Test_QM_combine_groups(unittest.TestCase):\n def test_combine_groups(self):\n minterms = [1, 2, 3, 4, 5, 6, 15]\n qm = QM(minterms)\n self.assertEqual(qm.combine_groups(['0001', '1000'], ['0011', '1001', '1100']), ['00_1', '_001', '100_', '1_00'])\n self.assertEqual(qm.combine_groups(['0000'], ['0001', '1000']), ['000_', '_000'])\n self.assertEqual(qm.combine_groups([], ['0001', '1000']), [])\n self.assertEqual(qm.combine_groups([], []), [])\n", "method_code": " def combine_groups(self, group1=[], group2=[]):\n \"\"\"\n Combines the in minterms in two groups of minterms.\n \n Args:\n group1: First group of minterms.\n group2: Second group of minterms.\n \n \n Returns:\n A dictionary {'combined': [], 'uncombined': []}\n uncombined are the minterms in the first group that failed to combine\n offspring are the results of the combination of the minterms in the first and second group\n \n \"\"\"\n result = []\n for mt1 in group1:\n has_combined = False\n for mt2 in group2:\n offspring = self.combine(mt1, mt2)\n if offspring:\n has_combined = True\n self.combined.append(mt1)\n self.combined.append(mt2)\n if offspring not in result:\n result.append(offspring)\n return result\n ", "context": "class QM():\n def combine_groups(self, group1=[], group2=[]): ...\n def __init__(self, minterms, dcares=[], chars=[]): ...\n def to_binary(self, minterms=[], nbits=0): ...\n def combine(self, min1, min2): ...\n def combine_generation(self, generation=[]): ...\n def group_minterms(self, mts=[]): ...\n def pis(self): ...\n def can_cover(self, pi, minterm): ...\n def primary_epis(self): ...\n def secondary_epis(self): ...\n def minimize(self): ...\n def to_char(self, term, chars): ...\n\n self.procedure = ''\n self.nbits = len(bin(max(minterms + dcares))[2:])\n self.minterms = self.to_binary(minterms)\n self.prime_implicants = []\n self.combined = []\n self.essential_prime_implicants = []\n self.coverage_table = {}\n self.chars = sorted(chars)\n", "repository": "Kumbong/quine_mccluskey", "test_name": "test_combine_groups", "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_000462.py"} {"focal_file": "core/qm/qm.py", "focal_class": "QM", "focal_method": "combine_generation", "tests": "import unittest\n\nclass Test_QM_combine_generation(unittest.TestCase):\n def test_combine_generation_no_dash(self):\n minterms = [1, 2, 3, 4, 5, 6, 15]\n qm = QM(minterms)\n self.assertEqual(qm.combine_generation([['0000'], ['0001', '1000'], ['0011', '1001', '1100'], ['0111', '1011'], ['1111']]), [['000_', '_000'], ['00_1', '_001', '100_', '1_00'], ['0_11', '_011', '10_1'], ['_111', '1_11']])\n\n def test_combine_generation_dash(self):\n minterms = [1, 2, 3, 4, 5, 6, 15]\n qm = QM(minterms)\n self.assertEqual(qm.combine_generation([['000_', '_000'], ['00_1', '_001', '100_', '1_00'], ['0_11', '_011', '10_1'], ['_111', '1_11']]), [['_00_'], ['_0_1'], ['__11']])\n\n def test_combine_generation_no_new_generation(self):\n minterms = [1, 2, 3, 4, 5, 6, 15]\n qm = QM(minterms)\n self.assertEqual(qm.combine_generation([['_00_'], ['_0_1'], ['__11']]), [])\n\n def test_combine_generation_empty_generation(self):\n minterms = [1, 2, 3, 4, 5, 6, 15]\n qm = QM(minterms)\n self.assertEqual(qm.combine_generation([]), [])\n\n def test_combine_generation_wrong(self):\n minterms = [1, 2, 3, 4, 5, 6, 15]\n qm = QM(minterms)\n self.assertNotEqual(qm.combine_generation([['_00_'], ['_0_1'], ['__11']]), [['____']])\n", "method_code": " def combine_generation(self, generation=[]):\n \"\"\"\n Combines the groups in each generation.\n \n Args:\n generation: A collection [] of groups to be combined\n \n \n Returns:\n A new generation [] of groups \n \n \"\"\"\n new_gen = []\n for i in range(len(generation) - 1):\n new_group = self.combine_groups(generation[i], generation[i + 1])\n if new_group:\n new_gen.append(new_group)\n return new_gen\n ", "context": "class QM():\n def combine_generation(self, generation=[]): ...\n def __init__(self, minterms, dcares=[], chars=[]): ...\n def to_binary(self, minterms=[], nbits=0): ...\n def combine(self, min1, min2): ...\n def combine_groups(self, group1=[], group2=[]): ...\n def group_minterms(self, mts=[]): ...\n def pis(self): ...\n def can_cover(self, pi, minterm): ...\n def primary_epis(self): ...\n def secondary_epis(self): ...\n def minimize(self): ...\n def to_char(self, term, chars): ...\n\n self.procedure = ''\n self.nbits = len(bin(max(minterms + dcares))[2:])\n self.minterms = self.to_binary(minterms)\n self.prime_implicants = []\n self.combined = []\n self.essential_prime_implicants = []\n self.coverage_table = {}\n self.chars = sorted(chars)\n", "repository": "Kumbong/quine_mccluskey", "test_name": "test_combine_generation_no_dash", "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_000463.py"} {"focal_file": "core/qm/qm.py", "focal_class": "QM", "focal_method": "group_minterms", "tests": "import unittest\n\nclass Test_QM_group_minterms(unittest.TestCase):\n def test_group_minterms(self):\n minterms = [1, 2, 3, 4, 5, 6, 15]\n qm = QM(minterms)\n self.assertEqual(qm.group_minterms(['0000', '0001', '0010', '0100', '0011', '0101', '1111']), [['0000'], ['0001', '0010', '0100'], ['0011', '0101'], ['1111']])\n", "method_code": " def group_minterms(self, mts=[]):\n \"\"\"\n Groups the elements in minterms according to the number of ones in their binary representation.\n \n Args:\n minterms: A non empty list of minterms in binary form.\n \n Returns:\n A dictionary of minterms where each key represents the number of ones present in the binary\n representation and each value is a list of minterms with an equal number of ones in their \n binary representation\n \n Raises:\n \"\"\"\n mts.sort()\n grps = []\n num_groups = len(mts[0])\n table_data = [[Color('{autogreen}Group{/autogreen}'), Color('{autogreen}Minterms (decimal){/autogreen}'), Color('{autogreen}Minterms (binary){/autogreen}')]]\n table = AsciiTable(table_data)\n table.inner_row_border = True\n self.procedure += Color('{autoblue}==========================\\nStep 1 : Grouping Minterms\\n==========================\\n{/autoblue}\\n')\n for i in range(num_groups + 1):\n grp = [x for x in mts if x.count('1') == i]\n if grp:\n grps.append(grp)\n for i in range(len(grps)):\n num_ones = grps[i][0].count('1')\n grp = grps[i]\n table_data.append([num_ones, str(int(grp[0], 2)), grp[0]])\n for j in range(1, len(grp)):\n table.table_data[i + 1][1] += '\\n' + str(int(grp[j], 2))\n table.table_data[i + 1][2] += '\\n' + grp[j]\n self.procedure += str(table.table)\n return grps\n ", "context": "class QM():\n def group_minterms(self, mts=[]): ...\n def __init__(self, minterms, dcares=[], chars=[]): ...\n def to_binary(self, minterms=[], nbits=0): ...\n def combine(self, min1, min2): ...\n def combine_groups(self, group1=[], group2=[]): ...\n def combine_generation(self, generation=[]): ...\n def pis(self): ...\n def can_cover(self, pi, minterm): ...\n def primary_epis(self): ...\n def secondary_epis(self): ...\n def minimize(self): ...\n def to_char(self, term, chars): ...\n\n self.procedure = ''\n self.nbits = len(bin(max(minterms + dcares))[2:])\n self.minterms = self.to_binary(minterms)\n self.prime_implicants = []\n self.combined = []\n self.essential_prime_implicants = []\n self.coverage_table = {}\n self.chars = sorted(chars)\n", "repository": "Kumbong/quine_mccluskey", "test_name": "test_group_minterms", "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_000464.py"} {"focal_file": "core/qm/qm.py", "focal_class": "QM", "focal_method": "pis", "tests": "import unittest\n\nclass Test_QM_pis(unittest.TestCase):\n def test_pis(self):\n minterms = [1, 2, 3, 4, 5, 6, 15]\n qm = QM(minterms)\n self.assertEqual(qm.pis(), ['1111', '00_1', '0_01', '001_', '0_10', '010_', '01_0'])\n", "method_code": " def pis(self):\n \"\"\"\n Computes the prime implicants based on the minterms and dont cares\n \n Returns:\n A list containing the prime implicants \n \"\"\"\n mts = self.minterms + self.dont_cares\n new_gen = self.group_minterms(mts)\n all_gens = [new_gen]\n while new_gen:\n for group in new_gen:\n for term in group:\n self.prime_implicants.append(term)\n new_gen = self.combine_generation(new_gen)\n if new_gen:\n all_gens.append(new_gen)\n self.prime_implicants = [pi for pi in self.prime_implicants if pi not in self.combined]\n table_data = [[]]\n for gen in all_gens:\n i = all_gens.index(gen)\n table_data[0].append(Color('{autogreen} Stage ' + str(i) + '{/autogreen}'))\n for gen in all_gens:\n i = all_gens.index(gen)\n for grp in gen:\n j = gen.index(grp)\n if i == 0:\n temp = ['' for x in table_data[0]]\n table_data.append(temp)\n for mt in grp:\n table_data[j + 1][i] += str(mt) + ' '\n if mt in self.combined:\n table_data[j + 1][i] += Color('{autocyan} ' + u'✓' + '{/autocyan}')\n else:\n table_data[j + 1][i] += Color('{autored} ' + '*' + '{/autored}')\n table_data[j + 1][i] += '\\n'\n table = AsciiTable(table_data)\n table.inner_row_border = True\n self.procedure += Color('\\n\\n{autoblue}===========================\\nStep 2 : Combining Minterms\\n===========================\\n{/autoblue}\\n')\n self.procedure += table.table\n self.procedure += Color('\\n\\n{autoblue} Prime Implicants {/autoblue}\\n ----------------\\n')\n for pi in self.prime_implicants:\n ch = ' (' + self.to_char(pi, self.chars) + ') ' if self.chars else ''\n self.procedure += ' ' + pi + ch + '\\n'\n return self.prime_implicants\n ", "context": "class QM():\n def pis(self): ...\n def __init__(self, minterms, dcares=[], chars=[]): ...\n def to_binary(self, minterms=[], nbits=0): ...\n def combine(self, min1, min2): ...\n def combine_groups(self, group1=[], group2=[]): ...\n def combine_generation(self, generation=[]): ...\n def group_minterms(self, mts=[]): ...\n def can_cover(self, pi, minterm): ...\n def primary_epis(self): ...\n def secondary_epis(self): ...\n def minimize(self): ...\n def to_char(self, term, chars): ...\n\n self.procedure = ''\n self.nbits = len(bin(max(minterms + dcares))[2:])\n self.minterms = self.to_binary(minterms)\n self.prime_implicants = []\n self.combined = []\n self.essential_prime_implicants = []\n self.coverage_table = {}\n self.chars = sorted(chars)\n", "repository": "Kumbong/quine_mccluskey", "test_name": "test_pis", "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_000465.py"} {"focal_file": "core/qm/qm.py", "focal_class": "QM", "focal_method": "can_cover", "tests": "import unittest\n\nclass Test_QM_can_cover(unittest.TestCase):\n def test_can_cover(self):\n minterms = [1, 2, 3, 4, 5, 6, 15]\n qm = QM(minterms)\n self.assertTrue(qm.can_cover('_00_', '0000'))\n self.assertTrue(qm.can_cover('_00_', '1001'))\n self.assertFalse(qm.can_cover('_11_', '0000'))\n self.assertFalse(qm.can_cover('_00_', '0110'))\n", "method_code": " def can_cover(self, pi, minterm):\n \"\"\"\n Checks if a prime implicant (pi) can cover the minterm\n \n Args:\n pi: A binary string representing the prime implicant\n minterm: A binary string representing the minterm in question\n \n Returns:\n True if the prime implicant can cover the minterm and false if otherwise\n Raises:\n \"\"\"\n pos = [i for i in range(len(pi)) if pi[i] == '_']\n for i in range(len(pi)):\n if i not in pos and pi[i] != minterm[i]:\n return False\n return True\n ", "context": "class QM():\n def can_cover(self, pi, minterm): ...\n def __init__(self, minterms, dcares=[], chars=[]): ...\n def to_binary(self, minterms=[], nbits=0): ...\n def combine(self, min1, min2): ...\n def combine_groups(self, group1=[], group2=[]): ...\n def combine_generation(self, generation=[]): ...\n def group_minterms(self, mts=[]): ...\n def pis(self): ...\n def primary_epis(self): ...\n def secondary_epis(self): ...\n def minimize(self): ...\n def to_char(self, term, chars): ...\n\n self.procedure = ''\n self.nbits = len(bin(max(minterms + dcares))[2:])\n self.minterms = self.to_binary(minterms)\n self.prime_implicants = []\n self.combined = []\n self.essential_prime_implicants = []\n self.coverage_table = {}\n self.chars = sorted(chars)\n", "repository": "Kumbong/quine_mccluskey", "test_name": "test_can_cover", "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_000466.py"} {"focal_file": "core/qm/qm.py", "focal_class": "QM", "focal_method": "primary_epis", "tests": "import unittest\n\nclass Test_QM_primary_epis(unittest.TestCase):\n def test_primary_epis(self):\n minterms = [1, 2, 3, 4, 5, 6, 9, 11, 15]\n qm = QM(minterms)\n self.assertEqual(qm.primary_epis(), [])\n", "method_code": " def primary_epis(self):\n \"\"\"\n Computes the essential prime implicants based on the minterms and dont cares\n \n Returns:\n A list containing the essential prime implicants \n \"\"\"\n for minterm in self.minterms:\n self.coverage_table[minterm] = []\n for pi in self.prime_implicants:\n if self.can_cover(pi, minterm):\n self.coverage_table[minterm].append(pi)\n table_data = [[''] + [Color('{autogreen}' + str(int(x, 2)) + '{/autogreen}') for x in self.minterms]]\n for pi in self.prime_implicants:\n table_data.append([pi] + ['' for x in self.minterms])\n for mt in self.minterms:\n if pi in self.coverage_table[mt]:\n table_data[self.prime_implicants.index(pi) + 1][self.minterms.index(mt) + 1] = 'X'\n if len(self.coverage_table[mt]) == 1:\n table_data[self.prime_implicants.index(pi) + 1][self.minterms.index(mt) + 1] = Color('{autored}X{/autored}')\n table_data.append([''] + ['' for x in self.minterms])\n for minterm in self.minterms:\n if len(self.coverage_table[minterm]) == 1:\n self.essential_prime_implicants.append(self.coverage_table[minterm][0])\n for minterm in self.minterms:\n if set(self.coverage_table[minterm]).intersection(set(self.essential_prime_implicants)):\n table_data[-1][self.minterms.index(minterm) + 1] = Color('{autocyan} ' + u'✓' + '{/autocyan}')\n self.essential_prime_implicants = list(set(self.essential_prime_implicants))\n self.coverage_table = {k: v for k, v in self.coverage_table.items() if not set(v).intersection(set(self.essential_prime_implicants))}\n table = AsciiTable(table_data)\n table.inner_row_border = True\n self.procedure += Color('\\n\\n{autoblue}=======================\\nStep 3 : Coverage Chart\\n=======================\\n{/autoblue}\\n')\n self.procedure += table.table\n if self.essential_prime_implicants:\n self.procedure += Color('\\n\\n{autoblue} Primary Essential Prime Implicants {/autoblue}\\n ----------------------------------\\n')\n for pi in self.essential_prime_implicants:\n ch = ' (' + self.to_char(pi, self.chars) + ') ' if self.chars else ''\n self.procedure += ' ' + pi + ch + '\\n'\n return self.essential_prime_implicants\n ", "context": "class QM():\n def primary_epis(self): ...\n def __init__(self, minterms, dcares=[], chars=[]): ...\n def to_binary(self, minterms=[], nbits=0): ...\n def combine(self, min1, min2): ...\n def combine_groups(self, group1=[], group2=[]): ...\n def combine_generation(self, generation=[]): ...\n def group_minterms(self, mts=[]): ...\n def pis(self): ...\n def can_cover(self, pi, minterm): ...\n def secondary_epis(self): ...\n def minimize(self): ...\n def to_char(self, term, chars): ...\n\n self.procedure = ''\n self.nbits = len(bin(max(minterms + dcares))[2:])\n self.minterms = self.to_binary(minterms)\n self.prime_implicants = []\n self.combined = []\n self.essential_prime_implicants = []\n self.coverage_table = {}\n self.chars = sorted(chars)\n", "repository": "Kumbong/quine_mccluskey", "test_name": "test_primary_epis", "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_000467.py"} {"focal_file": "core/qm/qm.py", "focal_class": "QM", "focal_method": "to_char", "tests": "import unittest\n\nclass Test_QM_to_char(unittest.TestCase):\n def test_to_char(self):\n minterms = [1, 2, 3, 4, 5, 6, 9, 11, 15]\n qm = QM(minterms)\n self.assertEqual(qm.to_char('_00_', ['a', 'b', 'c', 'd']), \"b'c'\")\n self.assertEqual(qm.to_char('_11_', ['a', 'b', 'c', 'd']), 'bc')\n self.assertEqual(qm.to_char('____', ['a', 'b', 'c', 'd']), '')\n self.assertEqual(qm.to_char('0000', ['a', 'b', 'c', 'd']), \"a'b'c'd'\")\n self.assertEqual(qm.to_char('1111', ['a', 'b', 'c', 'd']), 'abcd')\n", "method_code": " def to_char(self, term, chars):\n \"\"\"\n Converts the binary term to its character representation\n \n Args:\n term : A binary string representing the prime implicant\n chars: An array containing the possible acceptable characters\n Returns:\n A string with the character represenation from the string\n \"\"\"\n i = 0\n res = ''\n for ch in term:\n if ch == '1':\n res += chars[i]\n elif ch == '0':\n res = res + chars[i] + \"'\"\n i += 1\n return res\n ", "context": "class QM():\n def to_char(self, term, chars): ...\n def __init__(self, minterms, dcares=[], chars=[]): ...\n def to_binary(self, minterms=[], nbits=0): ...\n def combine(self, min1, min2): ...\n def combine_groups(self, group1=[], group2=[]): ...\n def combine_generation(self, generation=[]): ...\n def group_minterms(self, mts=[]): ...\n def pis(self): ...\n def can_cover(self, pi, minterm): ...\n def primary_epis(self): ...\n def secondary_epis(self): ...\n def minimize(self): ...\n\n self.procedure = ''\n self.nbits = len(bin(max(minterms + dcares))[2:])\n self.minterms = self.to_binary(minterms)\n self.prime_implicants = []\n self.combined = []\n self.essential_prime_implicants = []\n self.coverage_table = {}\n self.chars = sorted(chars)\n", "repository": "Kumbong/quine_mccluskey", "test_name": "test_to_char", "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_000468.py"} {"focal_file": "core/qm/petrick.py", "focal_class": null, "focal_method": "multiply", "tests": "import unittest\n\nclass Test_multiply(unittest.TestCase):\n def test_multiply(self):\n self.assertEqual(multiply('', ''), '')\n", "method_code": "def multiply(t1, t2):\n \"\"\"\n Multiplies (expands) two binary expressions t1 and t2 based on the distributive rule\n\n Args:\n t1 (str): first binary expression\n t2 (str): second binary expression\n\n Returns:\n A string representing the expansion of the boolean algebraic expressions\n\n\n \"\"\"\n t1 = t1.split('+')\n t2 = t2.split('+')\n prod = ''\n for m in t1:\n temp = ''\n for n in t2:\n if t1.index(m) == len(t1) - 1 and t2.index(n) == len(t2) - 1:\n if m != n:\n temp = temp + m + n\n else:\n temp += m\n elif m != n:\n temp = temp + m + n + '+'\n else:\n temp += m + '+'\n prod += temp\n return prod", "context": "def multiply(t1, t2): ...\ndef multiply(t1, t2): ...\ndef remove_dups(expr): ...\ndef multiply_all(terms): ...\ndef reduce_expr(expr): ...\ndef min_len_terms(terms): ...\ndef count_literals(term): ...\ndef fewest_literals(terms): ...\n", "repository": "Kumbong/quine_mccluskey", "test_name": "test_multiply", "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_000469.py"} {"focal_file": "core/qm/petrick.py", "focal_class": null, "focal_method": "min_len_terms", "tests": "import unittest\n\nclass Test_min_len_terms(unittest.TestCase):\n def test_min_len_terms(self):\n x = ['abcd', 'abc', 'abcde', 'a', 'b']\n self.assertEqual(min_len_terms(x), ['a', 'b'])\n self.assertEqual(min_len_terms(['a']), ['a'])\n", "method_code": "def min_len_terms(terms):\n \"\"\"\n Finds the shortest term\n\n Args:\n terms: A list of terms \n\n Returns:\n The terms that have the minimum length\n\n \"\"\"\n minlen = len(min(terms, key=lambda x: len(x)))\n terms = [term for term in terms if len(term) == minlen]\n return terms", "context": "def min_len_terms(terms): ...\ndef multiply(t1, t2): ...\ndef remove_dups(expr): ...\ndef multiply_all(terms): ...\ndef reduce_expr(expr): ...\ndef min_len_terms(terms): ...\ndef count_literals(term): ...\ndef fewest_literals(terms): ...\n", "repository": "Kumbong/quine_mccluskey", "test_name": "test_min_len_terms", "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_000470.py"} {"focal_file": "core/qm/petrick.py", "focal_class": null, "focal_method": "count_literals", "tests": "import unittest\n\nclass Test_count_literals(unittest.TestCase):\n def test_count_literals(self):\n self.assertEqual(count_literals('____'), 0)\n self.assertEqual(count_literals('abcd'), 4)\n self.assertEqual(count_literals('ab__'), 2)\n", "method_code": "def count_literals(term):\n \"\"\"\n Counts the number of literals in a term\n\n Args:\n term : A string containing literals\n \n\n Returns:\n The number of literals in term\n \"\"\"\n count = 0\n for char in term:\n if char != '_':\n count += 1\n return count", "context": "def count_literals(term): ...\ndef multiply(t1, t2): ...\ndef remove_dups(expr): ...\ndef multiply_all(terms): ...\ndef reduce_expr(expr): ...\ndef min_len_terms(terms): ...\ndef count_literals(term): ...\ndef fewest_literals(terms): ...\n", "repository": "Kumbong/quine_mccluskey", "test_name": "test_count_literals", "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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000471.py"} {"focal_file": "core/qm/petrick.py", "focal_class": null, "focal_method": "fewest_literals", "tests": "import unittest\n\nclass Test_fewest_literals(unittest.TestCase):\n def test_fewest_literals(self):\n self.assertEqual(fewest_literals(['abcd', 'ab__', '__cd']), ['ab__', '__cd'])\n self.assertEqual(fewest_literals(['a_b_', 'ab__', '__cd']), ['a_b_', 'ab__', '__cd'])\n", "method_code": "def fewest_literals(terms):\n \"\"\"\n Returns the terms that contain the fewest number of literals\n\n Args:\n terms: A list of of terms \n\n Returns:\n A list of minterms with the fewest number of literals\n\n \"\"\"\n min_count = count_literals(min(terms, key=lambda x: count_literals(x)))\n min_lits = []\n for term in terms:\n if count_literals(term) == min_count:\n min_lits.append(term)\n return min_lits", "context": "def fewest_literals(terms): ...\ndef multiply(t1, t2): ...\ndef remove_dups(expr): ...\ndef multiply_all(terms): ...\ndef reduce_expr(expr): ...\ndef min_len_terms(terms): ...\ndef count_literals(term): ...\ndef fewest_literals(terms): ...\n", "repository": "Kumbong/quine_mccluskey", "test_name": "test_fewest_literals", "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_000472.py"} {"focal_file": "wikicious/libs/simplejson/__init__.py", "focal_class": null, "focal_method": "dumps", "tests": "import unittest\n\nclass Test_dumps(unittest.TestCase):\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\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", "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, **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 *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 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 bigint_as_string) and (not sort_keys) and (not item_sort_key) and (not for_json) and (not ignore_nan) 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, bigint_as_string=bigint_as_string, sort_keys=sort_keys, item_sort_key=item_sort_key, for_json=for_json, ignore_nan=ignore_nan, **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, **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, **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, **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": "daadu/wikicious", "test_name": "test_tuple_array_dumps", "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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000473.py"} {"focal_file": "wikicious/libs/simplejson/__init__.py", "focal_class": null, "focal_method": "dump", "tests": "import unittest\n\nclass Test_dump(unittest.TestCase):\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\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", "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, **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 *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 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 bigint_as_string) and (not item_sort_key) and (not for_json) and (not ignore_nan) 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, bigint_as_string=bigint_as_string, sort_keys=sort_keys, item_sort_key=item_sort_key, for_json=for_json, ignore_nan=ignore_nan, **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, **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, **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, **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": "daadu/wikicious", "test_name": "test_tuple_array_dump", "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, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000474.py"} {"focal_file": "pythonstory/world/packets.py", "focal_class": null, "focal_method": "charlist", "tests": "import unittest\n\nclass Test_charlist(unittest.TestCase):\n def test_charlist(self):\n self.assertEqual(type(self.account), Account)\n packet = charlist(self.account)\n self.assertEqual(len(packet), 9)\n", "method_code": "def charlist(builder, account):\n builder.write(0)\n characters = account.characters\n builder.write(characters.count())\n for character in characters:\n packethelpers.add_character_entry(builder, character)\n builder.write(2).write_int(account.character_slots)\n return builder.get_packet()", "context": "@packet(sendopcodes.CHARLIST)\ndef charlist(builder, account): ...\ndef auth_success(builder, client): ...\ndef auth_failed(builder, reason): ...\ndef serverlist(builder, world): ...\ndef end_of_serverlist(builder): ...\ndef select_world(builder, worldid): ...\ndef recommended_worlds(builder, worlds): ...\ndef server_load(builder, load): ...\ndef charlist(builder, account): ...\ndef char_name_response(builder, name, available): ...\ndef create_character(builder, character): ...\ndef serverip(builder, ip, port, char_id): ...\n", "repository": "martolini/pythonstory", "test_name": "test_charlist", "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_000475.py"} {"focal_file": "pythonosc/dispatcher.py", "focal_class": null, "focal_method": "set_default_handler", "tests": "import unittest\n\nclass Test_set_default_handler(unittest.TestCase):\n def test_use_default_handler_when_set_and_no_match(self):\n handler = object()\n self.dispatcher.set_default_handler(handler)\n self.sortAndAssertSequenceEqual([dispatcher.Handler(handler, [])], self.dispatcher.handlers_for_address('/test'))\n", "method_code": " def set_default_handler(self, handler):\n \"\"\"Sets the default handler.\n \n Must be a function with the same constaints as with the self.map method\n or None to unset the default handler.\n \"\"\"\n self._default_handler = handler\n ", "context": "class Dispatcher(object):\n def set_default_handler(self, handler): ...\n def __init__(self): ...\n def map(self, address, handler, *args): ...\n def handlers_for_address(self, address_pattern): ...\n\n self._map = collections.defaultdict(list)\n self._default_handler = None\n", "repository": "vetriselvi/ptTechTouch", "test_name": "test_use_default_handler_when_set_and_no_match", "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_000476.py"} {"focal_file": "pythonosc/dispatcher.py", "focal_class": null, "focal_method": "map", "tests": "import unittest\n\nclass Test_map(unittest.TestCase):\n def test_multiple_handlers_with_wildcard_map(self):\n self.dispatcher.map('/foo/bar', 1)\n self.dispatcher.map('/*', 2)\n self.sortAndAssertSequenceEqual([dispatcher.Handler(1, []), dispatcher.Handler(2, [])], self.dispatcher.handlers_for_address('/foo/bar'))\n", "method_code": " def map(self, address, handler, *args):\n \"\"\"Map a given address to a handler.\n \n Args:\n - address: An explicit endpoint.\n - handler: A function that will be run when the address matches with\n the OscMessage passed as parameter.\n - args: Any additional arguments that will be always passed to the\n handlers after the osc messages arguments if any.\n \"\"\"\n self._map[address].append(Handler(handler, list(args)))\n ", "context": "class Dispatcher(object):\n def map(self, address, handler, *args): ...\n def __init__(self): ...\n def handlers_for_address(self, address_pattern): ...\n def set_default_handler(self, handler): ...\n\n self._map = collections.defaultdict(list)\n self._default_handler = None\n", "repository": "vetriselvi/ptTechTouch", "test_name": "test_multiple_handlers_with_wildcard_map", "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_000477.py"} {"focal_file": "pythonosc/osc_bundle.py", "focal_class": null, "focal_method": "dgram_is_bundle", "tests": "import unittest\n\nclass Test_dgram_is_bundle(unittest.TestCase):\n def test_dgram_is_bundle(self):\n self.assertTrue(osc_bundle.OscBundle.dgram_is_bundle(_DGRAM_SWITCH_GOES_ON))\n self.assertFalse(osc_bundle.OscBundle.dgram_is_bundle(b'junk'))\n", "method_code": " def dgram_is_bundle(dgram):\n \"\"\"Returns whether this datagram starts like an OSC bundle.\"\"\"\n return dgram.startswith(_BUNDLE_PREFIX)\n ", "context": "class OscBundle(object):\n @staticmethod\n def dgram_is_bundle(dgram): ...\n def __init__(self, dgram): ...\n def _parse_contents(self, index): ...\n def timestamp(self): ...\n def num_contents(self): ...\n def size(self): ...\n def dgram(self): ...\n def content(self, index): ...\n def __iter__(self): ...\n\n self._dgram = dgram\n self._contents = self._parse_contents(index)\n", "repository": "vetriselvi/ptTechTouch", "test_name": "test_dgram_is_bundle", "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_000478.py"} {"focal_file": "pythonosc/osc_server.py", "focal_class": null, "focal_method": "_is_valid_request", "tests": "import unittest\n\nclass Test_is_valid_request(unittest.TestCase):\n def test_is_valid_request(self):\n self.assertTrue(osc_server._is_valid_request([b'#bundle\\x00foobar']))\n self.assertTrue(osc_server._is_valid_request([b'/address/1/2/3,foobar']))\n self.assertFalse(osc_server._is_valid_request([b'']))\n", "method_code": "def _is_valid_request(request):\n \"\"\"Returns true if the request's data looks like an osc bundle or message.\"\"\"\n data = request[0]\n return osc_bundle.OscBundle.dgram_is_bundle(data) or osc_message.OscMessage.dgram_is_message(data)", "context": "def _is_valid_request(request): ...\ndef _call_handlers_for_packet(data, dispatcher): ...\ndef _is_valid_request(request): ...\n", "repository": "vetriselvi/ptTechTouch", "test_name": "test_is_valid_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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000479.py"} {"focal_file": "pythonosc/udp_client.py", "focal_class": "pythonosc.udp_client.UDPClient", "focal_method": "send", "tests": "import unittest\n\nclass Test_pythonosc_udp_client_UDPClient_send(unittest.TestCase):\n @mock.patch('socket.socket')\n def test_send(self, mock_socket_ctor):\n mock_socket = mock_socket_ctor.return_value\n client = udp_client.UDPClient('::1', 31337)\n msg = osc_message_builder.OscMessageBuilder('/').build()\n client.send(msg)\n self.assertTrue(mock_socket.sendto.called)\n mock_socket.sendto.assert_called_once_with(msg.dgram, ('::1', 31337))\n", "method_code": " def send(self, content):\n \"\"\"Sends an OscBundle or OscMessage to the server.\"\"\"\n self._sock.sendto(content.dgram, (self._address, self._port))\n ", "context": "class UDPClient(object):\n def send(self, content): ...\n def __init__(self, address, port): ...\n\n self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n self._address = address\n self._port = port\n", "repository": "vetriselvi/ptTechTouch", "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_000480.py"} {"focal_file": "pythonosc/parsing/ntp.py", "focal_class": null, "focal_method": "ntp_to_system_time", "tests": "import unittest\n\nclass Test_ntp_to_system_time(unittest.TestCase):\n def test_nto_to_system_time(self):\n self.assertGreater(0, ntp.ntp_to_system_time(0))\n", "method_code": "def ntp_to_system_time(date):\n \"\"\"Convert a NTP time to system time.\n\n System time is reprensented by seconds since the epoch in UTC.\n \"\"\"\n return date - _NTP_DELTA", "context": "def ntp_to_system_time(date): ...\ndef ntp_to_system_time(date): ...\ndef system_time_to_ntp(date): ...\n", "repository": "vetriselvi/ptTechTouch", "test_name": "test_nto_to_system_time", "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_000481.py"} {"focal_file": "pythonosc/parsing/ntp.py", "focal_class": null, "focal_method": "system_time_to_ntp", "tests": "import unittest\n\nclass Test_system_time_to_ntp(unittest.TestCase):\n def test_system_time_to_ntp(self):\n self.assertTrue(ntp.system_time_to_ntp(0.0))\n", "method_code": "def system_time_to_ntp(date):\n \"\"\"Convert a system time to a NTP time datagram.\n\n System time is reprensented by seconds since the epoch in UTC.\n \"\"\"\n try:\n ntp = date + _NTP_DELTA\n except TypeError as ve:\n raise NtpError('Invalud date: {}'.format(ve))\n num_secs, fraction = str(ntp).split('.')\n return struct.pack('>I', int(num_secs)) + struct.pack('>I', int(fraction))", "context": "def system_time_to_ntp(date): ...\ndef ntp_to_system_time(date): ...\ndef system_time_to_ntp(date): ...\n", "repository": "vetriselvi/ptTechTouch", "test_name": "test_system_time_to_ntp", "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_000482.py"} {"focal_file": "pythonosc/parsing/osc_types.py", "focal_class": null, "focal_method": "get_string", "tests": "import unittest\n\nclass Test_get_string(unittest.TestCase):\n def test_get_string(self):\n cases = {b'A\\x00\\x00\\x00': ('A', 4), b'AB\\x00\\x00': ('AB', 4), b'ABC\\x00': ('ABC', 4), b'ABCD\\x00\\x00\\x00\\x00': ('ABCD', 8), b'ABCD\\x00\\x00\\x00\\x00GARBAGE': ('ABCD', 8)}\n for dgram, expected in cases.items():\n self.assertEqual(expected, osc_types.get_string(dgram, 0))\n", "method_code": "def get_string(dgram, start_index):\n \"\"\"Get a python string from the datagram, starting at pos start_index.\n\n According to the specifications, a string is:\n \"A sequence of non-null ASCII characters followed by a null,\n followed by 0-3 additional null characters to make the total number\n of bits a multiple of 32\".\n\n Args:\n dgram: A datagram packet.\n start_index: An index where the string starts in the datagram.\n\n Returns:\n A tuple containing the string and the new end index.\n\n Raises:\n ParseError if the datagram could not be parsed.\n \"\"\"\n offset = 0\n try:\n while dgram[start_index + offset] != 0:\n offset += 1\n if offset == 0:\n raise ParseError('OSC string cannot begin with a null byte: %s' % dgram[start_index:])\n if offset % _STRING_DGRAM_PAD == 0:\n offset += _STRING_DGRAM_PAD\n else:\n offset += -offset % _STRING_DGRAM_PAD\n if offset > len(dgram[start_index:]):\n raise ParseError('Datagram is too short')\n data_str = dgram[start_index:start_index + offset]\n return (data_str.replace(b'\\x00', b'').decode('utf-8'), start_index + offset)\n except IndexError as ie:\n raise ParseError('Could not parse datagram %s' % ie)\n except TypeError as te:\n raise ParseError('Could not parse datagram %s' % te)", "context": "def get_string(dgram, start_index): ...\ndef write_string(val): ...\ndef get_string(dgram, start_index): ...\ndef write_int(val): ...\ndef get_int(dgram, start_index): ...\ndef write_float(val): ...\ndef get_float(dgram, start_index): ...\ndef get_blob(dgram, start_index): ...\ndef write_blob(val): ...\ndef get_date(dgram, start_index): ...\ndef write_date(system_time): ...\n", "repository": "vetriselvi/ptTechTouch", "test_name": "test_get_string", "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_000483.py"} {"focal_file": "pythonosc/parsing/osc_types.py", "focal_class": null, "focal_method": "get_float", "tests": "import unittest\n\nclass Test_get_float(unittest.TestCase):\n def test_get_float(self):\n cases = {b'\\x00\\x00\\x00\\x00': (0.0, 4), b\"?\\x80\\x00\\x00'\": (1.0, 4), b'@\\x00\\x00\\x00': (2.0, 4), b'\\x00\\x00\\x00\\x00GARBAGE': (0.0, 4)}\n for dgram, expected in cases.items():\n self.assertAlmostEqual(expected, osc_types.get_float(dgram, 0))\n", "method_code": "def get_float(dgram, start_index):\n \"\"\"Get a 32-bit big-endian IEEE 754 floating point number from the datagram.\n\n Args:\n dgram: A datagram packet.\n start_index: An index where the float starts in the datagram.\n\n Returns:\n A tuple containing the float and the new end index.\n\n Raises:\n ParseError if the datagram could not be parsed.\n \"\"\"\n try:\n if len(dgram[start_index:]) < _FLOAT_DGRAM_LEN:\n dgram = dgram + b'\\x00' * (_FLOAT_DGRAM_LEN - len(dgram[start_index:]))\n return (struct.unpack('>f', dgram[start_index:start_index + _FLOAT_DGRAM_LEN])[0], start_index + _FLOAT_DGRAM_LEN)\n except (struct.error, TypeError) as e:\n raise ParseError('Could not parse datagram %s' % e)", "context": "def get_float(dgram, start_index): ...\ndef write_string(val): ...\ndef get_string(dgram, start_index): ...\ndef write_int(val): ...\ndef get_int(dgram, start_index): ...\ndef write_float(val): ...\ndef get_float(dgram, start_index): ...\ndef get_blob(dgram, start_index): ...\ndef write_blob(val): ...\ndef get_date(dgram, start_index): ...\ndef write_date(system_time): ...\n", "repository": "vetriselvi/ptTechTouch", "test_name": "test_get_float", "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_000484.py"} {"focal_file": "pythonosc/parsing/osc_types.py", "focal_class": null, "focal_method": "get_blob", "tests": "import unittest\n\nclass Test_get_blob(unittest.TestCase):\n def test_get_blob(self):\n cases = {b'\\x00\\x00\\x00\\x00': (b'', 4), b'\\x00\\x00\\x00\\x08stuff\\x00\\x00\\x00': (b'stuff\\x00\\x00\\x00', 12), b'\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x00': (b'\\x00\\x00\\x00\\x00', 8), b'\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x00': (b'\\x00\\x00', 8), b'\\x00\\x00\\x00\\x08stuff\\x00\\x00\\x00datagramcontinues': (b'stuff\\x00\\x00\\x00', 12)}\n for dgram, expected in cases.items():\n self.assertEqual(expected, osc_types.get_blob(dgram, 0))\n", "method_code": "def get_blob(dgram, start_index):\n \"\"\" Get a blob from the datagram.\n\n According to the specifications, a blob is made of\n \"an int32 size count, followed by that many 8-bit bytes of arbitrary\n binary data, followed by 0-3 additional zero bytes to make the total\n number of bits a multiple of 32\".\n\n Args:\n dgram: A datagram packet.\n start_index: An index where the float starts in the datagram.\n\n Returns:\n A tuple containing the blob and the new end index.\n\n Raises:\n ParseError if the datagram could not be parsed.\n \"\"\"\n size, int_offset = get_int(dgram, start_index)\n total_size = size + -size % _BLOB_DGRAM_PAD\n end_index = int_offset + size\n if end_index - start_index > len(dgram[start_index:]):\n raise ParseError('Datagram is too short.')\n return (dgram[int_offset:int_offset + size], int_offset + total_size)", "context": "def get_blob(dgram, start_index): ...\ndef write_string(val): ...\ndef get_string(dgram, start_index): ...\ndef write_int(val): ...\ndef get_int(dgram, start_index): ...\ndef write_float(val): ...\ndef get_float(dgram, start_index): ...\ndef get_blob(dgram, start_index): ...\ndef write_blob(val): ...\ndef get_date(dgram, start_index): ...\ndef write_date(system_time): ...\n", "repository": "vetriselvi/ptTechTouch", "test_name": "test_get_blob", "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_000485.py"} {"focal_file": "pythonosc/parsing/osc_types.py", "focal_class": null, "focal_method": "write_date", "tests": "import unittest\n\nclass Test_write_date(unittest.TestCase):\n def test_write_date(self):\n self.assertEqual(b'\\x83\\xaa~\\x83\\x00\\x00\\x059', osc_types.write_date(3.1337))\n", "method_code": "def write_date(system_time):\n if system_time == IMMEDIATELY:\n return ntp.IMMEDIATELY\n try:\n return ntp.system_time_to_ntp(system_time)\n except ntp.NtpError as ntpe:\n raise BuildError(ntpe)", "context": "def write_date(system_time): ...\ndef write_string(val): ...\ndef get_string(dgram, start_index): ...\ndef write_int(val): ...\ndef get_int(dgram, start_index): ...\ndef write_float(val): ...\ndef get_float(dgram, start_index): ...\ndef get_blob(dgram, start_index): ...\ndef write_blob(val): ...\ndef get_date(dgram, start_index): ...\ndef write_date(system_time): ...\n", "repository": "vetriselvi/ptTechTouch", "test_name": "test_write_date", "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_000486.py"} {"focal_file": "app/ocupa2app/helpers/twitter.py", "focal_class": "Twitter", "focal_method": "get_token", "tests": "import unittest\n\nclass Test_Twitter_get_token(unittest.TestCase):\n def test_get_token(self):\n t = Twitter(self.user_id)\n token = t.get_token()\n", "method_code": " def get_token(self):\n if not self.user_id:\n raise KeyError('You must specify the user_id')\n url = Twitter.BASE_URL + 'get/key'\n d = self.get(url, {'email': self.user_id}, skip_operation=True)\n self.token = d.json()['key']\n return self.token\n ", "context": "class Twitter(APIBase):\n def get_token(self): ...\n def __init__(self, user_id, token=None): ...\n def get_posts_by_hashtag(self, hashtag): ...\n def get_post(self, tweet_id): ...\n def follow(self, user_id): ...\n def unfollow(self, user_id): ...\n def like(self, post_id): ...\n def unlike(self, post_id): ...\n\n self.token = token\n self.user_id = user_id\n self.cache = dict()\n\n BASE_URL = 'http://hackathon.ocupa2.com/twitter/1.1/'\n", "repository": "jpescalona/ocupa2", "test_name": "test_get_token", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 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_000487.py"} {"focal_file": "app/ocupa2app/helpers/twitter.py", "focal_class": null, "focal_method": "get_posts_by_hashtag", "tests": "import unittest\n\nclass Test_get_posts_by_hashtag(unittest.TestCase):\n def test_get_posts_by_hashtag(self):\n posts = self.tw.get_posts_by_hashtag('pizza')\n assert posts is not None\n", "method_code": " def get_posts_by_hashtag(self, hashtag):\n \"\"\" Returns a list of tweets \"\"\"\n url = Twitter.BASE_URL + 'search/tweets.json'\n params = {'q': hashtag}\n d = self.get(url, params)\n return d.json()\n ", "context": "class Twitter(APIBase):\n def get_posts_by_hashtag(self, hashtag): ...\n def __init__(self, user_id, token=None): ...\n def get_token(self): ...\n def get_post(self, tweet_id): ...\n def follow(self, user_id): ...\n def unfollow(self, user_id): ...\n def like(self, post_id): ...\n def unlike(self, post_id): ...\n\n self.token = token\n self.user_id = user_id\n self.cache = dict()\n\n BASE_URL = 'http://hackathon.ocupa2.com/twitter/1.1/'\n", "repository": "jpescalona/ocupa2", "test_name": "test_get_posts_by_hashtag", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 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_000488.py"} {"focal_file": "app/ocupa2app/helpers/instagram.py", "focal_class": "Instagram", "focal_method": "get_token", "tests": "import unittest\n\nclass Test_Instagram_get_token(unittest.TestCase):\n def test_get_token(self):\n i = Instagram(self.user_id)\n token = i.get_token()\n", "method_code": " def get_token(self):\n if not self.user_id:\n raise KeyError('You must specify the user_id')\n url = Instagram.BASE_URL + 'get/key'\n d = self.get(url, {'email': self.user_id}, skip_operation=True)\n self.token = d.json()['key']\n return self.token\n ", "context": "class Instagram(APIBase):\n def get_token(self): ...\n def __init__(self, user_id, token=None): ...\n def get_hashtag(self, hashtag): ...\n def get_recent_posts(self, hashtag_id): ...\n def get_top_posts(self, hashtag_id): ...\n def get_media(self, media_id): ...\n def get_user(self, user_id): ...\n def extend_posts(self, posts): ...\n def follow(self, user_id): ...\n def unfollow(self, user_id): ...\n def like(self, post_id): ...\n def unlike(self, post_id): ...\n\n self.token = token\n self.user_id = user_id\n self.hashtag_cache = dict()\n self.user_cache = dict()\n self.media_cache = dict()\n\n BASE_URL = 'http://hackathon.ocupa2.com/instagram/'\n", "repository": "jpescalona/ocupa2", "test_name": "test_get_token", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 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_000489.py"} {"focal_file": "app/ocupa2app/helpers/instagram.py", "focal_class": null, "focal_method": "get_hashtag", "tests": "import unittest\n\nclass Test_get_hashtag(unittest.TestCase):\n def test_get_hashtag(self):\n hashtag_id = self.ig.get_hashtag('porsche')\n self.assertEqual(hashtag_id, 288)\n", "method_code": " def get_hashtag(self, hashtag):\n \"\"\" Returns the ID of a hashtag \"\"\"\n if hashtag not in self.hashtag_cache:\n url = Instagram.BASE_URL + 'ig_hashtag_search'\n params = {'q': hashtag, 'user_id': self.user_id}\n d = self.get(url, params)\n j = d.json()\n if 'id' not in j:\n return None\n self.hashtag_cache[hashtag] = j['id']\n return self.hashtag_cache[hashtag]\n ", "context": "class Instagram(APIBase):\n def get_hashtag(self, hashtag): ...\n def __init__(self, user_id, token=None): ...\n def get_token(self): ...\n def get_recent_posts(self, hashtag_id): ...\n def get_top_posts(self, hashtag_id): ...\n def get_media(self, media_id): ...\n def get_user(self, user_id): ...\n def extend_posts(self, posts): ...\n def follow(self, user_id): ...\n def unfollow(self, user_id): ...\n def like(self, post_id): ...\n def unlike(self, post_id): ...\n\n self.token = token\n self.user_id = user_id\n self.hashtag_cache = dict()\n self.user_cache = dict()\n self.media_cache = dict()\n\n BASE_URL = 'http://hackathon.ocupa2.com/instagram/'\n", "repository": "jpescalona/ocupa2", "test_name": "test_get_hashtag", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000490.py"} {"focal_file": "app/ocupa2app/helpers/instagram.py", "focal_class": null, "focal_method": "get_recent_posts", "tests": "import unittest\n\nclass Test_get_recent_posts(unittest.TestCase):\n def test_get_recent_posts(self):\n posts = self.ig.get_recent_posts(21)\n assert posts is not None\n", "method_code": " def get_recent_posts(self, hashtag_id):\n url = Instagram.BASE_URL + '{id}/recent_media'.format(id=hashtag_id)\n params = {'user_id': self.user_id}\n d = self.get(url, params)\n try:\n return d.json()['data']\n except:\n return []\n ", "context": "class Instagram(APIBase):\n def get_recent_posts(self, hashtag_id): ...\n def __init__(self, user_id, token=None): ...\n def get_token(self): ...\n def get_hashtag(self, hashtag): ...\n def get_top_posts(self, hashtag_id): ...\n def get_media(self, media_id): ...\n def get_user(self, user_id): ...\n def extend_posts(self, posts): ...\n def follow(self, user_id): ...\n def unfollow(self, user_id): ...\n def like(self, post_id): ...\n def unlike(self, post_id): ...\n\n self.token = token\n self.user_id = user_id\n self.hashtag_cache = dict()\n self.user_cache = dict()\n self.media_cache = dict()\n\n BASE_URL = 'http://hackathon.ocupa2.com/instagram/'\n", "repository": "jpescalona/ocupa2", "test_name": "test_get_recent_posts", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 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_000491.py"} {"focal_file": "app/ocupa2app/helpers/instagram.py", "focal_class": null, "focal_method": "get_top_posts", "tests": "import unittest\n\nclass Test_get_top_posts(unittest.TestCase):\n def test_get_top_posts(self):\n posts = self.ig.get_top_posts(21)\n assert posts is not None\n", "method_code": " def get_top_posts(self, hashtag_id):\n url = Instagram.BASE_URL + '{id}/top_media'.format(id=hashtag_id)\n params = {'user_id': self.user_id}\n d = self.get(url, params)\n try:\n return d.json()['data']\n except:\n return []\n ", "context": "class Instagram(APIBase):\n def get_top_posts(self, hashtag_id): ...\n def __init__(self, user_id, token=None): ...\n def get_token(self): ...\n def get_hashtag(self, hashtag): ...\n def get_recent_posts(self, hashtag_id): ...\n def get_media(self, media_id): ...\n def get_user(self, user_id): ...\n def extend_posts(self, posts): ...\n def follow(self, user_id): ...\n def unfollow(self, user_id): ...\n def like(self, post_id): ...\n def unlike(self, post_id): ...\n\n self.token = token\n self.user_id = user_id\n self.hashtag_cache = dict()\n self.user_cache = dict()\n self.media_cache = dict()\n\n BASE_URL = 'http://hackathon.ocupa2.com/instagram/'\n", "repository": "jpescalona/ocupa2", "test_name": "test_get_top_posts", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 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_000492.py"} {"focal_file": "app/ocupa2app/helpers/instagram.py", "focal_class": null, "focal_method": "get_media", "tests": "import unittest\n\nclass Test_get_media(unittest.TestCase):\n def test_get_media(self):\n media = self.ig.get_media(10372)\n assert media is not None\n", "method_code": " def get_media(self, media_id):\n if media_id not in self.media_cache:\n url = Instagram.BASE_URL + 'media/{id}'.format(id=media_id)\n params = {'fields': 'id,comments_count,like_count,media_type,username'}\n d = self.get(url, params)\n self.media_cache[media_id] = d.json()[0]\n return self.media_cache[media_id]\n ", "context": "class Instagram(APIBase):\n def get_media(self, media_id): ...\n def __init__(self, user_id, token=None): ...\n def get_token(self): ...\n def get_hashtag(self, hashtag): ...\n def get_recent_posts(self, hashtag_id): ...\n def get_top_posts(self, hashtag_id): ...\n def get_user(self, user_id): ...\n def extend_posts(self, posts): ...\n def follow(self, user_id): ...\n def unfollow(self, user_id): ...\n def like(self, post_id): ...\n def unlike(self, post_id): ...\n\n self.token = token\n self.user_id = user_id\n self.hashtag_cache = dict()\n self.user_cache = dict()\n self.media_cache = dict()\n\n BASE_URL = 'http://hackathon.ocupa2.com/instagram/'\n", "repository": "jpescalona/ocupa2", "test_name": "test_get_media", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 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_000493.py"} {"focal_file": "app/ocupa2app/helpers/instagram.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 user = self.ig.get_user(74)\n assert user is not None\n", "method_code": " def get_user(self, user_id):\n if user_id not in self.user_cache:\n url = Instagram.BASE_URL + '{id}'.format(id=user_id)\n params = {'fields': 'id,username,media_count,follower_count'}\n d = self.get(url, params)\n self.user_cache[user_id] = d.json()[0]\n return self.user_cache[user_id]\n ", "context": "class Instagram(APIBase):\n def get_user(self, user_id): ...\n def __init__(self, user_id, token=None): ...\n def get_token(self): ...\n def get_hashtag(self, hashtag): ...\n def get_recent_posts(self, hashtag_id): ...\n def get_top_posts(self, hashtag_id): ...\n def get_media(self, media_id): ...\n def extend_posts(self, posts): ...\n def follow(self, user_id): ...\n def unfollow(self, user_id): ...\n def like(self, post_id): ...\n def unlike(self, post_id): ...\n\n self.token = token\n self.user_id = user_id\n self.hashtag_cache = dict()\n self.user_cache = dict()\n self.media_cache = dict()\n\n BASE_URL = 'http://hackathon.ocupa2.com/instagram/'\n", "repository": "jpescalona/ocupa2", "test_name": "test_get_user", "smells": [0, 0, 0, 0, 0, 0, 0, 1, 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_000494.py"} {"focal_file": "filecense/logic.py", "focal_class": null, "focal_method": "find_files", "tests": "import unittest\n\nclass Test_find_files(unittest.TestCase):\n def test_find_files(self):\n all_files = self.finder.find_files('./testdata/')\n for root, _, files in all_files:\n self.assertTrue(validDir(os.path.normpath(root)))\n self.assertEqual(len(files), len(testfiles))\n for f in files:\n self.assertTrue(validFile(f))\n", "method_code": " def find_files(self, path):\n return os.walk(path, topdown=True)\n ", "context": "class finder():\n def find_files(self, path): ...\n def __init__(self, verbose, ignore_dirs, ignore_files): ...\n def get_files(self, path): ...\n def ignore(self, all_files): ...\n def ignoreItems(self, dirs, items): ...\n\n self.verbose = verbose\n self.ignore_dirs = ignore_dirs\n self.ignore_files = ignore_files\n", "repository": "miscing/filecense", "test_name": "test_find_files", "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, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000495.py"} {"focal_file": "filecense/logic.py", "focal_class": null, "focal_method": "ignoreItems", "tests": "import unittest\n\nclass Test_ignoreItems(unittest.TestCase):\n def test_ignoreItems(self):\n all_files = self.finder.find_files('./testdata/')\n trimmedFiles = ['sourceFile.c', 'sourceFile.js', 'sourceFile.html', 'sourceFile.py', 'sourceFile.go', 'sourceFile.ts', 'sourceFile.cpp', 'sourceFile.css']\n for _, d, _ in all_files:\n self.finder.ignoreItems(True, d)\n self.assertEqual(['newdir'], d)\n break\n for _, _, f in all_files:\n self.finder.ignoreItems(False, f)\n self.assertEqual(trimmedFiles.sort(), f.sort())\n break\n", "method_code": " def ignoreItems(self, dirs, items):\n ignores = self.ignore_dirs if dirs else self.ignore_files\n while True:\n i = 0\n for item in items:\n if ignores.ignore(item):\n if self.verbose:\n print('skipping: ', os.path.abspath(item))\n items.remove(item)\n break\n i += 1\n if i >= len(items):\n break\n ", "context": "class finder():\n def ignoreItems(self, dirs, items): ...\n def __init__(self, verbose, ignore_dirs, ignore_files): ...\n def get_files(self, path): ...\n def find_files(self, path): ...\n def ignore(self, all_files): ...\n\n self.verbose = verbose\n self.ignore_dirs = ignore_dirs\n self.ignore_files = ignore_files\n", "repository": "miscing/filecense", "test_name": "test_ignoreItems", "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, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000496.py"} {"focal_file": "filecense/logic.py", "focal_class": null, "focal_method": "ignore", "tests": "import unittest\n\nclass Test_ignore(unittest.TestCase):\n def test_ignore(self):\n all_files = self.finder.find_files('./testdata/')\n files_after_ignore = self.finder.ignore(all_files)\n self.assertEqual(notIgnoredFiles.sort(), files_after_ignore.sort())\n", "method_code": " def ignore(self, item):\n for key in self:\n if self[key](key, item):\n return True\n return False\n ", "context": "class ignore_items():\n def ignore(self, item): ...\n def __init__(self, items=None): ...\n def __setitem__(self, k, v): ...\n def __getitem__(self, k): ...\n def __iter__(self): ...\n def add_items(self, tuples): ...\n def set_simple(self, name): ...\n def set_regex(self, name): ...\n def simple_check(self, matchTo, toMatch): ...\n def regex_check(self, matchTo, toMatch): ...\n\n self.data = {}\n", "repository": "miscing/filecense", "test_name": "test_ignore", "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_000497.py"} {"focal_file": "filecense/logic.py", "focal_class": null, "focal_method": "get_files", "tests": "import unittest\n\nclass Test_get_files(unittest.TestCase):\n def test_get_files(self):\n files = self.finder.get_files('./testdata/')\n self.assertEqual(notIgnoredFiles.sort(), files.sort())\n", "method_code": " def get_files(self, path):\n return self.ignore(self.find_files(path))\n ", "context": "class finder():\n def get_files(self, path): ...\n def __init__(self, verbose, ignore_dirs, ignore_files): ...\n def find_files(self, path): ...\n def ignore(self, all_files): ...\n def ignoreItems(self, dirs, items): ...\n\n self.verbose = verbose\n self.ignore_dirs = ignore_dirs\n self.ignore_files = ignore_files\n", "repository": "miscing/filecense", "test_name": "test_get_files", "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_000498.py"} {"focal_file": "filecense/logic.py", "focal_class": null, "focal_method": "comment_syntax", "tests": "import unittest\n\nclass Test_comment_syntax(unittest.TestCase):\n def test_comment_syntax(self):\n self.assertEqual(self.ff.comment_syntax('correct.py'), ['#'])\n self.assertEqual(self.ff.comment_syntax('Dockerfile'), ['#'])\n self.assertEqual(self.ff.comment_syntax('website.html'), [''])\n self.assertEqual(self.ff.comment_syntax('styling.css'), ['/*', '*/'])\n for incorrect in ['incorrect', 'noExt']:\n with self.assertRaises(ValueError):\n self.ff.comment_syntax(incorrect)\n", "method_code": " def comment_syntax(self, name):\n if pathlib.PurePath(name).suffix != '':\n return self.ext[pathlib.PurePath(name).suffix[1:]]\n else:\n for filere, comment in self.fileregex:\n regex = re.compile(filere)\n if regex.match(name):\n return comment\n raise ValueError('no comment syntax for given file')\n ", "context": "class file_format():\n def comment_syntax(self, name): ...\n def __init__(self, ext=None, filere=None): ...\n def add(self, target, comment_syntax): ...\n def add_ext(self, ext, comment_syntax): ...\n def add_filere(self, filere, comment_syntax): ...\n", "repository": "miscing/filecense", "test_name": "test_comment_syntax", "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, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000499.py"} {"focal_file": "filecense/logic.py", "focal_class": "file_format", "focal_method": "add", "tests": "import unittest\n\nclass Test_file_format_add(unittest.TestCase):\n def test_add(self):\n testFormats = [('Dockerfile', '#'), ('.ext', '#')]\n ff = file_format({}, [])\n for t, s in testFormats:\n ff.add(t, s)\n self.assertEqual(ff.ext, {'ext': '#'})\n self.assertEqual(ff.fileregex, [('Dockerfile', '#')])\n", "method_code": " def add(self, target, comment_syntax):\n if target[0] == '.':\n self.add_ext(target[1:], comment_syntax)\n else:\n self.add_filere(target, comment_syntax)\n ", "context": "class file_format():\n def add(self, target, comment_syntax): ...\n def __init__(self, ext=None, filere=None): ...\n def add_ext(self, ext, comment_syntax): ...\n def add_filere(self, filere, comment_syntax): ...\n def comment_syntax(self, name): ...\n", "repository": "miscing/filecense", "test_name": "test_add", "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, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000500.py"} {"focal_file": "filecense/logic.py", "focal_class": null, "focal_method": "add_ext", "tests": "import unittest\n\nclass Test_add_ext(unittest.TestCase):\n def test_add_ext(self):\n self.ff.add_ext('not', ['!!'])\n self.assertEqual(self.ff.comment_syntax('file.not'), ['!!'])\n", "method_code": " def add_ext(self, ext, comment_syntax):\n self.ext[ext] = comment_syntax\n ", "context": "class file_format():\n def add_ext(self, ext, comment_syntax): ...\n def __init__(self, ext=None, filere=None): ...\n def add(self, target, comment_syntax): ...\n def add_filere(self, filere, comment_syntax): ...\n def comment_syntax(self, name): ...\n", "repository": "miscing/filecense", "test_name": "test_add_ext", "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_000501.py"} {"focal_file": "filecense/logic.py", "focal_class": null, "focal_method": "add_filere", "tests": "import unittest\n\nclass Test_add_filere(unittest.TestCase):\n def test_add_filere(self):\n self.ff.add_filere('Somefilename', ['!!'])\n self.assertEqual(self.ff.comment_syntax('Somefilename'), ['!!'])\n", "method_code": " def add_filere(self, filere, comment_syntax):\n self.fileregex.append((filere, comment_syntax))\n ", "context": "class file_format():\n def add_filere(self, filere, comment_syntax): ...\n def __init__(self, ext=None, filere=None): ...\n def add(self, target, comment_syntax): ...\n def add_ext(self, ext, comment_syntax): ...\n def comment_syntax(self, name): ...\n", "repository": "miscing/filecense", "test_name": "test_add_filere", "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_000502.py"} {"focal_file": "filecense/logic.py", "focal_class": null, "focal_method": "already_has_license", "tests": "import unittest\n\nclass Test_already_has_license(unittest.TestCase):\n def test_already_has_license(self):\n copyfile(self.src_path, self.dst_path)\n name = 'John Doe'\n date = datetime.now().year\n top = comment_out(euplTop, ['//']) % (date, name)\n self.assertFalse(already_has_license(self.dst_path, top))\n write_top(top, self.dst_path)\n self.assertTrue(already_has_license(self.dst_path, top))\n os.remove(self.dst_path)\n", "method_code": "def already_has_license(filepath, top):\n regex = re.compile('^#!/.+$')\n with open(filepath, 'r') as f:\n content = f.read().split('\\n')\n if regex.match(content[0]):\n content = content[1:]\n return '\\n'.join(content).startswith(top)", "context": "def already_has_license(filepath, top): ...\ndef main(): ...\ndef parser(): ...\ndef find_root(path): ...\ndef write_full(text, location, name, open_opt): ...\ndef already_has_license(filepath, top): ...\ndef write_top(ntop, path): ...\ndef comment_out(text, comment): ...\ndef syntax_arg(arg): ...\n", "repository": "miscing/filecense", "test_name": "test_already_has_license", "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_000503.py"} {"focal_file": "filecense/logic.py", "focal_class": null, "focal_method": "write_top", "tests": "import unittest\n\nclass Test_write_top(unittest.TestCase):\n def test_write_top(self):\n with open(self.src_path) as f:\n src_content = f.read()\n for s, ht in self.syntax_and_hardcoded_text:\n copyfile(self.src_path, self.dst_path)\n write_top(comment_out(self.uncommented, s), self.dst_path)\n with open(self.dst_path) as f:\n dst_content = f.read()\n self.assertEqual(ht + '\\n' + src_content, dst_content)\n os.remove(self.dst_path)\n copyfile(self.src_path, self.dst_path)\n name = 'John Doe'\n date = datetime.now().year\n write_top(comment_out(euplTop, ['//']) % (date, name), self.dst_path)\n with open(self.dst_path) as f:\n dst_content = f.read()\n self.assertEqual(dst_content, self.euplCommented % (date, name) + src_content)\n os.remove(self.dst_path)\n", "method_code": "def write_top(ntop, path):\n regex = re.compile('^#!/.+$')\n f = open(path, 'r')\n line = f.readline()\n mark = False\n if regex.search(line) is not None:\n mark = True\n pass\n else:\n f.seek(0)\n saved = f.read()\n f.close()\n f = open(path, 'w')\n if mark:\n f.write(line)\n f.writelines([ntop, '\\n', saved])\n f.close()", "context": "def write_top(ntop, path): ...\ndef main(): ...\ndef parser(): ...\ndef find_root(path): ...\ndef write_full(text, location, name, open_opt): ...\ndef already_has_license(filepath, top): ...\ndef write_top(ntop, path): ...\ndef comment_out(text, comment): ...\ndef syntax_arg(arg): ...\n", "repository": "miscing/filecense", "test_name": "test_write_top", "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, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000504.py"} {"focal_file": "filecense/logic.py", "focal_class": null, "focal_method": "comment_out", "tests": "import unittest\n\nclass Test_comment_out(unittest.TestCase):\n def test_comment_out(self):\n for s, ht in self.syntax_and_hardcoded_text:\n commented = comment_out(self.uncommented, s)\n self.assertEqual(commented, ht)\n", "method_code": "def comment_out(text, comment):\n\n def comment_left(text):\n if text == '':\n return comment[0]\n return comment[0] + ' ' + text\n\n def comment_both(text):\n if text == '':\n return comment[0] + ' ' + comment[1]\n return comment[0] + ' ' + text + ' ' + comment[1]\n if not isinstance(comment, list) or len(comment) > 2:\n raise ValueError('incorrect comment arg, must be array of 1 or 2')\n if len(comment) == 1:\n line_maker = comment_left\n elif len(comment) == 2:\n line_maker = comment_both\n else:\n raise ValueError('comment syntax must be an array of 1 or 2')\n res = []\n res.append(line_maker(''))\n for line in text.splitlines():\n res.append(line_maker(line))\n res.append(line_maker(''))\n res.append('')\n return '\\n'.join(res)", "context": "def comment_out(text, comment): ...\ndef main(): ...\ndef parser(): ...\ndef find_root(path): ...\ndef write_full(text, location, name, open_opt): ...\ndef already_has_license(filepath, top): ...\ndef write_top(ntop, path): ...\ndef comment_out(text, comment): ...\ndef syntax_arg(arg): ...\n", "repository": "miscing/filecense", "test_name": "test_comment_out", "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_000505.py"} {"focal_file": "filecense/logic.py", "focal_class": null, "focal_method": "syntax_arg", "tests": "import unittest\n\nclass Test_syntax_arg(unittest.TestCase):\n def test_syntax_arg(self):\n self.assertEqual(syntax_arg('hello=world'), ('hello', ['world']))\n self.assertNotEqual(syntax_arg('hello=asdoisd'), ('hello', ['world']))\n for inc in ['hello=asdoisd=asd09', 'heasodijasd']:\n with self.assertRaises(ValueError):\n syntax_arg(inc)\n self.assertEqual(syntax_arg('.ext=#'), ('.ext', ['#']))\n self.assertEqual(syntax_arg('file=//'), ('file', ['//']))\n self.assertEqual(syntax_arg('file='), ('file', ['']))\n", "method_code": "def syntax_arg(arg):\n key_and_comment = arg.split('=')\n if len(key_and_comment) != 2:\n raise ValueError('syntax arguments must be given in key=value format')\n comments = key_and_comment[1].split(',')\n return (key_and_comment[0], comments)", "context": "def syntax_arg(arg): ...\ndef main(): ...\ndef parser(): ...\ndef find_root(path): ...\ndef write_full(text, location, name, open_opt): ...\ndef already_has_license(filepath, top): ...\ndef write_top(ntop, path): ...\ndef comment_out(text, comment): ...\ndef syntax_arg(arg): ...\n", "repository": "miscing/filecense", "test_name": "test_syntax_arg", "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, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000506.py"} {"focal_file": "filecense/logic.py", "focal_class": null, "focal_method": "write_full", "tests": "import unittest\n\nclass Test_write_full(unittest.TestCase):\n def test_write_full(self):\n write_full('This is not a license', '.', 'TESTLICENSE', 'x')\n self.assertTrue(os.path.isfile('TESTLICENSE'))\n with self.assertRaises(FileExistsError):\n write_full('This is not a license', '.', 'TESTLICENSE', 'x')\n write_full('This is not a license', '.', 'TESTLICENSE', 'w')\n self.assertTrue(os.path.isfile('TESTLICENSE'))\n os.remove('TESTLICENSE')\n", "method_code": "def write_full(text, location, name, open_opt):\n with open(os.path.join(location, name), open_opt) as f:\n f.write(text)", "context": "def write_full(text, location, name, open_opt): ...\ndef main(): ...\ndef parser(): ...\ndef find_root(path): ...\ndef write_full(text, location, name, open_opt): ...\ndef already_has_license(filepath, top): ...\ndef write_top(ntop, path): ...\ndef comment_out(text, comment): ...\ndef syntax_arg(arg): ...\n", "repository": "miscing/filecense", "test_name": "test_write_full", "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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000507.py"} {"focal_file": "filecense/logic.py", "focal_class": null, "focal_method": "find_root", "tests": "import unittest\n\nclass Test_find_root(unittest.TestCase):\n def test_find_root(self):\n root = os.path.normpath(os.path.join(here, '../testdata'))\n root_path = find_root(root)\n self.assertEqual(root_path, os.path.dirname(self.hardcoded_path))\n self.assertNotEqual(root_path, '../testdata')\n", "method_code": "def find_root(path):\n tuples = os.walk(path, topdown=True)\n for root, dirs, files in tuples:\n for d in dirs:\n if d == '.git':\n return os.path.abspath(root)\n return os.path.abspath(path)", "context": "def find_root(path): ...\ndef main(): ...\ndef parser(): ...\ndef find_root(path): ...\ndef write_full(text, location, name, open_opt): ...\ndef already_has_license(filepath, top): ...\ndef write_top(ntop, path): ...\ndef comment_out(text, comment): ...\ndef syntax_arg(arg): ...\n", "repository": "miscing/filecense", "test_name": "test_find_root", "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_000508.py"} {"focal_file": "src/fxd/minilexer.py", "focal_class": "fxd.minilexer.Parser", "focal_method": "parse_readline", "tests": "import unittest\n\nclass Test_fxd_minilexer_Parser_parse_readline(unittest.TestCase):\n def test_readline(self):\n string = StringIO('word1\\nword2')\n self.assertListEqual(string.readlines(), ['word1\\n', 'word2'])\n string.seek(0)\n my_lexer = dict(BASE, begin=dict(match=minilexer.MRE('^word1\\n?$'), after='word2'), word2=dict(match=minilexer.MRE('^word2\\n?$'), after='finish'))\n parser = minilexer.Parser(my_lexer)\n parser.parse_readline(string.readline)\n parser = minilexer.Parser(my_lexer, True)\n parser.parse_readline(string.readline)\n", "method_code": " def parse_readline(self, readline):\n self.current_readline = readline\n self.run_parser()\n ", "context": "class Parser():\n def parse_readline(self, readline): ...\n def __init__(self, lexer, eol_newline=False): ...\n def parse_lines(self, lines): ...\n def readline(self): ...\n def cache_push(self): ...\n def cache_pop(self): ...\n def cache_discard(self): ...\n def cache_purge(self): ...\n def iter_tokens(self, name): ...\n def reset_iter(self, lookup): ...\n def on_bad_token(self): ...\n def token_match(self, token, match): ...\n def run_parser(self): ...\n\n self.lexer = lexer\n self.eol_newline = eol_newline\n self.current_readline = None\n self.line_cache = list()\n self.idx_stack = list()\n self.next_lineidx = 0\n self.current_iter = None\n self.current_line = ''\n self.current_lineno = 0\n self.current_pos = 0\n", "repository": "fluxid/minilexer", "test_name": "test_readline", "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_000509.py"} {"focal_file": "yql/__init__.py", "focal_class": "YQLQuery", "focal_method": "get_placeholder_keys", "tests": "import unittest\n\nclass Test_YQLQuery_get_placeholder_keys(unittest.TestCase):\n def test_placeholder_regex_one(self):\n query = YQLQuery(\"SELECT * from foo where email='foo@foo.com'\")\n placeholders = query.get_placeholder_keys()\n self.assertEqual(placeholders, [])\n\n def test_placeholder_regex_two(self):\n query = YQLQuery(\"SELECT * from foo where email=@foo'\")\n placeholders = query.get_placeholder_keys()\n self.assertEqual(placeholders, ['foo'])\n\n def test_placeholder_regex_three(self):\n query = YQLQuery(\"SELECT * from foo where email=@foo and test=@bar'\")\n placeholders = query.get_placeholder_keys()\n self.assertEqual(placeholders, ['foo', 'bar'])\n\n def test_placeholder_regex_four(self):\n query = YQLQuery(\"SELECT * from foo where foo='bar' LIMIT @foo\")\n placeholders = query.get_placeholder_keys()\n self.assertEqual(placeholders, ['foo'])\n\n def test_placeholder_regex_five(self):\n query = YQLQuery(\"SELECT * from foo\\n where foo='bar' LIMIT\\n @foo\")\n placeholders = query.get_placeholder_keys()\n self.assertEqual(placeholders, ['foo'])\n", "method_code": " def get_placeholder_keys(self):\n \"\"\"Gets the @var placeholders\n \n http://developer.yahoo.com/yql/guide/var_substitution.html\n \"\"\"\n result = []\n for match in QUERY_PLACEHOLDER.finditer(self.query):\n result.append(match.group('param'))\n if result:\n yql_logger.debug('placeholder_keys: %s', result)\n return result\n ", "context": "class YQLQuery(object):\n def get_placeholder_keys(self): ...\n def __init__(self, query): ...\n def __str__(self): ...\n def get_http_method(self): ...\n def validate(self, substitutions=None): ...\n def _validate_substitutions(self, substitutions, placeholders): ...\n def _validate_substitutions_dictionary(self, placeholders, substitutions): ...\n\n self.query = clean_query(query)\n", "repository": "orymeyer/XML-Tweet", "test_name": "test_placeholder_regex_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_000510.py"} {"focal_file": "yql/__init__.py", "focal_class": "yql.ThreeLegged", "focal_method": "get_base_params", "tests": "import unittest\n\nclass Test_yql_ThreeLegged_get_base_params(unittest.TestCase):\n def test_get_base_params(self):\n y = yql.ThreeLegged('test-api-key', 'test-secret')\n result = y.get_base_params()\n self.assertEqual(set(['oauth_nonce', 'oauth_version', 'oauth_timestamp']), set(result.keys()))\n", "method_code": " def get_base_params():\n \"\"\"Set-up the basic parameters needed for a request\"\"\"\n params = {}\n params['oauth_version'] = '1.0'\n params['oauth_nonce'] = oauth.generate_nonce()\n params['oauth_timestamp'] = int(time.time())\n return params\n ", "context": "class TwoLegged(Public):\n @staticmethod\n def get_base_params(): ...\n def __init__(self, api_key, shared_secret, httplib2_inst=None): ...\n def get_signature(self, url): ...\n def __two_legged_request(self, parameters=None, method=None): ...\n def get_uri(self, query, params=None, **kwargs): ...\n\n self.endpoint = PRIVATE_ENDPOINT\n self.hmac_sha1_signature = oauth.SignatureMethod_HMAC_SHA1()\n self.plaintext_signature = oauth.SignatureMethod_PLAINTEXT()\n", "repository": "orymeyer/XML-Tweet", "test_name": "test_get_base_params", "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_000511.py"} {"focal_file": "yql/storage.py", "focal_class": null, "focal_method": "set", "tests": "import unittest\n\nclass Test_set(unittest.TestCase):\n @raises(NotImplementedError)\n def test_must_implement_set(self):\n\n class FooStore(BaseTokenStore):\n pass\n store = FooStore()\n store.set('some name', 'some token')\n", "method_code": " def set(self, name, token):\n raise NotImplementedError\n ", "context": "class BaseTokenStore(object):\n def set(self, name, token): ...\n def get(self, name): ...\n", "repository": "orymeyer/XML-Tweet", "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_000512.py"} {"focal_file": "yql/storage.py", "focal_class": null, "focal_method": "get", "tests": "import unittest\n\nclass Test_get(unittest.TestCase):\n @raises(NotImplementedError)\n def test_must_implement_get(self):\n\n class FooStore(BaseTokenStore):\n pass\n store = FooStore()\n store.get('some name')\n", "method_code": " def get(self, name):\n raise NotImplementedError\n ", "context": "class BaseTokenStore(object):\n def get(self, name): ...\n def set(self, name, token): ...\n", "repository": "orymeyer/XML-Tweet", "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_000513.py"} {"focal_file": "yql/__init__.py", "focal_class": "yql.YahooToken", "focal_method": "to_string", "tests": "import unittest\n\nclass Test_yql_YahooToken_to_string(unittest.TestCase):\n def test_y_token_to_string(self):\n token = yql.YahooToken('test-key', 'test-secret')\n token_to_string = token.to_string()\n string_data = dict(parse_qsl(token_to_string))\n self.assertEqual(string_data.get('oauth_token'), 'test-key')\n self.assertEqual(string_data.get('oauth_token_secret'), 'test-secret')\n\n def test_y_token_to_string2(self):\n token = yql.YahooToken('test-key', 'test-secret')\n token.timestamp = '1111'\n token.session_handle = 'poop'\n token.callback_confirmed = 'basilfawlty'\n token_to_string = token.to_string()\n string_data = dict(parse_qsl(token_to_string))\n self.assertEqual(string_data.get('oauth_token'), 'test-key')\n self.assertEqual(string_data.get('oauth_token_secret'), 'test-secret')\n self.assertEqual(string_data.get('token_creation_timestamp'), '1111')\n self.assertEqual(string_data.get('oauth_callback_confirmed'), 'basilfawlty')\n self.assertEqual(string_data.get('oauth_session_handle'), 'poop')\n", "method_code": " def to_string(self):\n \"\"\"Returns this token as a plain string, suitable for storage.\n The resulting string includes the token's secret, so you should never\n send or store this string where a third party can read it.\n \n \"\"\"\n data = {'oauth_token': self.key, 'oauth_token_secret': self.secret}\n if hasattr(self, 'session_handle'):\n data['oauth_session_handle'] = self.session_handle\n if hasattr(self, 'timestamp'):\n data['token_creation_timestamp'] = self.timestamp\n if self.callback_confirmed is not None:\n data['oauth_callback_confirmed'] = self.callback_confirmed\n return urlencode(data)\n ", "context": "class YahooToken(oauth.Token):\n def to_string(self): ...\n def from_string(data_string): ...\n", "repository": "orymeyer/XML-Tweet", "test_name": "test_y_token_to_string", "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_000514.py"} {"focal_file": "yql/__init__.py", "focal_class": null, "focal_method": "from_string", "tests": "import unittest\n\nclass Test_from_string(unittest.TestCase):\n def test_y_token_from_string(self):\n token_string = 'oauth_token=foo&oauth_token_secret=bar&oauth_session_handle=baz&token_creation_timestamp=1111'\n token_from_string = yql.YahooToken.from_string(token_string)\n self.assertEqual(token_from_string.key, 'foo')\n self.assertEqual(token_from_string.secret, 'bar')\n self.assertEqual(token_from_string.session_handle, 'baz')\n self.assertEqual(token_from_string.timestamp, '1111')\n", "method_code": " def from_string(data_string):\n \"\"\"Deserializes a token from a string like one returned by\n \n `to_string()`.\"\"\"\n if not len(data_string):\n raise ValueError('Invalid parameter string.')\n params = parse_qs(data_string, keep_blank_values=False)\n if not len(params):\n raise ValueError('Invalid parameter string.')\n try:\n key = params['oauth_token'][0]\n except Exception:\n raise ValueError(\"'oauth_token' not found in OAuth request.\")\n try:\n secret = params['oauth_token_secret'][0]\n except Exception:\n raise ValueError(\"'oauth_token_secret' not found in OAuth request.\")\n token = YahooToken(key, secret)\n session_handle = params.get('oauth_session_handle')\n if session_handle:\n setattr(token, 'session_handle', session_handle[0])\n timestamp = params.get('token_creation_timestamp')\n if timestamp:\n setattr(token, 'timestamp', timestamp[0])\n try:\n token.callback_confirmed = params['oauth_callback_confirmed'][0]\n except KeyError:\n pass\n return token\n ", "context": "class YahooToken(oauth.Token):\n @staticmethod\n def from_string(data_string): ...\n def to_string(self): ...\n", "repository": "orymeyer/XML-Tweet", "test_name": "test_y_token_from_string", "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_000515.py"} {"focal_file": "yql/__init__.py", "focal_class": null, "focal_method": "one", "tests": "import unittest\n\nclass Test_one(unittest.TestCase):\n @raises(NotOneError)\n def test_one(self):\n \"\"\"Test that accessing one result raises exception\"\"\"\n yqlobj.one()\n", "method_code": " def one(self):\n \"\"\"Return just one result directly.\"\"\"\n rows = self.rows\n if len(rows) > 1:\n raise NotOneError('More than one result')\n else:\n return rows[0]\n ", "context": "class YQLObj(object):\n def one(self): ...\n def __init__(self, result_dict): ...\n def raw(self): ...\n def uri(self): ...\n def query_params(self): ...\n def results(self): ...\n def rows(self): ...\n def query(self): ...\n def lang(self): ...\n def count(self): ...\n def diagnostics(self): ...\n def pprint_raw(self, indent=4): ...\n def pformat_raw(self, indent=4): ...\n\n self._raw = result_dict and result_dict.get('query') or {}\n", "repository": "orymeyer/XML-Tweet", "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_000516.py"} {"focal_file": "archiver/clients.py", "focal_class": null, "focal_method": "sqs_client", "tests": "import unittest\n\nclass Test_sqs_client(unittest.TestCase):\n @mock.patch('archiver.clients.get_session')\n def test_sqs_client(self, mock_session):\n sqs1 = clients.sqs_client(FAKE_QUEUE_NAME1)\n sqs2 = clients.sqs_client(FAKE_QUEUE_NAME1)\n sqs3 = clients.sqs_client(FAKE_QUEUE_NAME2)\n self.assertTrue(sqs1 is sqs2)\n self.assertFalse(sqs1 is sqs3)\n mock_session().client.assert_has_calls([mock.call('sqs'), mock.call('sqs')], any_order=True)\n", "method_code": "def sqs_client(queue):\n if queue not in _CLIENTS['sqs']:\n _CLIENTS['sqs'][queue] = SQSClient(queue)\n return _CLIENTS['sqs'][queue]", "context": "def sqs_client(queue): ...\ndef sqs_client(queue): ...\ndef s3_client(): ...\ndef persistence_client(): ...\ndef get_session(): ...\n", "repository": "rm-you/tweench", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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, 1, 0, 0], "pynose_source_file": "test_000517.py"} {"focal_file": "archiver/clients.py", "focal_class": null, "focal_method": "s3_client", "tests": "import unittest\n\nclass Test_s3_client(unittest.TestCase):\n @mock.patch('archiver.clients.get_session')\n def test_s3_client(self, mock_session):\n s3_1 = clients.s3_client()\n s3_2 = clients.s3_client()\n self.assertTrue(s3_1 is s3_2)\n mock_session().client.assert_has_calls([mock.call('s3')], any_order=True)\n", "method_code": "def s3_client():\n if not _CLIENTS['s3']:\n _CLIENTS['s3'] = S3Client()\n return _CLIENTS['s3']", "context": "def s3_client(): ...\ndef sqs_client(queue): ...\ndef s3_client(): ...\ndef persistence_client(): ...\ndef get_session(): ...\n", "repository": "rm-you/tweench", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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, 1, 0, 0], "pynose_source_file": "test_000518.py"} {"focal_file": "archiver/clients.py", "focal_class": null, "focal_method": "persistence_client", "tests": "import unittest\n\nclass Test_persistence_client(unittest.TestCase):\n def test_persistence_client(self):\n self.mock_config().PERSISTENCE_DRIVER = 'archiver.persistence.logger:LoggingPersistence'\n persist_1 = clients.persistence_client()\n persist_2 = clients.persistence_client()\n self.assertTrue(persist_1 is persist_2)\n", "method_code": "def persistence_client():\n if not _CLIENTS['persistence']:\n conf = config.get_config()\n persistence_module, persistence_class = conf.PERSISTENCE_DRIVER.split(':')\n persistence_module = importlib.import_module(persistence_module)\n persistence_class = getattr(persistence_module, persistence_class)\n _CLIENTS['persistence'] = persistence_class()\n return _CLIENTS['persistence']", "context": "def persistence_client(): ...\ndef sqs_client(queue): ...\ndef s3_client(): ...\ndef persistence_client(): ...\ndef get_session(): ...\n", "repository": "rm-you/tweench", "test_name": "test_persistence_client", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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, 1, 0, 0], "pynose_source_file": "test_000519.py"} {"focal_file": "archiver/clients.py", "focal_class": null, "focal_method": "get_session", "tests": "import unittest\n\nclass Test_get_session(unittest.TestCase):\n @mock.patch('archiver.clients.session.Session')\n def test_get_session(self, mock_boto_session):\n session1 = clients.get_session()\n session2 = clients.get_session()\n self.assertTrue(session1 is session2)\n mock_boto_session.assert_called_with(aws_access_key_id=self.mock_config().AWS_ACCESS_KEY_ID, aws_secret_access_key=self.mock_config().AWS_ACCESS_KEY_SECRET, region_name=self.mock_config().AWS_REGION)\n", "method_code": "def get_session():\n if not _CLIENTS['session']:\n conf = config.get_config()\n _CLIENTS['session'] = session.Session(aws_access_key_id=conf.AWS_ACCESS_KEY_ID, aws_secret_access_key=conf.AWS_ACCESS_KEY_SECRET, region_name=conf.AWS_REGION)\n return _CLIENTS['session']", "context": "def get_session(): ...\ndef sqs_client(queue): ...\ndef s3_client(): ...\ndef persistence_client(): ...\ndef get_session(): ...\n", "repository": "rm-you/tweench", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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, 1, 0, 0], "pynose_source_file": "test_000520.py"} {"focal_file": "archiver/clients.py", "focal_class": null, "focal_method": "upload", "tests": "import unittest\n\nclass Test_upload(unittest.TestCase):\n def test_upload(self):\n s3 = self._make_s3client()\n s3.upload(FAKE_BUCKET_NAME, FAKE_PATH, FAKE_DATA)\n self.mock_client().upload_fileobj.assert_called_once_with(FAKE_DATA, FAKE_BUCKET_NAME, FAKE_PATH, None)\n", "method_code": " def upload(self, bucket, path, data, extra_args=None):\n LOG.info(u'Uploading file to S3 ({}): {}'.format(bucket, path))\n self.client.upload_fileobj(data, bucket, path, extra_args)\n ", "context": "class S3Client(object):\n def upload(self, bucket, path, data, extra_args=None): ...\n def __init__(self): ...\n def object_exists(self, bucket, path): ...\n\n self.client = get_session().client('s3')\n", "repository": "rm-you/tweench", "test_name": "test_upload", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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_000521.py"} {"focal_file": "archiver/clients.py", "focal_class": null, "focal_method": "object_exists", "tests": "import unittest\n\nclass Test_object_exists(unittest.TestCase):\n def test_object_exists_true(self):\n s3 = self._make_s3client()\n exists = s3.object_exists(FAKE_BUCKET_NAME, FAKE_PATH)\n self.mock_client().head_object.assert_called_once_with(Bucket=FAKE_BUCKET_NAME, Key=FAKE_PATH)\n self.assertTrue(exists)\n\n def test_object_exists_false(self):\n s3 = self._make_s3client()\n self.mock_client().head_object.side_effect = boto_exceptions.ClientError({'Error': {'Code': 403, 'Message': 'Forbidden'}}, 'HeadObject')\n exists = s3.object_exists(FAKE_BUCKET_NAME, FAKE_PATH)\n self.mock_client().head_object.assert_called_once_with(Bucket=FAKE_BUCKET_NAME, Key=FAKE_PATH)\n self.assertFalse(exists)\n", "method_code": " def object_exists(self, bucket, path):\n try:\n self.client.head_object(Bucket=bucket, Key=path)\n except boto_exceptions.ClientError:\n return False\n LOG.info(u'File already exists in S3: {}'.format(path))\n return True\n ", "context": "class S3Client(object):\n def object_exists(self, bucket, path): ...\n def __init__(self): ...\n def upload(self, bucket, path, data, extra_args=None): ...\n\n self.client = get_session().client('s3')\n", "repository": "rm-you/tweench", "test_name": "test_object_exists_true", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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_000522.py"} {"focal_file": "archiver/clients.py", "focal_class": null, "focal_method": "send_message", "tests": "import unittest\n\nclass Test_send_message(unittest.TestCase):\n def test_send_message(self):\n sqs = self._make_sqsclient()\n sqs.send_message(FAKE_MESSAGE)\n self.mock_client().get_queue_url.assert_any_call(QueueName=FAKE_QUEUE_NAME1)\n self.mock_client().send_message.assert_called_once_with(QueueUrl=self.mock_client().get_queue_url().__getitem__(), MessageBody=FAKE_MESSAGE)\n", "method_code": " def send_message(self, message):\n self.client.send_message(QueueUrl=self.queue_url, MessageBody=message)\n ", "context": "class SQSClient(object):\n def send_message(self, message): ...\n def __init__(self, queue_name): ...\n def get_message(self, wait=20): ...\n def delete_message(self, mid): ...\n\n self.client = get_session().client('sqs')\n self.queue_url = response['QueueUrl']\n\n _message_types = {constants.MESSAGE_SUBREDDIT: messages.SubredditMessage, constants.MESSAGE_POST: messages.PostMessage}\n", "repository": "rm-you/tweench", "test_name": "test_send_message", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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_000523.py"} {"focal_file": "archiver/clients.py", "focal_class": null, "focal_method": "get_message", "tests": "import unittest\n\nclass Test_get_message(unittest.TestCase):\n def test_get_message(self):\n sqs = self._make_sqsclient()\n self.mock_client().receive_message.return_value = {'Messages': [{'Body': json.dumps({'type': FAKE_MESSAGE_TYPE, 'body': FAKE_MESSAGE}), 'ReceiptHandle': FAKE_RECEIPT_ID}]}\n resp = sqs.get_message(wait=FAKE_WAIT_TIME)\n self.mock_client().receive_message.assert_called_once_with(QueueUrl=self.mock_client().get_queue_url().__getitem__(), AttributeNames=['All'], MaxNumberOfMessages=1, WaitTimeSeconds=FAKE_WAIT_TIME)\n self.assertIsInstance(resp, messages.SubredditMessage)\n self.assertEqual(resp.body, FAKE_MESSAGE)\n self.assertEqual(resp.type, constants.MESSAGE_SUBREDDIT)\n self.assertEqual(resp.id, FAKE_RECEIPT_ID)\n\n def test_get_message_timeout(self):\n sqs = self._make_sqsclient()\n self.mock_client().receive_message.return_value = {}\n resp = sqs.get_message(wait=FAKE_WAIT_TIME)\n self.assertIsNone(resp)\n", "method_code": " def get_message(self, wait=20):\n resp = self.client.receive_message(QueueUrl=self.queue_url, AttributeNames=['All'], MaxNumberOfMessages=1, WaitTimeSeconds=wait)\n if resp.get('Messages'):\n m = resp.get('Messages')[0]\n body = json.loads(m['Body'])\n receipt_handle = m['ReceiptHandle']\n m_obj = self._message_types[body.get('type')](mid=receipt_handle, **body.get('body'))\n return m_obj\n return None\n ", "context": "class SQSClient(object):\n def get_message(self, wait=20): ...\n def __init__(self, queue_name): ...\n def send_message(self, message): ...\n def delete_message(self, mid): ...\n\n self.client = get_session().client('sqs')\n self.queue_url = response['QueueUrl']\n\n _message_types = {constants.MESSAGE_SUBREDDIT: messages.SubredditMessage, constants.MESSAGE_POST: messages.PostMessage}\n", "repository": "rm-you/tweench", "test_name": "test_get_message", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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_000524.py"} {"focal_file": "archiver/clients.py", "focal_class": null, "focal_method": "delete_message", "tests": "import unittest\n\nclass Test_delete_message(unittest.TestCase):\n def test_delete_message(self):\n sqs = self._make_sqsclient()\n sqs.delete_message(FAKE_RECEIPT_ID)\n self.mock_client().get_queue_url.assert_any_call(QueueName=FAKE_QUEUE_NAME1)\n self.mock_client().delete_message.assert_called_once_with(QueueUrl=self.mock_client().get_queue_url().__getitem__(), ReceiptHandle=FAKE_RECEIPT_ID)\n", "method_code": " def delete_message(self, mid):\n self.client.delete_message(QueueUrl=self.queue_url, ReceiptHandle=mid)\n ", "context": "class SQSClient(object):\n def delete_message(self, mid): ...\n def __init__(self, queue_name): ...\n def send_message(self, message): ...\n def get_message(self, wait=20): ...\n\n self.client = get_session().client('sqs')\n self.queue_url = response['QueueUrl']\n\n _message_types = {constants.MESSAGE_SUBREDDIT: messages.SubredditMessage, constants.MESSAGE_POST: messages.PostMessage}\n", "repository": "rm-you/tweench", "test_name": "test_delete_message", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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_000525.py"} {"focal_file": "archiver/clients.py", "focal_class": null, "focal_method": "_prepare_headers", "tests": "import unittest\n\nclass Test_prepare_headers(unittest.TestCase):\n def test__prepare_headers(self):\n headers = self.imgur_client._prepare_headers()\n self.assertEqual(self.expected_headers, headers)\n", "method_code": " def _prepare_headers(self):\n headers = {'Authorization': 'Client-ID {0}'.format(self.client_id)}\n return headers\n ", "context": "class ImgurClient(object):\n def _prepare_headers(self): ...\n def __init__(self, client_id): ...\n def get_album(self, album_id): ...\n def get_image(self, image_id): ...\n\n self.client_id = client_id\n\n _base_url = 'https://api.imgur.com'\n _album = '/3/album/{id}'\n _image = '/3/image/{id}'\n", "repository": "rm-you/tweench", "test_name": "test__prepare_headers", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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_000526.py"} {"focal_file": "archiver/clients.py", "focal_class": null, "focal_method": "get_album", "tests": "import unittest\n\nclass Test_get_album(unittest.TestCase):\n @requests_mock.mock()\n def test_get_album(self, mock_req):\n fake_content = {'data': {'images': [{'link': FAKE_IMAGE_URL1}, {'link': FAKE_IMAGE_URL2}]}}\n mock_req.get(self.expected_album_url, json=fake_content)\n album = self.imgur_client.get_album(FAKE_ALBUM_ID)\n self.assertListEqual(album, [FAKE_IMAGE_URL1, FAKE_IMAGE_URL2])\n", "method_code": " def get_album(self, album_id):\n album_url = self._album.format(id=album_id)\n url = '{0}{1}'.format(self._base_url, album_url)\n r = requests.get(url, headers=self._prepare_headers())\n images = r.json().get('data', {}).get('images', [])\n links = {i.get('link') for i in images if i.get('link')}\n return list(links)\n ", "context": "class ImgurClient(object):\n def get_album(self, album_id): ...\n def __init__(self, client_id): ...\n def _prepare_headers(self): ...\n def get_image(self, image_id): ...\n\n self.client_id = client_id\n\n _base_url = 'https://api.imgur.com'\n _album = '/3/album/{id}'\n _image = '/3/image/{id}'\n", "repository": "rm-you/tweench", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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_000527.py"} {"focal_file": "archiver/clients.py", "focal_class": null, "focal_method": "get_image", "tests": "import unittest\n\nclass Test_get_image(unittest.TestCase):\n @requests_mock.mock()\n def test_get_image(self, mock_req):\n fake_content = {'data': {'link': FAKE_IMAGE_URL1}}\n mock_req.get(self.expected_image_url, json=fake_content)\n image = self.imgur_client.get_image(FAKE_IMAGE_ID1)\n self.assertEqual(image, FAKE_IMAGE_URL1)\n", "method_code": " def get_image(self, image_id):\n image_url = self._image.format(id=image_id)\n url = '{0}{1}'.format(self._base_url, image_url)\n r = requests.get(url, headers=self._prepare_headers())\n link = r.json().get('data', {}).get('link')\n return link\n ", "context": "class ImgurClient(object):\n def get_image(self, image_id): ...\n def __init__(self, client_id): ...\n def _prepare_headers(self): ...\n def get_album(self, album_id): ...\n\n self.client_id = client_id\n\n _base_url = 'https://api.imgur.com'\n _album = '/3/album/{id}'\n _image = '/3/image/{id}'\n", "repository": "rm-you/tweench", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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_000528.py"} {"focal_file": "archiver/image_handling.py", "focal_class": null, "focal_method": "upload", "tests": "import unittest\n\nclass Test_upload(unittest.TestCase):\n def test_upload(self):\n image = self._make_image(FAKE_IMAGE_PATH1, FAKE_IMAGE_DATA1)\n image.upload()\n self.mock_bytesio.assert_has_calls([mock.call(FAKE_IMAGE_DATA1)])\n self.mock_s3().upload.assert_called_once_with(FAKE_IMAGE_BUCKET_NAME, FAKE_IMAGE_PATH1, self.mock_bytesio(), FAKE_CONTENT_TYPE)\n", "method_code": " def upload(self):\n io_data = io.BytesIO(self.data)\n self.s3.upload(self.conf.IMAGE_BUCKET_NAME, self.path, io_data, {'ContentType': self.type})\n ", "context": "class Image(object):\n def upload(self): ...\n def __init__(self, path, data, thumb_data=None, content_type=None, thumb_content_type=None): ...\n def upload_thumbnail(self, width=None, height=None): ...\n def _thumbnail(self, width=None, height=None): ...\n def get_colors(self): ...\n def get_dimensions(self): ...\n\n self.conf = config.get_config()\n self.s3 = clients.s3_client()\n self.path = path\n self.data = data\n self.thumb_data = thumb_data\n", "repository": "rm-you/tweench", "test_name": "test_upload", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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_000529.py"} {"focal_file": "archiver/image_handling.py", "focal_class": null, "focal_method": "upload_thumbnail", "tests": "import unittest\n\nclass Test_upload_thumbnail(unittest.TestCase):\n def test_upload_thumbnail(self):\n image = self._make_image(FAKE_IMAGE_PATH1, FAKE_IMAGE_DATA1)\n self.mock_pil.open().size = (600, 800)\n image.upload_thumbnail(width=FAKE_THUMBNAIL_SIZE)\n self.mock_pil.open().resize.assert_called_once_with((300, 400), self.mock_pil.ANTIALIAS)\n self.mock_pil.open().resize().save.assert_called_once_with(self.mock_bytesio(), FAKE_IMAGE_FORMAT)\n self.mock_pil.open().resize.reset_mock()\n self.mock_s3().upload.assert_called_once_with(FAKE_THUMB_BUCKET_NAME, FAKE_IMAGE_PATH1, self.mock_bytesio(), FAKE_CONTENT_TYPE)\n self.mock_s3().upload.reset_mock()\n image.upload_thumbnail(height=FAKE_THUMBNAIL_SIZE)\n self.mock_pil.open().resize.assert_called_once_with((225, 300), self.mock_pil.ANTIALIAS)\n self.mock_pil.open().resize().save.assert_called_once_with(self.mock_bytesio(), FAKE_IMAGE_FORMAT)\n self.mock_s3().upload.assert_called_once_with(FAKE_THUMB_BUCKET_NAME, FAKE_IMAGE_PATH1, self.mock_bytesio(), FAKE_CONTENT_TYPE)\n\n def test_upload_thumbnail_with_data(self):\n image = self._make_image(path=FAKE_IMAGE_PATH1, data=FAKE_IMAGE_DATA1, thumb_data=FAKE_IMAGE_DATA2)\n image.upload_thumbnail()\n self.mock_s3().upload.assert_called_once_with(FAKE_THUMB_BUCKET_NAME, FAKE_IMAGE_PATH1, self.mock_bytesio(), FAKE_CONTENT_TYPE)\n", "method_code": " def upload_thumbnail(self, width=None, height=None):\n if self.thumb_data:\n thumb_data = io.BytesIO(self.thumb_data)\n else:\n if not width and (not height) or (width and height):\n raise ArithmeticError('Must supply either width or height!')\n thumb_data = self._thumbnail(width, height)\n self.s3.upload(self.conf.THUMB_BUCKET_NAME, self.path, thumb_data, {'ContentType': self.thumb_type})\n ", "context": "class Image(object):\n def upload_thumbnail(self, width=None, height=None): ...\n def __init__(self, path, data, thumb_data=None, content_type=None, thumb_content_type=None): ...\n def upload(self): ...\n def _thumbnail(self, width=None, height=None): ...\n def get_colors(self): ...\n def get_dimensions(self): ...\n\n self.conf = config.get_config()\n self.s3 = clients.s3_client()\n self.path = path\n self.data = data\n self.thumb_data = thumb_data\n", "repository": "rm-you/tweench", "test_name": "test_upload_thumbnail", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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_000530.py"} {"focal_file": "archiver/image_handling.py", "focal_class": null, "focal_method": "get_colors", "tests": "import unittest\n\nclass Test_get_colors(unittest.TestCase):\n @mock.patch('archiver.image_handling.colorific')\n def test_get_colors(self, mock_colorific):\n fake_color = mock.Mock()\n fake_color.prominence = 0.5\n mock_colorific.extract_colors().colors = [fake_color]\n image = self._make_image(FAKE_IMAGE_PATH1, FAKE_IMAGE_DATA1)\n colors = image.get_colors()\n mock_colorific.extract_colors.called_once_with(self.mock_pil)\n self.assertEqual(colors, [{'prominence': 50, 'value': mock_colorific.rgb_to_hex()}])\n\n @mock.patch('archiver.image_handling.colorific')\n def test_get_colors_error(self, mock_colorific):\n mock_colorific.extract_colors.side_effect = ValueError\n image = self._make_image(FAKE_IMAGE_PATH1, FAKE_IMAGE_DATA1)\n colors = image.get_colors()\n self.assertIsNone(colors)\n", "method_code": " def get_colors(self):\n if self.pi:\n LOG.info(u'Analyzing color data for image...')\n try:\n colors = colorific.extract_colors(self.pi).colors\n return [{'value': colorific.rgb_to_hex(c.value), 'prominence': int(c.prominence * 100)} for c in colors]\n except:\n LOG.error(u'Exception while analyzing colors for image: {}'.format(self.path))\n else:\n LOG.info(u\"Can't analyze colors, no image data.\")\n ", "context": "class Image(object):\n def get_colors(self): ...\n def __init__(self, path, data, thumb_data=None, content_type=None, thumb_content_type=None): ...\n def upload(self): ...\n def upload_thumbnail(self, width=None, height=None): ...\n def _thumbnail(self, width=None, height=None): ...\n def get_dimensions(self): ...\n\n self.conf = config.get_config()\n self.s3 = clients.s3_client()\n self.path = path\n self.data = data\n self.thumb_data = thumb_data\n", "repository": "rm-you/tweench", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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_000531.py"} {"focal_file": "archiver/image_handling.py", "focal_class": null, "focal_method": "get_dimensions", "tests": "import unittest\n\nclass Test_get_dimensions(unittest.TestCase):\n def test_get_dimensions(self):\n image = self._make_image(FAKE_IMAGE_PATH1, FAKE_IMAGE_DATA1)\n self.mock_pil.open().size = (600, 800)\n dimensions = image.get_dimensions()\n self.assertEqual(dimensions, {'height': 600, 'width': 800})\n", "method_code": " def get_dimensions(self):\n if self.pi:\n LOG.info(u'Calculating dimensions for image...')\n return {'height': self.pi.size[0], 'width': self.pi.size[1]}\n LOG.info(u\"Can't calculate dimensions, no image data.\")\n ", "context": "class Image(object):\n def get_dimensions(self): ...\n def __init__(self, path, data, thumb_data=None, content_type=None, thumb_content_type=None): ...\n def upload(self): ...\n def upload_thumbnail(self, width=None, height=None): ...\n def _thumbnail(self, width=None, height=None): ...\n def get_colors(self): ...\n\n self.conf = config.get_config()\n self.s3 = clients.s3_client()\n self.path = path\n self.data = data\n self.thumb_data = thumb_data\n", "repository": "rm-you/tweench", "test_name": "test_get_dimensions", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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_000532.py"} {"focal_file": "archiver/image_handling.py", "focal_class": null, "focal_method": "_download_one_imgur", "tests": "import unittest\n\nclass Test_download_one_imgur(unittest.TestCase):\n @mock.patch('archiver.image_handling.Image')\n @requests_mock.mock()\n def test__download_one_imgur_object_exists(self, mock_image, mock_req):\n img1_ret = {'path': FAKE_IMAGE_PATH1, 'url': FAKE_IMAGE_URL1, 'dimensions': mock_image().get_dimensions(), 'colors': mock_image().get_colors()}\n self.mock_persistence().get_image.return_value = img1_ret\n self.mock_s3().object_exists.return_value = True\n image = self.dh._download_one_imgur(FAKE_IMAGE_URL1)\n self.assertEqual(mock_req.call_count, 0)\n self.assertEqual(image, img1_ret)\n", "method_code": " def _download_one_imgur(self, url):\n if not url:\n LOG.info(u'Imgur hash no longer valid.')\n return None\n name = url.split('/')[-1]\n path = '{hash}/{name}'.format(hash=hashlib.md5(url).hexdigest(), name=name)\n object_in_s3 = self.s3.object_exists(self.conf.IMAGE_BUCKET_NAME, path)\n object_in_db = self.persistence.get_image(path)\n if object_in_db and object_in_s3:\n return object_in_db\n LOG.info(u\"Downloading '{path}': {url}\".format(path=path, url=url))\n r = requests.get(url, stream=False)\n if r.status_code != 200:\n LOG.info(u'Imgur link could not be fetched, status code: {status}'.format(status=r.status_code))\n return {'url': url}\n image = self._handle_image_data(r.content, path)\n return {'url': url, 'path': path, 'dimensions': image.get_dimensions(), 'colors': image.get_colors()}\n ", "context": "class DownloadHandler(object):\n def _download_one_imgur(self, url): ...\n def __init__(self): ...\n def store_images(self, praw_post): ...\n def _single(self, image_id): ...\n def _album(self, album_id): ...\n def _hashes(self, hashes): ...\n def _gfycat(self, gfy_id): ...\n def _external(self, url): ...\n def _handle_image_data(self, data, path, thumb_data=None, content_type=None, thumb_content_type=None): ...\n\n self.conf = config.get_config()\n self.s3 = clients.s3_client()\n self.persistence = clients.persistence_client()\n self._regexes = collections.OrderedDict([(re.compile(constants.IMGUR_ALBUM, re.IGNORECASE), self._album), (re.compile(constants.IMGUR_GALLERY, re.IGNORECASE), self._album), (re.compile(constants.IMGUR_HASHES, re.IGNORECASE), self._hashes), (re.compile(constants.IMGUR_PAGE, re.IGNORECASE), self._single), (re.compile(constants.IMGUR_SINGLE, re.IGNORECASE), self._single), (re.compile(constants.GFYCAT, re.IGNORECASE), self._gfycat), (re.compile(constants.EXTERNAL, re.IGNORECASE), self._external)])\n self.gfycat = gfycat.GfycatClient()\n", "repository": "rm-you/tweench", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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_000533.py"} {"focal_file": "archiver/image_handling.py", "focal_class": "archiver.image_handling.DownloadHandler", "focal_method": "store_images", "tests": "import unittest\n\nclass Test_archiver_image_handling_DownloadHandler_store_images(unittest.TestCase):\n @mock.patch.object(image_handling.DownloadHandler, '_single')\n def test_store_images(self, mock_single):\n dh = image_handling.DownloadHandler()\n praw_post = mock.MagicMock()\n praw_post.url = FAKE_IMAGE_URL1\n praw_post.subreddit.display_name = FAKE_SUBREDDIT_NAME\n praw_post.author.name = FAKE_USERNAME\n praw_post.id = FAKE_POST_ID\n image_mock = mock.Mock()\n mock_single.return_value = [image_mock]\n images = dh.store_images(praw_post)\n mock_single.assert_called_once_with(FAKE_IMAGE_ID1)\n self.assertListEqual(images, [image_mock])\n", "method_code": " def store_images(self, praw_post):\n LOG.info(u'Determining type of image URL: {url}'.format(url=praw_post.url))\n images = []\n for regex in self._regexes:\n m = regex.match(praw_post.url)\n if m:\n images.extend(self._regexes[regex](*m.groups()))\n break\n return images\n ", "context": "class DownloadHandler(object):\n def store_images(self, praw_post): ...\n def __init__(self): ...\n def _single(self, image_id): ...\n def _album(self, album_id): ...\n def _hashes(self, hashes): ...\n def _download_one_imgur(self, url): ...\n def _gfycat(self, gfy_id): ...\n def _external(self, url): ...\n def _handle_image_data(self, data, path, thumb_data=None, content_type=None, thumb_content_type=None): ...\n\n self.conf = config.get_config()\n self.s3 = clients.s3_client()\n self.persistence = clients.persistence_client()\n self._regexes = collections.OrderedDict([(re.compile(constants.IMGUR_ALBUM, re.IGNORECASE), self._album), (re.compile(constants.IMGUR_GALLERY, re.IGNORECASE), self._album), (re.compile(constants.IMGUR_HASHES, re.IGNORECASE), self._hashes), (re.compile(constants.IMGUR_PAGE, re.IGNORECASE), self._single), (re.compile(constants.IMGUR_SINGLE, re.IGNORECASE), self._single), (re.compile(constants.GFYCAT, re.IGNORECASE), self._gfycat), (re.compile(constants.EXTERNAL, re.IGNORECASE), self._external)])\n self.gfycat = gfycat.GfycatClient()\n", "repository": "rm-you/tweench", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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_000534.py"} {"focal_file": "archiver/image_handling.py", "focal_class": null, "focal_method": "_single", "tests": "import unittest\n\nclass Test_single(unittest.TestCase):\n @mock.patch('archiver.image_handling.Image')\n @requests_mock.mock()\n def test__single(self, mock_image, mock_req):\n self.mock_imgur().get_image.return_value = FAKE_IMAGE_URL1\n mock_req.get(FAKE_IMAGE_URL1, content=FAKE_IMAGE_DATA1)\n images = self.dh._single(FAKE_IMAGE_ID1)\n self.mock_imgur().get_image.assert_called_once_with(FAKE_IMAGE_ID1)\n self.assertEqual(mock_req.call_count, 1)\n self.assertEqual(mock_req.request_history[0].url, FAKE_IMAGE_URL1)\n mock_image.assert_called_once_with(path=FAKE_IMAGE_PATH1, data=FAKE_IMAGE_DATA1, content_type=None, thumb_content_type=None, thumb_data=None)\n mock_image().upload.assert_called_once()\n mock_image().upload_thumbnail.assert_called_once_with(FAKE_THUMBNAIL_SIZE)\n img_ret = {'path': FAKE_IMAGE_PATH1, 'url': FAKE_IMAGE_URL1, 'dimensions': mock_image().get_dimensions(), 'colors': mock_image().get_colors()}\n self.assertListEqual(images, [img_ret])\n", "method_code": " def _single(self, image_id):\n LOG.info(u'Single imgur page detected: {page}'.format(page=image_id))\n image_url = self.imgur.get_image(image_id)\n image = self._download_one_imgur(image_url)\n return [image] if image is not None else []\n ", "context": "class DownloadHandler(object):\n def _single(self, image_id): ...\n def __init__(self): ...\n def store_images(self, praw_post): ...\n def _album(self, album_id): ...\n def _hashes(self, hashes): ...\n def _download_one_imgur(self, url): ...\n def _gfycat(self, gfy_id): ...\n def _external(self, url): ...\n def _handle_image_data(self, data, path, thumb_data=None, content_type=None, thumb_content_type=None): ...\n\n self.conf = config.get_config()\n self.s3 = clients.s3_client()\n self.persistence = clients.persistence_client()\n self._regexes = collections.OrderedDict([(re.compile(constants.IMGUR_ALBUM, re.IGNORECASE), self._album), (re.compile(constants.IMGUR_GALLERY, re.IGNORECASE), self._album), (re.compile(constants.IMGUR_HASHES, re.IGNORECASE), self._hashes), (re.compile(constants.IMGUR_PAGE, re.IGNORECASE), self._single), (re.compile(constants.IMGUR_SINGLE, re.IGNORECASE), self._single), (re.compile(constants.GFYCAT, re.IGNORECASE), self._gfycat), (re.compile(constants.EXTERNAL, re.IGNORECASE), self._external)])\n self.gfycat = gfycat.GfycatClient()\n", "repository": "rm-you/tweench", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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_000535.py"} {"focal_file": "archiver/image_handling.py", "focal_class": null, "focal_method": "_album", "tests": "import unittest\n\nclass Test_album(unittest.TestCase):\n @mock.patch('archiver.image_handling.Image')\n @requests_mock.mock()\n def test__album(self, mock_image, mock_req):\n self.mock_imgur().get_album.return_value = [FAKE_IMAGE_URL1, FAKE_IMAGE_URL2]\n mock_req.get(FAKE_IMAGE_URL1, content=FAKE_IMAGE_DATA1)\n mock_req.get(FAKE_IMAGE_URL2, content=FAKE_IMAGE_DATA2)\n images = self.dh._album(FAKE_IMAGE_ID1)\n self.mock_imgur().get_album.assert_called_once_with(FAKE_IMAGE_ID1)\n self.assertEqual(mock_req.call_count, 2)\n self.assertListEqual([mock_req.request_history[0].url, mock_req.request_history[1].url], [FAKE_IMAGE_URL1, FAKE_IMAGE_URL2])\n mock_image.assert_has_calls([mock.call(path=FAKE_IMAGE_PATH1, data=FAKE_IMAGE_DATA1, content_type=None, thumb_content_type=None, thumb_data=None), mock.call(path=FAKE_IMAGE_PATH2, data=FAKE_IMAGE_DATA2, content_type=None, thumb_content_type=None, thumb_data=None)], any_order=True)\n self.assertEqual(mock_image().upload.call_count, 2)\n self.assertEqual(mock_image().upload_thumbnail.call_count, 2)\n mock_image().upload.assert_has_calls([mock.call(), mock.call()])\n mock_image().upload_thumbnail.assert_has_calls([mock.call(FAKE_THUMBNAIL_SIZE), mock.call(FAKE_THUMBNAIL_SIZE)])\n img1_ret = {'path': FAKE_IMAGE_PATH1, 'url': FAKE_IMAGE_URL1, 'dimensions': mock_image().get_dimensions(), 'colors': mock_image().get_colors()}\n img2_ret = {'path': FAKE_IMAGE_PATH2, 'url': FAKE_IMAGE_URL2, 'dimensions': mock_image().get_dimensions(), 'colors': mock_image().get_colors()}\n self.assertListEqual(images, [img1_ret, img2_ret])\n", "method_code": " def _album(self, album_id):\n LOG.info(u'Album detected: {album_id}'.format(album_id=album_id))\n image_urls = self.imgur.get_album(album_id)\n images = [self._download_one_imgur(url) for url in image_urls if url is not None]\n return [image for image in images if image is not None]\n ", "context": "class DownloadHandler(object):\n def _album(self, album_id): ...\n def __init__(self): ...\n def store_images(self, praw_post): ...\n def _single(self, image_id): ...\n def _hashes(self, hashes): ...\n def _download_one_imgur(self, url): ...\n def _gfycat(self, gfy_id): ...\n def _external(self, url): ...\n def _handle_image_data(self, data, path, thumb_data=None, content_type=None, thumb_content_type=None): ...\n\n self.conf = config.get_config()\n self.s3 = clients.s3_client()\n self.persistence = clients.persistence_client()\n self._regexes = collections.OrderedDict([(re.compile(constants.IMGUR_ALBUM, re.IGNORECASE), self._album), (re.compile(constants.IMGUR_GALLERY, re.IGNORECASE), self._album), (re.compile(constants.IMGUR_HASHES, re.IGNORECASE), self._hashes), (re.compile(constants.IMGUR_PAGE, re.IGNORECASE), self._single), (re.compile(constants.IMGUR_SINGLE, re.IGNORECASE), self._single), (re.compile(constants.GFYCAT, re.IGNORECASE), self._gfycat), (re.compile(constants.EXTERNAL, re.IGNORECASE), self._external)])\n self.gfycat = gfycat.GfycatClient()\n", "repository": "rm-you/tweench", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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_000536.py"} {"focal_file": "archiver/image_handling.py", "focal_class": null, "focal_method": "_hashes", "tests": "import unittest\n\nclass Test_hashes(unittest.TestCase):\n @mock.patch('archiver.image_handling.Image')\n @requests_mock.mock()\n def test__hashes(self, mock_image, mock_req):\n self.mock_imgur().get_image.side_effect = [FAKE_IMAGE_URL1, FAKE_IMAGE_URL2]\n mock_req.get(FAKE_IMAGE_URL1, content=FAKE_IMAGE_DATA1)\n mock_req.get(FAKE_IMAGE_URL2, content=FAKE_IMAGE_DATA2)\n images = self.dh._hashes(FAKE_IMAGE_HASHES)\n self.mock_imgur().get_image.assert_has_calls([mock.call(FAKE_IMAGE_ID1), mock.call(FAKE_IMAGE_ID2)])\n self.assertEqual(mock_req.call_count, 2)\n self.assertListEqual([mock_req.request_history[0].url, mock_req.request_history[1].url], [FAKE_IMAGE_URL1, FAKE_IMAGE_URL2])\n mock_image.assert_has_calls([mock.call(path=FAKE_IMAGE_PATH1, data=FAKE_IMAGE_DATA1, content_type=None, thumb_content_type=None, thumb_data=None), mock.call(path=FAKE_IMAGE_PATH2, data=FAKE_IMAGE_DATA2, content_type=None, thumb_content_type=None, thumb_data=None)], any_order=True)\n self.assertEqual(mock_image().upload.call_count, 2)\n self.assertEqual(mock_image().upload_thumbnail.call_count, 2)\n mock_image().upload.assert_has_calls([mock.call(), mock.call()])\n mock_image().upload_thumbnail.assert_has_calls([mock.call(FAKE_THUMBNAIL_SIZE), mock.call(FAKE_THUMBNAIL_SIZE)])\n img1_ret = {'path': FAKE_IMAGE_PATH1, 'url': FAKE_IMAGE_URL1, 'dimensions': mock_image().get_dimensions(), 'colors': mock_image().get_colors()}\n img2_ret = {'path': FAKE_IMAGE_PATH2, 'url': FAKE_IMAGE_URL2, 'dimensions': mock_image().get_dimensions(), 'colors': mock_image().get_colors()}\n self.assertListEqual(images, [img1_ret, img2_ret])\n", "method_code": " def _hashes(self, hashes):\n hashes = hashes.strip(',').split(',')\n LOG.info(u'Image hashes detected: {hashes}'.format(hashes=hashes))\n image_urls = [self.imgur.get_image(image_id) for image_id in hashes]\n images = [self._download_one_imgur(url) for url in image_urls if url is not None]\n return [image for image in images if image is not None]\n ", "context": "class DownloadHandler(object):\n def _hashes(self, hashes): ...\n def __init__(self): ...\n def store_images(self, praw_post): ...\n def _single(self, image_id): ...\n def _album(self, album_id): ...\n def _download_one_imgur(self, url): ...\n def _gfycat(self, gfy_id): ...\n def _external(self, url): ...\n def _handle_image_data(self, data, path, thumb_data=None, content_type=None, thumb_content_type=None): ...\n\n self.conf = config.get_config()\n self.s3 = clients.s3_client()\n self.persistence = clients.persistence_client()\n self._regexes = collections.OrderedDict([(re.compile(constants.IMGUR_ALBUM, re.IGNORECASE), self._album), (re.compile(constants.IMGUR_GALLERY, re.IGNORECASE), self._album), (re.compile(constants.IMGUR_HASHES, re.IGNORECASE), self._hashes), (re.compile(constants.IMGUR_PAGE, re.IGNORECASE), self._single), (re.compile(constants.IMGUR_SINGLE, re.IGNORECASE), self._single), (re.compile(constants.GFYCAT, re.IGNORECASE), self._gfycat), (re.compile(constants.EXTERNAL, re.IGNORECASE), self._external)])\n self.gfycat = gfycat.GfycatClient()\n", "repository": "rm-you/tweench", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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_000537.py"} {"focal_file": "archiver/image_handling.py", "focal_class": null, "focal_method": "_external", "tests": "import unittest\n\nclass Test_external(unittest.TestCase):\n @mock.patch('archiver.image_handling.Image')\n @requests_mock.mock()\n def test__external(self, mock_image, mock_req):\n head = structures.CaseInsensitiveDict({'Content-Type': 'image/jpeg'})\n mock_req.get(FAKE_IMAGE_URL1, content=FAKE_IMAGE_DATA1, headers=head)\n images = self.dh._external(FAKE_IMAGE_URL1)\n self.assertEqual(mock_req.call_count, 1)\n self.assertEqual(mock_req.request_history[0].url, FAKE_IMAGE_URL1)\n mock_image.assert_called_once_with(path=FAKE_IMAGE_PATH1, data=FAKE_IMAGE_DATA1, content_type=None, thumb_content_type=None, thumb_data=None)\n mock_image().upload.assert_called_once()\n mock_image().upload_thumbnail.assert_called_once_with(FAKE_THUMBNAIL_SIZE)\n img_ret = {'path': FAKE_IMAGE_PATH1, 'url': FAKE_IMAGE_URL1}\n self.assertListEqual(images, [img_ret])\n", "method_code": " def _external(self, url):\n LOG.info(u'Generic image URL detected: {url}'.format(url=url))\n name = url.split('/')[-1]\n path = '{hash}/{name}'.format(hash=hashlib.md5(url).hexdigest(), name=name)\n if not self.s3.object_exists(self.conf.IMAGE_BUCKET_NAME, path):\n try:\n r = requests.get(url, stream=False)\n except requests.exceptions.ConnectionError:\n return [{'url': url}]\n if r.status_code != 200 or r.headers['content-type'].startswith('text'):\n LOG.info(u'Failed to fetch ({status}): {url}'.format(status=r.status_code, url=url))\n return [{'url': url}]\n self._handle_image_data(r.content, path)\n return [{'url': url, 'path': path}]\n ", "context": "class DownloadHandler(object):\n def _external(self, url): ...\n def __init__(self): ...\n def store_images(self, praw_post): ...\n def _single(self, image_id): ...\n def _album(self, album_id): ...\n def _hashes(self, hashes): ...\n def _download_one_imgur(self, url): ...\n def _gfycat(self, gfy_id): ...\n def _handle_image_data(self, data, path, thumb_data=None, content_type=None, thumb_content_type=None): ...\n\n self.conf = config.get_config()\n self.s3 = clients.s3_client()\n self.persistence = clients.persistence_client()\n self._regexes = collections.OrderedDict([(re.compile(constants.IMGUR_ALBUM, re.IGNORECASE), self._album), (re.compile(constants.IMGUR_GALLERY, re.IGNORECASE), self._album), (re.compile(constants.IMGUR_HASHES, re.IGNORECASE), self._hashes), (re.compile(constants.IMGUR_PAGE, re.IGNORECASE), self._single), (re.compile(constants.IMGUR_SINGLE, re.IGNORECASE), self._single), (re.compile(constants.GFYCAT, re.IGNORECASE), self._gfycat), (re.compile(constants.EXTERNAL, re.IGNORECASE), self._external)])\n self.gfycat = gfycat.GfycatClient()\n", "repository": "rm-you/tweench", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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_000538.py"} {"focal_file": "archiver/image_handling.py", "focal_class": null, "focal_method": "_gfycat", "tests": "import unittest\n\nclass Test_gfycat(unittest.TestCase):\n @mock.patch('archiver.image_handling.Image')\n @requests_mock.mock()\n def test__gfycat(self, mock_image, mock_req):\n self.mock_gfycat().query_gfy.return_value = {'gfyItem': {'webmUrl': FAKE_GFY_WEBM, 'max2mbGif': FAKE_GFY_THUMB, 'width': FAKE_GFY_IMAGE_WIDTH, 'height': FAKE_GFY_IMAGE_HEIGHT}}\n head1 = structures.CaseInsensitiveDict({'Content-Type': 'video/webm'})\n head2 = structures.CaseInsensitiveDict({'Content-Type': 'image/gif'})\n mock_req.get(FAKE_GFY_WEBM, content=FAKE_IMAGE_DATA1, headers=head1)\n mock_req.get(FAKE_GFY_THUMB, content=FAKE_IMAGE_DATA2, headers=head2)\n images = self.dh._gfycat(FAKE_GFY_ID)\n self.assertEqual(mock_req.call_count, 2)\n self.assertListEqual([mock_req.request_history[0].url, mock_req.request_history[1].url], [FAKE_GFY_WEBM, FAKE_GFY_THUMB])\n mock_image.assert_called_once_with(path=FAKE_GFY_PATH, data=FAKE_IMAGE_DATA1, thumb_data=FAKE_IMAGE_DATA2, content_type=FAKE_CONTENT_TYPE_WEBM, thumb_content_type=FAKE_CONTENT_TYPE_GIF)\n mock_image().upload.assert_called_once()\n mock_image().upload_thumbnail.assert_called_once()\n img_ret = {'path': FAKE_GFY_PATH, 'url': FAKE_GFY_WEBM, 'dimensions': {'height': FAKE_GFY_IMAGE_HEIGHT, 'width': FAKE_GFY_IMAGE_WIDTH}}\n self.assertListEqual(images, [img_ret])\n", "method_code": " def _gfycat(self, gfy_id):\n LOG.info(u'Gfycat detected: {gfy_id}'.format(gfy_id=gfy_id))\n gfy_data = self.gfycat.query_gfy(gfy_id)\n if gfy_data and 'gfyItem' in gfy_data:\n url = gfy_data['gfyItem']['webmUrl']\n r1 = requests.get(url, stream=False)\n if r1.status_code != 200:\n LOG.info(u'Gfycat image could not be downloaded. Status code: {code}'.format(code=r1.status_code))\n return []\n thumb_url = gfy_data['gfyItem'].get('max2mbGif') or gfy_data['gfyItem'].get('max5mbGif')\n r2 = requests.get(thumb_url, stream=False)\n name = url.split('/')[-1]\n path = '{hash}/{name}'.format(hash=hashlib.md5(url).hexdigest(), name=name)\n self._handle_image_data(data=r1.content, thumb_data=r2.content, path=path, content_type=r1.headers['content-type'], thumb_content_type=r2.headers['content-type'])\n return [{'url': url, 'path': path, 'dimensions': {'height': gfy_data['gfyItem']['height'], 'width': gfy_data['gfyItem']['width']}}]\n ", "context": "class DownloadHandler(object):\n def _gfycat(self, gfy_id): ...\n def __init__(self): ...\n def store_images(self, praw_post): ...\n def _single(self, image_id): ...\n def _album(self, album_id): ...\n def _hashes(self, hashes): ...\n def _download_one_imgur(self, url): ...\n def _external(self, url): ...\n def _handle_image_data(self, data, path, thumb_data=None, content_type=None, thumb_content_type=None): ...\n\n self.conf = config.get_config()\n self.s3 = clients.s3_client()\n self.persistence = clients.persistence_client()\n self._regexes = collections.OrderedDict([(re.compile(constants.IMGUR_ALBUM, re.IGNORECASE), self._album), (re.compile(constants.IMGUR_GALLERY, re.IGNORECASE), self._album), (re.compile(constants.IMGUR_HASHES, re.IGNORECASE), self._hashes), (re.compile(constants.IMGUR_PAGE, re.IGNORECASE), self._single), (re.compile(constants.IMGUR_SINGLE, re.IGNORECASE), self._single), (re.compile(constants.GFYCAT, re.IGNORECASE), self._gfycat), (re.compile(constants.EXTERNAL, re.IGNORECASE), self._external)])\n self.gfycat = gfycat.GfycatClient()\n", "repository": "rm-you/tweench", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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_000539.py"} {"focal_file": "archiver/messages.py", "focal_class": "archiver.messages.PostMessage", "focal_method": "enqueue", "tests": "import unittest\n\nclass Test_archiver_messages_PostMessage_enqueue(unittest.TestCase):\n def test_enqueue(self):\n message = messages.PostMessage(FAKE_POST_LINK)\n mock_queue = mock.Mock(spec=clients.SQSClient)\n message.enqueue(mock_queue)\n mock_queue.send_message.assert_called_once_with(str(message))\n", "method_code": " def enqueue(self, client):\n LOG.debug(u'Enqueueing message: {msg}'.format(msg=str(self)))\n client.send_message(str(self))\n ", "context": "class QueueMessage(object):\n def enqueue(self, client): ...\n def finish(self, client): ...\n def __str__(self): ...\n\n id = None\n type = None\n body = None\n", "repository": "rm-you/tweench", "test_name": "test_enqueue", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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_000540.py"} {"focal_file": "archiver/messages.py", "focal_class": "archiver.messages.PostMessage", "focal_method": "finish", "tests": "import unittest\n\nclass Test_archiver_messages_PostMessage_finish(unittest.TestCase):\n def test_finish(self):\n message = messages.PostMessage(FAKE_POST_LINK, mid=FAKE_MESSAGE_ID)\n mock_queue = mock.Mock(spec=clients.SQSClient)\n message.finish(mock_queue)\n mock_queue.delete_message.assert_called_once_with(message.id)\n", "method_code": " def finish(self, client):\n if not self.id:\n raise AttributeError('Message has no ID!')\n LOG.debug(u'Deleting message: {msg}'.format(msg=str(self)))\n client.delete_message(self.id)\n ", "context": "class QueueMessage(object):\n def finish(self, client): ...\n def enqueue(self, client): ...\n def __str__(self): ...\n\n id = None\n type = None\n body = None\n", "repository": "rm-you/tweench", "test_name": "test_finish", "smells": [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 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_000541.py"} {"focal_file": "cr8/cli.py", "focal_class": null, "focal_method": "dicts_from_stdin", "tests": "import unittest\n\nclass Test_dicts_from_stdin(unittest.TestCase):\n @patch('sys.stdin', new_callable=lambda: io.StringIO('{\"name\": \"n1\"}\\n{\"name\": \"n2\"}'))\n def test_dicts_from_stdin_multi_json(self, stdin):\n stdin.isatty = lambda: False\n dicts = iter(dicts_from_stdin())\n d1 = next(dicts)\n d2 = next(dicts)\n self.assertEqual({'name': 'n1'}, d1)\n self.assertEqual({'name': 'n2'}, d2)\n self.assertRaises(StopIteration, next, dicts)\n\n @patch('sys.stdin', new_callable=lambda: io.StringIO('{\\n \"name\": \"n1\"\\n}'))\n def test_dicts_from_stdin_single_json(self, stdin):\n stdin.isatty = lambda: False\n dicts = iter(dicts_from_stdin())\n d1 = next(dicts)\n self.assertEqual({'name': 'n1'}, d1)\n self.assertRaises(StopIteration, next, dicts)\n\n @patch('sys.stdin', new_callable=lambda: io.StringIO('[\\n{\\n\"name\": \"n1\"\\n},\\n{\\n\"name\": \"n2\"\\n}\\n]'))\n def test_dicts_from_json_list_of_obj(self, stdin):\n dicts = iter(dicts_from_stdin())\n d1 = next(dicts)\n d2 = next(dicts)\n self.assertEqual({'name': 'n1'}, d1)\n self.assertEqual({'name': 'n2'}, d2)\n self.assertRaises(StopIteration, next, dicts)\n", "method_code": "def dicts_from_stdin():\n if sys.stdin.isatty():\n raise SystemExit('Expected json input via stdin')\n yield from dicts_from_lines(sys.stdin)", "context": "def dicts_from_stdin(): ...\ndef to_int(s: str) -> int: ...\ndef lines_from_stdin(default=None): ...\ndef dicts_from_lines(lines): ...\ndef dicts_from_stdin(): ...\n", "repository": "mfussenegger/cr8", "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_000542.py"} {"focal_file": "cr8/cli.py", "focal_class": null, "focal_method": "lines_from_stdin", "tests": "import unittest\n\nclass Test_lines_from_stdin(unittest.TestCase):\n @patch('sys.stdin', new_callable=io.StringIO)\n def test_lines_from_stdin_isatty_but_default(self, stdin):\n stdin.isatty = lambda: True\n lines = list(lines_from_stdin('default'))\n self.assertEqual(['default'], lines)\n", "method_code": "def lines_from_stdin(default=None):\n if sys.stdin.isatty():\n if default:\n yield default\n return\n for line in sys.stdin:\n yield line", "context": "def lines_from_stdin(default=None): ...\ndef to_int(s: str) -> int: ...\ndef lines_from_stdin(default=None): ...\ndef dicts_from_lines(lines): ...\ndef dicts_from_stdin(): ...\n", "repository": "mfussenegger/cr8", "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_000543.py"} {"focal_file": "cr8/cli.py", "focal_class": null, "focal_method": "dicts_from_lines", "tests": "import unittest\n\nclass Test_dicts_from_lines(unittest.TestCase):\n def test_dicts_from_iterable(self):\n d = next(iter(dicts_from_lines(['{\\n', ' \"name\": 10\\n', '}\\n'])))\n self.assertEqual(d, {'name': 10})\n\n def test_dicts_from_iterable_with_empty_lines(self):\n d = list(dicts_from_lines(['', '{\"name\": 10}', '\\n', '', '{\"name\": 20}\\n\\n']))\n self.assertEqual(d[0], {'name': 10})\n self.assertEqual(d[1], {'name': 20})\n\n def test_dicts_from_iterator(self):\n d = next(iter(dicts_from_lines(iter(['{\\n', ' \"name\": 10\\n', '}\\n']))))\n self.assertEqual(d, {'name': 10})\n", "method_code": "def dicts_from_lines(lines):\n \"\"\" returns a generator producing dicts from json lines\n\n 1 JSON object per line is supported:\n\n {\"name\": \"n1\"}\n {\"name\": \"n2\"}\n\n Or 1 JSON object:\n\n {\n \"name\": \"n1\"\n }\n\n Or a list of JSON objects:\n\n [\n {\"name\": \"n1\"},\n {\"name\": \"n2\"},\n ]\n\n Or a list of JSON objects in a single line:\n\n [{\"name\": \"n1\"}, {\"name\": \"n2\"}]\n \"\"\"\n lines = iter(lines)\n for line in lines:\n line = line.strip()\n if not line:\n continue\n try:\n data = loads(line)\n if isinstance(data, list):\n yield from data\n else:\n yield data\n except ValueError:\n content = line + ''.join(lines)\n dicts = loads(content)\n if isinstance(dicts, list):\n yield from dicts\n else:\n yield dicts", "context": "def dicts_from_lines(lines): ...\ndef to_int(s: str) -> int: ...\ndef lines_from_stdin(default=None): ...\ndef dicts_from_lines(lines): ...\ndef dicts_from_stdin(): ...\n", "repository": "mfussenegger/cr8", "test_name": "test_dicts_from_iterable", "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_000544.py"} {"focal_file": "cr8/engine.py", "focal_class": "Result", "focal_method": "eval_fail_if", "tests": "import unittest\n\nclass Test_Result_eval_fail_if(unittest.TestCase):\n def test_fail_if_fails(self):\n timed_stats = TimedStats(1, 2, Stats())\n result = Result({}, 'select name', timed_stats, 1)\n with self.assertRaises(FailIf):\n eval_fail_if(\"'{statement}' == 'select name'\", result)\n", "method_code": "def eval_fail_if(fail_if: str, result):\n fail_if = fail_if.format(**result.as_dict())\n if eval(fail_if):\n raise FailIf('Expression failed: ' + fail_if)", "context": "def eval_fail_if(fail_if: str, result): ...\ndef eval_fail_if(fail_if: str, result): ...\ndef run_and_measure(f, statements, concurrency, num_items=None, sampler=None): ...\ndef _generate_statements(stmt, args, iterations, duration): ...\n", "repository": "mfussenegger/cr8", "test_name": "test_fail_if_fails", "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_000545.py"} {"focal_file": "cr8/insert_fake_data.py", "focal_class": "Column", "focal_method": "provider_for_column", "tests": "import unittest\n\nclass Test_Column_provider_for_column(unittest.TestCase):\n def test_fake_provider_for_name_column(self):\n provider = self.f.provider_for_column(Column('name', 'string', None))\n self.assertEqual(provider(), 'Allison Hill')\n\n def test_fake_provider_for_string_id_column(self):\n provider = self.f.provider_for_column(Column('id', 'string', None))\n self.assertEqual(len(provider()), len('8731cdac-8671-441d-b07f-e766ffe303e1'))\n\n def test_fake_provider_for_int_id_column(self):\n provider = self.f.provider_for_column(Column('id', 'integer', None))\n self.assertEqual(provider(), 1)\n self.assertEqual(provider(), 2)\n provider2 = self.f.provider_for_column(Column('id', 'integer', None))\n self.assertEqual(provider2(), 1)\n\n def test_fake_provider_for_long_id_column(self):\n provider = self.f.provider_for_column(Column('id', 'long', None))\n self.assertEqual(provider(), 1)\n\n def test_type_default_provider_for_unknown_int_column(self):\n provider = self.f.provider_for_column(Column('column_name_without_provider', 'integer', None))\n self.assertEqual(provider(), 598833565)\n\n def test_invalid_provider_for_column(self):\n msg = 'No fake provider found for column \"x\" with type \"y\"'\n with self.assertRaises(ValueError) as cm:\n self.f.provider_for_column(Column('x', 'y', None))\n self.assertEqual(str(cm.exception), msg)\n\n def test_provider_for_object_column_creates_empty_dicts(self):\n provider = self.f.provider_for_column(Column('obj', 'object', None))\n self.assertEqual(provider(), dict())\n\n def test_provider_for_string_array(self):\n provider = self.f.provider_for_column(Column('foo', 'string_array', None))\n value = provider()\n self.assertEqual(len(value), 40)\n self.assertEqual(value[0], 'born')\n\n def test_provider_for_bitstring(self):\n provider = self.f.provider_for_column(Column('foo', 'bit', 4))\n value = provider()\n self.assertEqual(value, '0110')\n provider = self.f.provider_for_column(Column('foo', 'bit', 8))\n value = provider()\n self.assertEqual(value, '11110100')\n", "method_code": " def provider_for_column(self, column):\n provider = getattr(self.fake, column.name, None)\n if provider:\n return provider\n custom_provider = self._custom.get(column.name)\n if custom_provider:\n return custom_provider(self.fake, column)\n alternative = self._mapping.get((column.name, column.type_name))\n if not alternative:\n alternative = self._provider_for_type(column)\n if not alternative:\n msg = 'No fake provider found for column \"{col}\" with type \"{type}\"'\n raise ValueError(msg.format(col=column.name, type=column.type_name))\n return alternative(self.fake, column)\n ", "context": "class DataFaker():\n def provider_for_column(self, column): ...\n def __init__(self): ...\n def _provider_for_type(self, column: Column): ...\n def provider_from_mapping(self, column_name, mapping): ...\n\n self.fake = Factory.create()\n\n _mapping = {('id', 'string'): lambda f, ctx: f.uuid4, ('id', 'text'): lambda f, ctx: f.uuid4, ('id', 'integer'): auto_inc, ('id', 'long'): auto_inc, ('id', 'bigint'): auto_inc}\n _type_default = {'byte': lambda f, col: partial(f.random_int, min=-128, max=127), 'char': lambda f, col: partial(f.random_int, min=-128, max=127), 'short': _gen_short, 'smallint': _gen_short, 'integer': lambda f, col: partial(f.random_int, min=-2147483648, max=2147483647), 'long': _gen_long, 'bigint': _gen_long, 'float': lambda f, col: f.pyfloat, 'real': lambda f, col: f.pyfloat, 'double': lambda f, col: f.pydecimal, 'double precision': lambda f, col: f.pydecimal, 'ip': lambda f, col: f.ipv4, 'timestamp': lambda f, col: partial(f.date_time_between, start_date='-2y', end_date='now'), 'timestamp with time zone': lambda f, col: partial(f.date_time_between, start_date='-2y', end_date='now'), 'timestamp without time zone': lambda f, col: partial(f.date_time_between, start_date='-2y', end_date='now'), 'string': lambda f, col: f.word, 'text': lambda f, col: f.word, 'boolean': lambda f, col: f.boolean, 'geo_point': lambda f, col: f.geo_point, 'geo_shape': lambda f, col: f.geo_shape, 'object': lambda f, col: dict, 'bit': _gen_bit}\n _custom = {'auto_inc': auto_inc}\n", "repository": "mfussenegger/cr8", "test_name": "test_fake_provider_for_name_column", "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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000546.py"} {"focal_file": "cr8/insert_fake_data.py", "focal_class": null, "focal_method": "provider_from_mapping", "tests": "import unittest\n\nclass Test_provider_from_mapping(unittest.TestCase):\n def test_provider_from_mapping(self):\n mapping = {'x': ['random_int', [10, 20]]}\n provider = self.f.provider_from_mapping('x', mapping)\n self.assertEqual(provider(), 20)\n", "method_code": " def provider_from_mapping(self, column_name, mapping):\n key = mapping[column_name]\n args = None\n if isinstance(key, list):\n key, args = key\n provider = getattr(self.fake, key, None)\n if not provider:\n raise KeyError('No fake provider with name \"%s\" found' % (key,))\n if args:\n provider = partial(provider, *args)\n return provider\n ", "context": "class DataFaker():\n def provider_from_mapping(self, column_name, mapping): ...\n def __init__(self): ...\n def _provider_for_type(self, column: Column): ...\n def provider_for_column(self, column): ...\n\n self.fake = Factory.create()\n\n _mapping = {('id', 'string'): lambda f, ctx: f.uuid4, ('id', 'text'): lambda f, ctx: f.uuid4, ('id', 'integer'): auto_inc, ('id', 'long'): auto_inc, ('id', 'bigint'): auto_inc}\n _type_default = {'byte': lambda f, col: partial(f.random_int, min=-128, max=127), 'char': lambda f, col: partial(f.random_int, min=-128, max=127), 'short': _gen_short, 'smallint': _gen_short, 'integer': lambda f, col: partial(f.random_int, min=-2147483648, max=2147483647), 'long': _gen_long, 'bigint': _gen_long, 'float': lambda f, col: f.pyfloat, 'real': lambda f, col: f.pyfloat, 'double': lambda f, col: f.pydecimal, 'double precision': lambda f, col: f.pydecimal, 'ip': lambda f, col: f.ipv4, 'timestamp': lambda f, col: partial(f.date_time_between, start_date='-2y', end_date='now'), 'timestamp with time zone': lambda f, col: partial(f.date_time_between, start_date='-2y', end_date='now'), 'timestamp without time zone': lambda f, col: partial(f.date_time_between, start_date='-2y', end_date='now'), 'string': lambda f, col: f.word, 'text': lambda f, col: f.word, 'boolean': lambda f, col: f.boolean, 'geo_point': lambda f, col: f.geo_point, 'geo_shape': lambda f, col: f.geo_shape, 'object': lambda f, col: dict, 'bit': _gen_bit}\n _custom = {'auto_inc': auto_inc}\n", "repository": "mfussenegger/cr8", "test_name": "test_provider_from_mapping", "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_000547.py"} {"focal_file": "cr8/misc.py", "focal_class": null, "focal_method": "as_bulk_queries", "tests": "import unittest\n\nclass Test_as_bulk_queries(unittest.TestCase):\n def test_as_bulk_queries(self):\n queries = [('x', (1, 2)), ('x', (3, 4)), ('x', (5, 6)), ('y', (1, 2))]\n bulk_queries = sorted(list(misc.as_bulk_queries(queries, 2)))\n self.assertEqual(bulk_queries, [('x', [(1, 2), (3, 4)]), ('x', [(5, 6)]), ('y', [(1, 2)])])\n", "method_code": "def as_bulk_queries(queries, bulk_size):\n \"\"\"Group a iterable of (stmt, args) by stmt into (stmt, bulk_args).\n\n bulk_args will be a list of the args grouped by stmt.\n\n len(bulk_args) will be <= bulk_size\n \"\"\"\n stmt_dict = defaultdict(list)\n for stmt, args in queries:\n bulk_args = stmt_dict[stmt]\n bulk_args.append(args)\n if len(bulk_args) == bulk_size:\n yield (stmt, bulk_args)\n del stmt_dict[stmt]\n for stmt, bulk_args in stmt_dict.items():\n yield (stmt, bulk_args)", "context": "def as_bulk_queries(queries, bulk_size): ...\ndef init_logging(log): ...\ndef try_len(o: Any) -> Optional[int]: ...\ndef parse_version(version: str) -> tuple: ...\ndef parse_table(fq_table: str) -> Tuple[str, str]: ...\ndef as_bulk_queries(queries, bulk_size): ...\ndef get_lines(filename: str) -> Iterator[str]: ...\ndef as_statements(lines: Iterator[str]) -> Iterator[str]: ...\ndef break_iterable(iterable, pred): ...\n", "repository": "mfussenegger/cr8", "test_name": "test_as_bulk_queries", "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_000548.py"} {"focal_file": "cr8/reindex.py", "focal_class": null, "focal_method": "reindex", "tests": "import unittest\n\nclass Test_reindex(unittest.TestCase):\n def test_reindex(self):\n crate_v3 = CrateNode(crate_dir=get_crate('3.x.x'), keep_data=True, settings=self.crate_settings)\n self._to_stop.append(crate_v3)\n crate_v3.start()\n with client(crate_v3.http_url) as c:\n aio.run(c.execute, 'create table t (x int)')\n args = ((1,), (2,), (3,))\n aio.run(c.execute_many, 'insert into t (x) values (?)', args)\n crate_v3.stop()\n self._to_stop.remove(crate_v3)\n crate_v4 = CrateNode(crate_dir=get_crate('4.0.3'), keep_data=True, settings=self.crate_settings)\n self._to_stop.append(crate_v4)\n crate_v4.start()\n reindex(crate_v4.http_url)\n with client(crate_v4.http_url) as c:\n result = aio.run(c.execute, \"SELECT version FROM information_schema.tables WHERE table_name = 't'\")\n version = result['rows'][0][0]\n self.assertEqual(version, {'upgraded': None, 'created': '4.0.3'})\n cnt = aio.run(c.execute, 'SELECT count(*) FROM t')['rows'][0][0]\n self.assertEqual(cnt, 3)\n", "method_code": "def reindex(hosts=None):\n with clients.client(hosts) as client:\n run(_async_reindex, client)", "context": "@argh.arg('--hosts', help='crate hosts', type=str, required=True)\ndef reindex(hosts=None): ...\ndef _fetch_tables_to_upgrade(client, version): ...\ndef _show_create_table(client, fq_table): ...\ndef _reindex_table(client, schema, table, create_table, column_names): ...\ndef _fetch_column_names(client, schema, table): ...\ndef _async_reindex(client): ...\ndef reindex(hosts=None): ...\ndef main(): ...\n", "repository": "mfussenegger/cr8", "test_name": "test_reindex", "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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000549.py"} {"focal_file": "libcloud/httplib_ssl.py", "focal_class": null, "focal_method": "_verify_hostname", "tests": "import unittest\n\nclass Test_verify_hostname(unittest.TestCase):\n def test_verify_hostname(self):\n cert1 = {'notAfter': 'Feb 16 16:54:50 2013 GMT', 'subject': ((('countryName', 'US'),), (('stateOrProvinceName', 'Delaware'),), (('localityName', 'Wilmington'),), (('organizationName', 'Python Software Foundation'),), (('organizationalUnitName', 'SSL'),), (('commonName', 'somemachine.python.org'),))}\n cert2 = {'notAfter': 'Feb 16 16:54:50 2013 GMT', 'subject': ((('countryName', 'US'),), (('stateOrProvinceName', 'Delaware'),), (('localityName', 'Wilmington'),), (('organizationName', 'Python Software Foundation'),), (('organizationalUnitName', 'SSL'),), (('commonName', 'somemachine.python.org'),)), 'subjectAltName': (('DNS', 'foo.alt.name'), ('DNS', 'foo.alt.name.1'))}\n cert3 = {'notAfter': 'Feb 16 16:54:50 2013 GMT', 'subject': ((('countryName', 'US'),), (('stateOrProvinceName', 'Delaware'),), (('localityName', 'Wilmington'),), (('organizationName', 'Python Software Foundation'),), (('organizationalUnitName', 'SSL'),), (('commonName', 'python.org'),))}\n cert4 = {'notAfter': 'Feb 16 16:54:50 2013 GMT', 'subject': ((('countryName', 'US'),), (('stateOrProvinceName', 'Delaware'),), (('localityName', 'Wilmington'),), (('organizationName', 'Python Software Foundation'),), (('organizationalUnitName', 'SSL'),), (('commonName', '*.api.joyentcloud.com'),))}\n self.assertFalse(self.httplib_object._verify_hostname(hostname='invalid', cert=cert1))\n self.assertFalse(self.httplib_object._verify_hostname(hostname='machine.python.org', cert=cert1))\n self.assertFalse(self.httplib_object._verify_hostname(hostname='foomachine.python.org', cert=cert1))\n self.assertFalse(self.httplib_object._verify_hostname(hostname='somesomemachine.python.org', cert=cert1))\n self.assertFalse(self.httplib_object._verify_hostname(hostname='somemachine.python.orga', cert=cert1))\n self.assertFalse(self.httplib_object._verify_hostname(hostname='somemachine.python.org.org', cert=cert1))\n self.assertTrue(self.httplib_object._verify_hostname(hostname='somemachine.python.org', cert=cert1))\n self.assertFalse(self.httplib_object._verify_hostname(hostname='invalid', cert=cert2))\n self.assertFalse(self.httplib_object._verify_hostname(hostname='afoo.alt.name.1', cert=cert2))\n self.assertFalse(self.httplib_object._verify_hostname(hostname='a.foo.alt.name.1', cert=cert2))\n self.assertFalse(self.httplib_object._verify_hostname(hostname='foo.alt.name.1.2', cert=cert2))\n self.assertFalse(self.httplib_object._verify_hostname(hostname='afoo.alt.name.1.2', cert=cert2))\n self.assertTrue(self.httplib_object._verify_hostname(hostname='foo.alt.name.1', cert=cert2))\n self.assertTrue(self.httplib_object._verify_hostname(hostname='python.org', cert=cert3))\n self.assertFalse(self.httplib_object._verify_hostname(hostname='opython.org', cert=cert3))\n self.assertFalse(self.httplib_object._verify_hostname(hostname='ython.org', cert=cert3))\n self.assertTrue(self.httplib_object._verify_hostname(hostname='us-east-1.api.joyentcloud.com', cert=cert4))\n self.assertTrue(self.httplib_object._verify_hostname(hostname='useast-1.api.joyentcloud.com', cert=cert4))\n", "method_code": " def _verify_hostname(self, hostname, cert):\n \"\"\"Verify hostname against peer cert\n \n Check both commonName and entries in subjectAltName, using a\n rudimentary glob to dns regex check to find matches\n \"\"\"\n common_name = self._get_common_name(cert)\n alt_names = self._get_subject_alt_names(cert)\n valid_patterns = [re.compile('^' + pattern.replace('.', '\\\\.').replace('*', '[0-9A-Za-z\\\\-]+') + '$') for pattern in set(common_name) | set(alt_names)]\n return any((pattern.search(hostname) for pattern in valid_patterns))\n ", "context": "class LibcloudHTTPSConnection(httplib.HTTPSConnection):\n def _verify_hostname(self, hostname, cert): ...\n def __init__(self, *args, **kwargs): ...\n def _setup_verify(self): ...\n def _setup_ca_cert(self): ...\n def connect(self): ...\n def _get_subject_alt_names(self, cert): ...\n def _get_common_name(self, cert): ...\n\n verify = False\n ca_cert = None\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_verify_hostname", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000550.py"} {"focal_file": "libcloud/httplib_ssl.py", "focal_class": null, "focal_method": "_get_subject_alt_names", "tests": "import unittest\n\nclass Test_get_subject_alt_names(unittest.TestCase):\n def test_get_subject_alt_names(self):\n cert1 = {'notAfter': 'Feb 16 16:54:50 2013 GMT', 'subject': ((('countryName', 'US'),), (('stateOrProvinceName', 'Delaware'),), (('localityName', 'Wilmington'),), (('organizationName', 'Python Software Foundation'),), (('organizationalUnitName', 'SSL'),), (('commonName', 'somemachine.python.org'),))}\n cert2 = {'notAfter': 'Feb 16 16:54:50 2013 GMT', 'subject': ((('countryName', 'US'),), (('stateOrProvinceName', 'Delaware'),), (('localityName', 'Wilmington'),), (('organizationName', 'Python Software Foundation'),), (('organizationalUnitName', 'SSL'),), (('commonName', 'somemachine.python.org'),)), 'subjectAltName': (('DNS', 'foo.alt.name'), ('DNS', 'foo.alt.name.1'))}\n self.assertEqual(self.httplib_object._get_subject_alt_names(cert=cert1), [])\n alt_names = self.httplib_object._get_subject_alt_names(cert=cert2)\n self.assertEqual(len(alt_names), 2)\n self.assertTrue('foo.alt.name' in alt_names)\n self.assertTrue('foo.alt.name.1' in alt_names)\n", "method_code": " def _get_subject_alt_names(self, cert):\n \"\"\"Get SubjectAltNames\n \n Retrieve 'subjectAltName' attributes from cert data structure\n \"\"\"\n if 'subjectAltName' not in cert:\n values = []\n else:\n values = [value for field, value in cert['subjectAltName'] if field == 'DNS']\n return values\n ", "context": "class LibcloudHTTPSConnection(httplib.HTTPSConnection):\n def _get_subject_alt_names(self, cert): ...\n def __init__(self, *args, **kwargs): ...\n def _setup_verify(self): ...\n def _setup_ca_cert(self): ...\n def connect(self): ...\n def _verify_hostname(self, hostname, cert): ...\n def _get_common_name(self, cert): ...\n\n verify = False\n ca_cert = None\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_get_subject_alt_names", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000551.py"} {"focal_file": "libcloud/httplib_ssl.py", "focal_class": null, "focal_method": "_get_common_name", "tests": "import unittest\n\nclass Test_get_common_name(unittest.TestCase):\n def test_get_common_name(self):\n cert = {'notAfter': 'Feb 16 16:54:50 2013 GMT', 'subject': ((('countryName', 'US'),), (('stateOrProvinceName', 'Delaware'),), (('localityName', 'Wilmington'),), (('organizationName', 'Python Software Foundation'),), (('organizationalUnitName', 'SSL'),), (('commonName', 'somemachine.python.org'),))}\n self.assertEqual(self.httplib_object._get_common_name(cert)[0], 'somemachine.python.org')\n self.assertEqual(self.httplib_object._get_common_name({}), None)\n", "method_code": " def _get_common_name(self, cert):\n \"\"\"Get Common Name\n \n Retrieve 'commonName' attribute from cert data structure\n \"\"\"\n if 'subject' not in cert:\n return None\n values = [value[0][1] for value in cert['subject'] if value[0][0] == 'commonName']\n return values\n ", "context": "class LibcloudHTTPSConnection(httplib.HTTPSConnection):\n def _get_common_name(self, cert): ...\n def __init__(self, *args, **kwargs): ...\n def _setup_verify(self): ...\n def _setup_ca_cert(self): ...\n def connect(self): ...\n def _verify_hostname(self, hostname, cert): ...\n def _get_subject_alt_names(self, cert): ...\n\n verify = False\n ca_cert = None\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_get_common_name", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000552.py"} {"focal_file": "libcloud/httplib_ssl.py", "focal_class": null, "focal_method": "_setup_verify", "tests": "import unittest\n\nclass Test_setup_verify(unittest.TestCase):\n @patch('warnings.warn')\n def test_setup_verify(self, _):\n libcloud.security.CA_CERTS_PATH = []\n libcloud.security.VERIFY_SSL_CERT = True\n libcloud.security.VERIFY_SSL_CERT_STRICT = False\n self.httplib_object._setup_verify()\n warnings.warn.assert_called_once_with(libcloud.security.CA_CERTS_UNAVAILABLE_WARNING_MSG)\n libcloud.security.VERIFY_SSL_CERT = True\n libcloud.security.VERIFY_SSL_CERT_STRICT = True\n try:\n self.httplib_object._setup_verify()\n except RuntimeError:\n e = sys.exc_info()[1]\n msg = libcloud.security.CA_CERTS_UNAVAILABLE_ERROR_MSG\n self.assertEqual(str(e), msg)\n pass\n else:\n self.fail('Exception not thrown')\n libcloud.security.VERIFY_SSL_CERT = False\n libcloud.security.VERIFY_SSL_CERT_STRICT = False\n self.httplib_object._setup_verify()\n", "method_code": " def _setup_verify(self):\n \"\"\"Setup Verify SSL or not\n \n Reads security module's VERIFY_SSL_CERT and toggles whether\n the class overrides the connect() class method or runs the\n inherited httplib.HTTPSConnection connect()\n \"\"\"\n self.verify = libcloud.security.VERIFY_SSL_CERT\n self.strict = libcloud.security.VERIFY_SSL_CERT_STRICT\n if self.verify:\n self._setup_ca_cert()\n else:\n warnings.warn(libcloud.security.VERIFY_SSL_DISABLED_MSG)\n ", "context": "class LibcloudHTTPSConnection(httplib.HTTPSConnection):\n def _setup_verify(self): ...\n def __init__(self, *args, **kwargs): ...\n def _setup_ca_cert(self): ...\n def connect(self): ...\n def _verify_hostname(self, hostname, cert): ...\n def _get_subject_alt_names(self, cert): ...\n def _get_common_name(self, cert): ...\n\n verify = False\n ca_cert = None\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000553.py"} {"focal_file": "libcloud/httplib_ssl.py", "focal_class": null, "focal_method": "_setup_ca_cert", "tests": "import unittest\n\nclass Test_setup_ca_cert(unittest.TestCase):\n @patch('warnings.warn')\n def test_setup_ca_cert(self, _):\n self.httplib_object.verify = False\n self.httplib_object.strict = False\n self.httplib_object._setup_ca_cert()\n self.assertEqual(self.httplib_object.ca_cert, None)\n self.httplib_object.verify = True\n libcloud.security.CA_CERTS_PATH = [os.path.abspath(__file__)]\n self.httplib_object._setup_ca_cert()\n self.assertTrue(self.httplib_object.ca_cert is not None)\n libcloud.security.CA_CERTS_PATH = []\n self.httplib_object._setup_ca_cert()\n warnings.warn.assert_called_once_with(libcloud.security.CA_CERTS_UNAVAILABLE_WARNING_MSG)\n self.assertFalse(self.httplib_object.ca_cert)\n self.assertFalse(self.httplib_object.verify)\n", "method_code": " def _setup_ca_cert(self):\n \"\"\"Setup CA Certs\n \n Search in CA_CERTS_PATH for valid candidates and\n return first match. Otherwise, complain about certs\n not being available.\n \"\"\"\n if not self.verify:\n return\n ca_certs_available = [cert for cert in libcloud.security.CA_CERTS_PATH if os.path.exists(cert) and os.path.isfile(cert)]\n if ca_certs_available:\n self.ca_cert = ca_certs_available[0]\n elif self.strict:\n raise RuntimeError(libcloud.security.CA_CERTS_UNAVAILABLE_ERROR_MSG)\n else:\n warnings.warn(libcloud.security.CA_CERTS_UNAVAILABLE_WARNING_MSG)\n self.ca_cert = None\n self.verify = False\n ", "context": "class LibcloudHTTPSConnection(httplib.HTTPSConnection):\n def _setup_ca_cert(self): ...\n def __init__(self, *args, **kwargs): ...\n def _setup_verify(self): ...\n def connect(self): ...\n def _verify_hostname(self, hostname, cert): ...\n def _get_subject_alt_names(self, cert): ...\n def _get_common_name(self, cert): ...\n\n verify = False\n ca_cert = None\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000554.py"} {"focal_file": "libcloud/pricing.py", "focal_class": null, "focal_method": "get_size_price", "tests": "import unittest\n\nclass Test_get_size_price(unittest.TestCase):\n def test_get_size_price(self):\n libcloud.pricing.PRICING_DATA['compute']['foo'] = {2: 2, '3': 3}\n price1 = libcloud.pricing.get_size_price(driver_type='compute', driver_name='foo', size_id=2)\n price2 = libcloud.pricing.get_size_price(driver_type='compute', driver_name='foo', size_id='3')\n self.assertEqual(price1, 2)\n self.assertEqual(price2, 3)\n", "method_code": "def get_size_price(driver_type, driver_name, size_id):\n \"\"\"\n Return price for the provided size.\n\n @type driver_type: C{str}\n @param driver_type: Driver type ('compute' or 'storage')\n\n @type driver_name: C{str}\n @param driver_name: Driver name\n\n @type size_id: C{int/str}\n @param size_id: Unique size ID (can be an integer or a string - depends on\n the driver)\n\n @rtype: C{int}\n @return: Size price.\n \"\"\"\n pricing = get_pricing(driver_type=driver_type, driver_name=driver_name)\n price = float(pricing[size_id])\n return price", "context": "def get_size_price(driver_type, driver_name, size_id): ...\ndef clear_pricing_data(): ...\ndef get_pricing_file_path(file_path=None): ...\ndef get_pricing(driver_type, driver_name, pricing_file_path=None): ...\ndef set_pricing(driver_type, driver_name, pricing): ...\ndef get_size_price(driver_type, driver_name, size_id): ...\ndef invalidate_pricing_cache(): ...\ndef invalidate_module_pricing_cache(driver_type, driver_name): ...\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_get_size_price", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000555.py"} {"focal_file": "libcloud/pricing.py", "focal_class": null, "focal_method": "invalidate_pricing_cache", "tests": "import unittest\n\nclass Test_invalidate_pricing_cache(unittest.TestCase):\n def test_invalid_pricing_cache(self):\n libcloud.pricing.PRICING_DATA['compute']['foo'] = {2: 2}\n self.assertTrue('foo' in libcloud.pricing.PRICING_DATA['compute'])\n libcloud.pricing.invalidate_pricing_cache()\n self.assertFalse('foo' in libcloud.pricing.PRICING_DATA['compute'])\n", "method_code": "def invalidate_pricing_cache():\n \"\"\"\n Invalidate the cache for all the drivers.\n \"\"\"\n PRICING_DATA['compute'] = {}\n PRICING_DATA['storage'] = {}", "context": "def invalidate_pricing_cache(): ...\ndef clear_pricing_data(): ...\ndef get_pricing_file_path(file_path=None): ...\ndef get_pricing(driver_type, driver_name, pricing_file_path=None): ...\ndef set_pricing(driver_type, driver_name, pricing): ...\ndef get_size_price(driver_type, driver_name, size_id): ...\ndef invalidate_pricing_cache(): ...\ndef invalidate_module_pricing_cache(driver_type, driver_name): ...\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_invalid_pricing_cache", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000556.py"} {"focal_file": "libcloud/pricing.py", "focal_class": null, "focal_method": "invalidate_module_pricing_cache", "tests": "import unittest\n\nclass Test_invalidate_module_pricing_cache(unittest.TestCase):\n def test_invalid_module_pricing_cache(self):\n libcloud.pricing.PRICING_DATA['compute']['foo'] = {1: 1}\n self.assertTrue('foo' in libcloud.pricing.PRICING_DATA['compute'])\n libcloud.pricing.invalidate_module_pricing_cache(driver_type='compute', driver_name='foo')\n self.assertFalse('foo' in libcloud.pricing.PRICING_DATA['compute'])\n libcloud.pricing.invalidate_module_pricing_cache(driver_type='compute', driver_name='foo1')\n", "method_code": "def invalidate_module_pricing_cache(driver_type, driver_name):\n \"\"\"\n Invalidate the cache for the specified driver.\n\n @type driver_type: C{str}\n @param driver_type: Driver type ('compute' or 'storage')\n\n @type driver_name: C{str}\n @param driver_name: Driver name\n \"\"\"\n if driver_name in PRICING_DATA[driver_type]:\n del PRICING_DATA[driver_type][driver_name]", "context": "def invalidate_module_pricing_cache(driver_type, driver_name): ...\ndef clear_pricing_data(): ...\ndef get_pricing_file_path(file_path=None): ...\ndef get_pricing(driver_type, driver_name, pricing_file_path=None): ...\ndef set_pricing(driver_type, driver_name, pricing): ...\ndef get_size_price(driver_type, driver_name, size_id): ...\ndef invalidate_pricing_cache(): ...\ndef invalidate_module_pricing_cache(driver_type, driver_name): ...\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_invalid_module_pricing_cache", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000557.py"} {"focal_file": "libcloud/pricing.py", "focal_class": null, "focal_method": "set_pricing", "tests": "import unittest\n\nclass Test_set_pricing(unittest.TestCase):\n def test_set_pricing(self):\n self.assertFalse('foo' in libcloud.pricing.PRICING_DATA['compute'])\n libcloud.pricing.set_pricing(driver_type='compute', driver_name='foo', pricing={'foo': 1})\n self.assertTrue('foo' in libcloud.pricing.PRICING_DATA['compute'])\n", "method_code": "def set_pricing(driver_type, driver_name, pricing):\n \"\"\"\n Populate the driver pricing dictionary.\n\n @type driver_type: C{str}\n @param driver_type: Driver type ('compute' or 'storage')\n\n @type driver_name: C{str}\n @param driver_name: Driver name\n\n @type pricing: C{dict}\n @param pricing: Dictionary where a key is a size ID and a value is a price.\n \"\"\"\n PRICING_DATA[driver_type][driver_name] = pricing", "context": "def set_pricing(driver_type, driver_name, pricing): ...\ndef clear_pricing_data(): ...\ndef get_pricing_file_path(file_path=None): ...\ndef get_pricing(driver_type, driver_name, pricing_file_path=None): ...\ndef set_pricing(driver_type, driver_name, pricing): ...\ndef get_size_price(driver_type, driver_name, size_id): ...\ndef invalidate_pricing_cache(): ...\ndef invalidate_module_pricing_cache(driver_type, driver_name): ...\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_set_pricing", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000558.py"} {"focal_file": "libcloud/common/cloudstack.py", "focal_class": null, "focal_method": "_sync_request", "tests": "import unittest\n\nclass Test_sync_request(unittest.TestCase):\n def test_sync_request_bad_response(self):\n self.driver.path = '/bad/response'\n try:\n self.connection._sync_request('fake')\n except Exception:\n e = sys.exc_info()[1]\n self.assertTrue(isinstance(e, MalformedResponseError))\n return\n self.assertTrue(False)\n\n def test_sync_request(self):\n self.driver.path = '/sync'\n self.connection._sync_request('fake')\n", "method_code": " def _sync_request(self, command, **kwargs):\n \"\"\"This method handles synchronous calls which are generally fast\n information retrieval requests and thus return 'quickly'.\"\"\"\n kwargs['command'] = command\n result = self.request(self.driver.path, params=kwargs)\n command = command.lower() + 'response'\n if command not in result.object:\n raise MalformedResponseError('Unknown response format', body=result.body, driver=self.driver)\n result = result.object[command]\n return result\n ", "context": "class CloudStackConnection(ConnectionUserAndKeyPollingConnection):\n def _sync_request(self, command, **kwargs): ...\n def _make_signature(self, params): ...\n def add_default_params(self, params): ...\n def pre_connect_hook(self, params, headers): ...\n def _async_request(self, command, **kwargs): ...\n def get_request_kwargs(self, action, params=None, data='', headers=None, method='GET', context=None): ...\n def get_poll_request_kwargs(self, response, context, request_kwargs): ...\n def has_completed(self, response): ...\n\n responseCls = CloudStackResponse\n poll_interval = 1\n request_method = '_sync_request'\n timeout = 600\n ASYNC_PENDING = 0\n ASYNC_SUCCESS = 1\n ASYNC_FAILURE = 2\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_sync_request_bad_response", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000559.py"} {"focal_file": "libcloud/common/cloudstack.py", "focal_class": null, "focal_method": "_async_request", "tests": "import unittest\n\nclass Test_async_request(unittest.TestCase):\n def test_async_request_successful(self):\n self.driver.path = '/async/success'\n result = self.connection._async_request('fake')\n self.assertEqual(result, {'fake': 'result'})\n\n def test_async_request_unsuccessful(self):\n self.driver.path = '/async/fail'\n try:\n self.connection._async_request('fake')\n except Exception:\n e = sys.exc_info()[1]\n self.assertEquals(CloudStackMockHttp.ERROR_TEXT, str(e))\n return\n self.assertFalse(True)\n\n def test_async_request_delayed(self):\n global async_delay\n self.driver.path = '/async/delayed'\n async_delay = 2\n self.connection._async_request('fake')\n self.assertEqual(async_delay, 0)\n", "method_code": " def _async_request(self, command, **kwargs):\n context = {'command': command}\n context.update(kwargs)\n result = super(CloudStackConnection, self).async_request(action=None, params=None, data=None, headers=None, method=None, context=context)\n return result['jobresult']\n ", "context": "class CloudStackConnection(ConnectionUserAndKeyPollingConnection):\n def _async_request(self, command, **kwargs): ...\n def _make_signature(self, params): ...\n def add_default_params(self, params): ...\n def pre_connect_hook(self, params, headers): ...\n def get_request_kwargs(self, action, params=None, data='', headers=None, method='GET', context=None): ...\n def get_poll_request_kwargs(self, response, context, request_kwargs): ...\n def has_completed(self, response): ...\n def _sync_request(self, command, **kwargs): ...\n\n responseCls = CloudStackResponse\n poll_interval = 1\n request_method = '_sync_request'\n timeout = 600\n ASYNC_PENDING = 0\n ASYNC_SUCCESS = 1\n ASYNC_FAILURE = 2\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_async_request_successful", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000560.py"} {"focal_file": "libcloud/compute/drivers/abiquo.py", "focal_class": "AbiquoNodeDriver", "focal_method": "destroy_node", "tests": "import unittest\n\nclass Test_AbiquoNodeDriver_destroy_node(unittest.TestCase):\n def test_destroy_node_response(self):\n \"\"\"\n 'destroy_node' basic test.\n\n Override the destroy to return a different node available\n to be undeployed. (by default it returns an already undeployed node,\n for test creation).\n \"\"\"\n self.driver = AbiquoNodeDriver('go', 'trunks', 'http://dummy.host.com/api')\n node = self.driver.list_nodes()[0]\n ret = self.driver.destroy_node(node)\n self.assertTrue(ret)\n", "method_code": " def destroy_node(self, node):\n \"\"\"\n Destroy a node\n \n Depending on the provider, this may destroy all data associated with\n the node, including backups.\n \n @param node: The node to be destroyed\n @type node: L{Node}\n \n @return: True if the destroy was successful, otherwise False\n @rtype: C{bool}\n \"\"\"\n e_vm = self.connection.request(node.extra['uri_id']).object\n state = e_vm.findtext('state')\n if state in ['ALLOCATED', 'CONFIGURED', 'LOCKED', 'UNKNOWN']:\n raise LibcloudError('Invalid Node state', self)\n if state != 'NOT_ALLOCATED':\n vm_task = ET.Element('virtualmachinetask')\n force_undeploy = ET.SubElement(vm_task, 'forceUndeploy')\n force_undeploy.text = 'True'\n destroy_uri = node.extra['uri_id'] + '/action/undeploy'\n headers = {'Content-type': self.VM_TASK_MIME_TYPE}\n res = self.connection.async_request(action=destroy_uri, method='POST', data=tostring(vm_task), headers=headers)\n if state == 'NOT_ALLOCATED' or res.async_success():\n self.connection.request(action=node.extra['uri_id'], method='DELETE')\n return True\n else:\n return False\n ", "context": "class AbiquoNodeDriver(NodeDriver):\n def destroy_node(self, node): ...\n def __init__(self, user_id, secret, endpoint, **kwargs): ...\n def create_node(self, **kwargs): ...\n def ex_run_node(self, node): ...\n def ex_set_context(self): ...\n def ex_create_group(self, name, location=None): ...\n def ex_destroy_group(self, group): ...\n def ex_list_groups(self, location=None): ...\n def list_images(self, location=None): ...\n def list_locations(self): ...\n def list_nodes(self, location=None): ...\n def list_sizes(self, location=None): ...\n def reboot_node(self, node): ...\n def _ex_connection_class_kwargs(self): ...\n def _deploy_remote(self, e_vm): ...\n def _to_location(self, vdc, dc, driver): ...\n def _to_node(self, vm, driver): ...\n def _to_nodeimage(self, template, driver, repo): ...\n def _get_locations(self, location=None): ...\n def _get_enterprise_id(self): ...\n def _define_create_node_location(self, **kwargs): ...\n def _define_create_node_group(self, xml_loc, loc, **kwargs): ...\n def _define_create_node_node(self, group, **kwargs): ...\n\n self.endpoint = endpoint\n\n type = Provider.ABIQUO\n name = 'Abiquo'\n website = 'http://www.abiquo.com/'\n connectionCls = AbiquoConnection\n features = {'create_node': ['password']}\n timeout = 2000\n NODES_MIME_TYPE = 'application/vnd.abiquo.virtualmachineswithnode+xml'\n NODE_MIME_TYPE = 'application/vnd.abiquo.virtualmachinewithnode+xml'\n VAPP_MIME_TYPE = 'application/vnd.abiquo.virtualappliance+xml'\n VM_TASK_MIME_TYPE = 'application/vnd.abiquo.virtualmachinetask+xml'\n GIGABYTE = 1073741824\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_destroy_node_response", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000561.py"} {"focal_file": "libcloud/compute/drivers/abiquo.py", "focal_class": null, "focal_method": "ex_run_node", "tests": "import unittest\n\nclass Test_ex_run_node(unittest.TestCase):\n def test_run_node(self):\n \"\"\"\n Test 'ex_run_node' feature.\n \"\"\"\n node = self.driver.list_nodes()[0]\n self.driver.ex_run_node(node)\n", "method_code": " def ex_run_node(self, node):\n \"\"\"\n Runs a node\n \n Here there is a bit difference between Abiquo states and libcloud\n states, so this method is created to have better compatibility. In\n libcloud, if the node is not running, then it does not exist (avoiding\n UNKNOWN and temporal states). In Abiquo, you can define a node, and\n then deploy it.\n \n If the node is in L{NodeState.TERMINATED} libcloud's state and in\n 'NOT_DEPLOYED' Abiquo state, there is a way to run and recover it\n for libcloud using this method. There is no way to reach this state\n if you are using only libcloud, but you may have used another Abiquo\n client and now you want to recover your node to be used by libcloud.\n \n @param node: The node to run\n @type node: L{Node}\n \n @return: The node itself, but with the new state\n @rtype: L{Node}\n \"\"\"\n e_vm = self.connection.request(node.extra['uri_id']).object\n state = e_vm.findtext('state')\n if state != 'NOT_ALLOCATED':\n raise LibcloudError('Invalid Node state', self)\n self._deploy_remote(e_vm)\n edit_vm = get_href(e_vm, 'edit')\n headers = {'Accept': self.NODE_MIME_TYPE}\n e_vm = self.connection.request(edit_vm, headers=headers).object\n return self._to_node(e_vm, self)\n ", "context": "class AbiquoNodeDriver(NodeDriver):\n def ex_run_node(self, node): ...\n def __init__(self, user_id, secret, endpoint, **kwargs): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def ex_set_context(self): ...\n def ex_create_group(self, name, location=None): ...\n def ex_destroy_group(self, group): ...\n def ex_list_groups(self, location=None): ...\n def list_images(self, location=None): ...\n def list_locations(self): ...\n def list_nodes(self, location=None): ...\n def list_sizes(self, location=None): ...\n def reboot_node(self, node): ...\n def _ex_connection_class_kwargs(self): ...\n def _deploy_remote(self, e_vm): ...\n def _to_location(self, vdc, dc, driver): ...\n def _to_node(self, vm, driver): ...\n def _to_nodeimage(self, template, driver, repo): ...\n def _get_locations(self, location=None): ...\n def _get_enterprise_id(self): ...\n def _define_create_node_location(self, **kwargs): ...\n def _define_create_node_group(self, xml_loc, loc, **kwargs): ...\n def _define_create_node_node(self, group, **kwargs): ...\n\n self.endpoint = endpoint\n\n type = Provider.ABIQUO\n name = 'Abiquo'\n website = 'http://www.abiquo.com/'\n connectionCls = AbiquoConnection\n features = {'create_node': ['password']}\n timeout = 2000\n NODES_MIME_TYPE = 'application/vnd.abiquo.virtualmachineswithnode+xml'\n NODE_MIME_TYPE = 'application/vnd.abiquo.virtualmachinewithnode+xml'\n VAPP_MIME_TYPE = 'application/vnd.abiquo.virtualappliance+xml'\n VM_TASK_MIME_TYPE = 'application/vnd.abiquo.virtualmachinetask+xml'\n GIGABYTE = 1073741824\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_run_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/compute/drivers/bluebox.py", "focal_class": null, "focal_method": "create_node", "tests": "import unittest\n\nclass Test_create_node(unittest.TestCase):\n def test_create_node(self):\n node = self.driver.create_node(name='foo', size=self.driver.list_sizes()[0], image=self.driver.list_images()[0], auth=NodeAuthPassword('test123'))\n self.assertTrue(isinstance(node, Node))\n self.assertEqual(node.state, NodeState.PENDING)\n self.assertEqual(node.name, 'foo.apitest.blueboxgrid.com')\n", "method_code": " def create_node(self, **kwargs):\n headers = {'Content-Type': 'application/x-www-form-urlencoded'}\n size = kwargs['size']\n name = kwargs['name']\n image = kwargs['image']\n size = kwargs['size']\n try:\n auth = kwargs['auth']\n except Exception:\n raise Exception('SSH public key or password required.')\n data = {'hostname': name, 'product': size.id, 'template': image.id}\n ssh = None\n password = None\n if isinstance(auth, NodeAuthSSHKey):\n ssh = auth.pubkey\n data.update(ssh_public_key=ssh)\n elif isinstance(auth, NodeAuthPassword):\n password = auth.password\n data.update(password=password)\n if 'ex_username' in kwargs:\n data.update(username=kwargs['ex_username'])\n if not ssh and (not password):\n raise Exception('SSH public key or password required.')\n params = urlencode(data)\n result = self.connection.request('/api/blocks.json', headers=headers, data=params, method='POST')\n node = self._to_node(result.object)\n return node\n ", "context": "class BlueboxNodeDriver(NodeDriver):\n def create_node(self, **kwargs): ...\n def list_nodes(self): ...\n def list_sizes(self, location=None): ...\n def list_images(self, location=None): ...\n def destroy_node(self, node): ...\n def list_locations(self): ...\n def reboot_node(self, node): ...\n def _to_node(self, vm): ...\n def _to_image(self, image): ...\n\n connectionCls = BlueboxConnection\n type = Provider.BLUEBOX\n api_name = 'bluebox'\n name = 'Bluebox Blocks'\n website = 'http://bluebox.net'\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000563.py"} {"focal_file": "libcloud/compute/drivers/bluebox.py", "focal_class": null, "focal_method": "list_nodes", "tests": "import unittest\n\nclass Test_list_nodes(unittest.TestCase):\n def test_list_nodes(self):\n node = self.driver.list_nodes()[0]\n self.assertEqual(node.name, 'foo.apitest.blueboxgrid.com')\n self.assertEqual(node.state, NodeState.RUNNING)\n", "method_code": " def list_nodes(self):\n result = self.connection.request('/api/blocks.json')\n return [self._to_node(i) for i in result.object]\n ", "context": "class BlueboxNodeDriver(NodeDriver):\n def list_nodes(self): ...\n def list_sizes(self, location=None): ...\n def list_images(self, location=None): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def list_locations(self): ...\n def reboot_node(self, node): ...\n def _to_node(self, vm): ...\n def _to_image(self, image): ...\n\n connectionCls = BlueboxConnection\n type = Provider.BLUEBOX\n api_name = 'bluebox'\n name = 'Bluebox Blocks'\n website = 'http://bluebox.net'\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_nodes", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000564.py"} {"focal_file": "libcloud/compute/drivers/bluebox.py", "focal_class": null, "focal_method": "list_sizes", "tests": "import unittest\n\nclass Test_list_sizes(unittest.TestCase):\n def test_list_sizes(self):\n sizes = self.driver.list_sizes()\n self.assertEqual(len(sizes), 4)\n ids = [s.id for s in sizes]\n for size in sizes:\n self.assertTrue(size.price > 0)\n self.assertTrue('94fd37a7-2606-47f7-84d5-9000deda52ae' in ids)\n self.assertTrue('b412f354-5056-4bf0-a42f-6ddd998aa092' in ids)\n self.assertTrue('0cd183d3-0287-4b1a-8288-b3ea8302ed58' in ids)\n self.assertTrue('b9b87a5b-2885-4a2e-b434-44a163ca6251' in ids)\n", "method_code": " def list_sizes(self, location=None):\n sizes = []\n for key, values in list(BLUEBOX_INSTANCE_TYPES.items()):\n attributes = copy.deepcopy(values)\n attributes.update({'price': self._get_size_price(size_id=key)})\n sizes.append(BlueboxNodeSize(driver=self.connection.driver, **attributes))\n return sizes\n ", "context": "class BlueboxNodeDriver(NodeDriver):\n def list_sizes(self, location=None): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def list_locations(self): ...\n def reboot_node(self, node): ...\n def _to_node(self, vm): ...\n def _to_image(self, image): ...\n\n connectionCls = BlueboxConnection\n type = Provider.BLUEBOX\n api_name = 'bluebox'\n name = 'Bluebox Blocks'\n website = 'http://bluebox.net'\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_sizes", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000565.py"} {"focal_file": "libcloud/compute/drivers/bluebox.py", "focal_class": null, "focal_method": "list_images", "tests": "import unittest\n\nclass Test_list_images(unittest.TestCase):\n def test_list_images(self):\n images = self.driver.list_images()\n image = images[0]\n self.assertEqual(len(images), 10)\n self.assertEqual(image.name, 'CentOS 5 (Latest Release)')\n self.assertEqual(image.id, 'c66b8145-f768-45ef-9878-395bf8b1b7ff')\n", "method_code": " def list_images(self, location=None):\n result = self.connection.request('/api/block_templates.json')\n images = []\n for image in result.object:\n images.extend([self._to_image(image)])\n return images\n ", "context": "class BlueboxNodeDriver(NodeDriver):\n def list_images(self, location=None): ...\n def list_nodes(self): ...\n def list_sizes(self, location=None): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def list_locations(self): ...\n def reboot_node(self, node): ...\n def _to_node(self, vm): ...\n def _to_image(self, image): ...\n\n connectionCls = BlueboxConnection\n type = Provider.BLUEBOX\n api_name = 'bluebox'\n name = 'Bluebox Blocks'\n website = 'http://bluebox.net'\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_images", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000566.py"} {"focal_file": "libcloud/compute/drivers/bluebox.py", "focal_class": null, "focal_method": "reboot_node", "tests": "import unittest\n\nclass Test_reboot_node(unittest.TestCase):\n def test_reboot_node(self):\n node = self.driver.list_nodes()[0]\n ret = self.driver.reboot_node(node)\n self.assertTrue(ret)\n", "method_code": " def reboot_node(self, node):\n url = '/api/blocks/%s/reboot.json' % node.id\n result = self.connection.request(url, method='PUT')\n return result.status == 200\n ", "context": "class BlueboxNodeDriver(NodeDriver):\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def list_sizes(self, location=None): ...\n def list_images(self, location=None): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def list_locations(self): ...\n def _to_node(self, vm): ...\n def _to_image(self, image): ...\n\n connectionCls = BlueboxConnection\n type = Provider.BLUEBOX\n api_name = 'bluebox'\n name = 'Bluebox Blocks'\n website = 'http://bluebox.net'\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_reboot_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000567.py"} {"focal_file": "libcloud/compute/drivers/bluebox.py", "focal_class": null, "focal_method": "destroy_node", "tests": "import unittest\n\nclass Test_destroy_node(unittest.TestCase):\n def test_destroy_node(self):\n node = self.driver.list_nodes()[0]\n ret = self.driver.destroy_node(node)\n self.assertTrue(ret)\n", "method_code": " def destroy_node(self, node):\n url = '/api/blocks/%s.json' % node.id\n result = self.connection.request(url, method='DELETE')\n return result.status == 200\n ", "context": "class BlueboxNodeDriver(NodeDriver):\n def destroy_node(self, node): ...\n def list_nodes(self): ...\n def list_sizes(self, location=None): ...\n def list_images(self, location=None): ...\n def create_node(self, **kwargs): ...\n def list_locations(self): ...\n def reboot_node(self, node): ...\n def _to_node(self, vm): ...\n def _to_image(self, image): ...\n\n connectionCls = BlueboxConnection\n type = Provider.BLUEBOX\n api_name = 'bluebox'\n name = 'Bluebox Blocks'\n website = 'http://bluebox.net'\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_destroy_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000568.py"} {"focal_file": "libcloud/compute/drivers/brightbox.py", "focal_class": null, "focal_method": "list_nodes", "tests": "import unittest\n\nclass Test_list_nodes(unittest.TestCase):\n def test_list_nodes(self):\n nodes = self.driver.list_nodes()\n self.assertEqual(len(nodes), 2)\n self.assertEqual(len(nodes[0].public_ips), 1)\n self.assertEqual(len(nodes[1].public_ips), 1)\n self.assertEqual(len(nodes[0].private_ips), 1)\n self.assertEqual(len(nodes[1].private_ips), 1)\n self.assertTrue('109.107.35.16' in nodes[0].public_ips)\n self.assertTrue('10.74.210.210' in nodes[0].private_ips)\n self.assertTrue('10.240.228.234' in nodes[1].private_ips)\n self.assertTrue('2a02:1348:14c:393a:24:19ff:fef0:e4ea' in nodes[1].public_ips)\n self.assertEqual(nodes[0].state, NodeState.RUNNING)\n self.assertEqual(nodes[1].state, NodeState.RUNNING)\n\n def test_list_node_extras(self):\n nodes = self.driver.list_nodes()\n self.assertFalse(nodes[0].size is None)\n self.assertFalse(nodes[1].size is None)\n self.assertFalse(nodes[0].image is None)\n self.assertFalse(nodes[1].image is None)\n self.assertEqual(nodes[0].image.id, 'img-arm8f')\n self.assertEqual(nodes[0].size.id, 'typ-urtky')\n self.assertEqual(nodes[1].image.id, 'img-j93gd')\n self.assertEqual(nodes[1].size.id, 'typ-qdiwq')\n self.assertEqual(nodes[0].extra['fqdn'], 'srv-xvpn7.gb1.brightbox.com')\n self.assertEqual(nodes[1].extra['fqdn'], 'srv-742vn.gb1.brightbox.com')\n self.assertEqual(nodes[0].extra['hostname'], 'srv-xvpn7')\n self.assertEqual(nodes[1].extra['hostname'], 'srv-742vn')\n self.assertEqual(nodes[0].extra['status'], 'active')\n self.assertEqual(nodes[1].extra['status'], 'active')\n self.assertTrue('interfaces' in nodes[0].extra)\n self.assertTrue('zone' in nodes[0].extra)\n self.assertTrue('snapshots' in nodes[0].extra)\n self.assertTrue('server_groups' in nodes[0].extra)\n self.assertTrue('started_at' in nodes[0].extra)\n self.assertTrue('created_at' in nodes[0].extra)\n self.assertFalse('deleted_at' in nodes[0].extra)\n", "method_code": " def list_nodes(self):\n data = self.connection.request('/%s/servers' % self.api_version).object\n return list(map(self._to_node, data))\n ", "context": "class BrightboxNodeDriver(NodeDriver):\n def list_nodes(self): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None, api_version=API_VERSION, **kwargs): ...\n def _to_node(self, data): ...\n def _to_image(self, data): ...\n def _to_size(self, data): ...\n def _to_location(self, data): ...\n def _post(self, path, data={}): ...\n def _put(self, path, data={}): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def list_images(self): ...\n def list_sizes(self): ...\n def list_locations(self): ...\n def ex_list_cloud_ips(self): ...\n def ex_create_cloud_ip(self, reverse_dns=None): ...\n def ex_update_cloud_ip(self, cloud_ip_id, reverse_dns): ...\n def ex_map_cloud_ip(self, cloud_ip_id, interface_id): ...\n def ex_unmap_cloud_ip(self, cloud_ip_id): ...\n def ex_destroy_cloud_ip(self, cloud_ip_id): ...\n\n connectionCls = BrightboxConnection\n type = Provider.BRIGHTBOX\n name = 'Brightbox'\n website = 'http://www.brightbox.co.uk/'\n features = {'create_node': ['ssh_key']}\n NODE_STATE_MAP = {'creating': NodeState.PENDING, 'active': NodeState.RUNNING, 'inactive': NodeState.UNKNOWN, 'deleting': NodeState.UNKNOWN, 'deleted': NodeState.TERMINATED, 'failed': NodeState.UNKNOWN, 'unavailable': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_nodes", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000569.py"} {"focal_file": "libcloud/compute/drivers/brightbox.py", "focal_class": null, "focal_method": "list_sizes", "tests": "import unittest\n\nclass Test_list_sizes(unittest.TestCase):\n def test_list_sizes(self):\n sizes = self.driver.list_sizes()\n self.assertEqual(len(sizes), 7)\n self.assertEqual(sizes[0].id, 'typ-4nssg')\n self.assertEqual(sizes[0].name, 'Brightbox Nano Instance')\n self.assertEqual(sizes[0].ram, 512)\n self.assertEqual(sizes[0].disk, 20480)\n self.assertEqual(sizes[0].bandwidth, 0)\n self.assertEqual(sizes[0].price, 0)\n", "method_code": " def list_sizes(self):\n data = self.connection.request('/%s/server_types' % self.api_version).object\n return list(map(self._to_size, data))\n ", "context": "class BrightboxNodeDriver(NodeDriver):\n def list_sizes(self): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None, api_version=API_VERSION, **kwargs): ...\n def _to_node(self, data): ...\n def _to_image(self, data): ...\n def _to_size(self, data): ...\n def _to_location(self, data): ...\n def _post(self, path, data={}): ...\n def _put(self, path, data={}): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self): ...\n def list_locations(self): ...\n def ex_list_cloud_ips(self): ...\n def ex_create_cloud_ip(self, reverse_dns=None): ...\n def ex_update_cloud_ip(self, cloud_ip_id, reverse_dns): ...\n def ex_map_cloud_ip(self, cloud_ip_id, interface_id): ...\n def ex_unmap_cloud_ip(self, cloud_ip_id): ...\n def ex_destroy_cloud_ip(self, cloud_ip_id): ...\n\n connectionCls = BrightboxConnection\n type = Provider.BRIGHTBOX\n name = 'Brightbox'\n website = 'http://www.brightbox.co.uk/'\n features = {'create_node': ['ssh_key']}\n NODE_STATE_MAP = {'creating': NodeState.PENDING, 'active': NodeState.RUNNING, 'inactive': NodeState.UNKNOWN, 'deleting': NodeState.UNKNOWN, 'deleted': NodeState.TERMINATED, 'failed': NodeState.UNKNOWN, 'unavailable': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_sizes", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000570.py"} {"focal_file": "libcloud/compute/drivers/brightbox.py", "focal_class": null, "focal_method": "list_images", "tests": "import unittest\n\nclass Test_list_images(unittest.TestCase):\n def test_list_images(self):\n images = self.driver.list_images()\n self.assertEqual(len(images), 3)\n self.assertEqual(images[0].id, 'img-99q79')\n self.assertEqual(images[0].name, 'CentOS 5.5 server')\n self.assertTrue('ancestor' in images[0].extra)\n self.assertFalse('licence_name' in images[0].extra)\n\n def test_list_images_extras(self):\n images = self.driver.list_images()\n extra = images[-1].extra\n self.assertEqual(extra['arch'], 'i686')\n self.assertFalse(extra['compatibility_mode'])\n self.assertEqual(extra['created_at'], '2012-01-22T05:36:24Z')\n self.assertTrue('description' in extra)\n self.assertEqual(extra['disk_size'], 671)\n self.assertFalse('min_ram' in extra)\n self.assertFalse(extra['official'])\n self.assertEqual(extra['owner'], 'acc-tqs4c')\n self.assertTrue(extra['public'])\n self.assertEqual(extra['source'], 'oneiric-i386-20178.gz')\n self.assertEqual(extra['source_type'], 'upload')\n self.assertEqual(extra['status'], 'deprecated')\n self.assertEqual(extra['username'], 'ubuntu')\n self.assertEqual(extra['virtual_size'], 1025)\n self.assertFalse('ancestor' in extra)\n self.assertFalse('licence_name' in extra)\n", "method_code": " def list_images(self):\n data = self.connection.request('/%s/images' % self.api_version).object\n return list(map(self._to_image, data))\n ", "context": "class BrightboxNodeDriver(NodeDriver):\n def list_images(self): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None, api_version=API_VERSION, **kwargs): ...\n def _to_node(self, data): ...\n def _to_image(self, data): ...\n def _to_size(self, data): ...\n def _to_location(self, data): ...\n def _post(self, path, data={}): ...\n def _put(self, path, data={}): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def list_nodes(self): ...\n def list_sizes(self): ...\n def list_locations(self): ...\n def ex_list_cloud_ips(self): ...\n def ex_create_cloud_ip(self, reverse_dns=None): ...\n def ex_update_cloud_ip(self, cloud_ip_id, reverse_dns): ...\n def ex_map_cloud_ip(self, cloud_ip_id, interface_id): ...\n def ex_unmap_cloud_ip(self, cloud_ip_id): ...\n def ex_destroy_cloud_ip(self, cloud_ip_id): ...\n\n connectionCls = BrightboxConnection\n type = Provider.BRIGHTBOX\n name = 'Brightbox'\n website = 'http://www.brightbox.co.uk/'\n features = {'create_node': ['ssh_key']}\n NODE_STATE_MAP = {'creating': NodeState.PENDING, 'active': NodeState.RUNNING, 'inactive': NodeState.UNKNOWN, 'deleting': NodeState.UNKNOWN, 'deleted': NodeState.TERMINATED, 'failed': NodeState.UNKNOWN, 'unavailable': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_images", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000571.py"} {"focal_file": "libcloud/compute/drivers/brightbox.py", "focal_class": null, "focal_method": "list_locations", "tests": "import unittest\n\nclass Test_list_locations(unittest.TestCase):\n def test_list_locations(self):\n locations = self.driver.list_locations()\n self.assertEqual(locations[0].id, 'zon-6mxqw')\n self.assertEqual(locations[0].name, 'gb1-a')\n self.assertEqual(locations[1].id, 'zon-remk1')\n self.assertEqual(locations[1].name, 'gb1-b')\n\n def test_create_node_in_location(self):\n size = self.driver.list_sizes()[0]\n image = self.driver.list_images()[0]\n location = self.driver.list_locations()[1]\n node = self.driver.create_node(name='Test Node', image=image, size=size, location=location)\n self.assertEqual('srv-nnumd', node.id)\n self.assertEqual('Test Node', node.name)\n self.assertEqual('gb1-b', node.extra['zone'].name)\n", "method_code": " def list_locations(self):\n data = self.connection.request('/%s/zones' % self.api_version).object\n return list(map(self._to_location, data))\n ", "context": "class BrightboxNodeDriver(NodeDriver):\n def list_locations(self): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None, api_version=API_VERSION, **kwargs): ...\n def _to_node(self, data): ...\n def _to_image(self, data): ...\n def _to_size(self, data): ...\n def _to_location(self, data): ...\n def _post(self, path, data={}): ...\n def _put(self, path, data={}): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self): ...\n def list_sizes(self): ...\n def ex_list_cloud_ips(self): ...\n def ex_create_cloud_ip(self, reverse_dns=None): ...\n def ex_update_cloud_ip(self, cloud_ip_id, reverse_dns): ...\n def ex_map_cloud_ip(self, cloud_ip_id, interface_id): ...\n def ex_unmap_cloud_ip(self, cloud_ip_id): ...\n def ex_destroy_cloud_ip(self, cloud_ip_id): ...\n\n connectionCls = BrightboxConnection\n type = Provider.BRIGHTBOX\n name = 'Brightbox'\n website = 'http://www.brightbox.co.uk/'\n features = {'create_node': ['ssh_key']}\n NODE_STATE_MAP = {'creating': NodeState.PENDING, 'active': NodeState.RUNNING, 'inactive': NodeState.UNKNOWN, 'deleting': NodeState.UNKNOWN, 'deleted': NodeState.TERMINATED, 'failed': NodeState.UNKNOWN, 'unavailable': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_locations", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000572.py"} {"focal_file": "libcloud/compute/drivers/brightbox.py", "focal_class": null, "focal_method": "destroy_node", "tests": "import unittest\n\nclass Test_destroy_node(unittest.TestCase):\n def test_destroy_node(self):\n node = self.driver.list_nodes()[0]\n self.assertTrue(self.driver.destroy_node(node))\n", "method_code": " def destroy_node(self, node):\n response = self.connection.request('/%s/servers/%s' % (self.api_version, node.id), method='DELETE')\n return response.status == httplib.ACCEPTED\n ", "context": "class BrightboxNodeDriver(NodeDriver):\n def destroy_node(self, node): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None, api_version=API_VERSION, **kwargs): ...\n def _to_node(self, data): ...\n def _to_image(self, data): ...\n def _to_size(self, data): ...\n def _to_location(self, data): ...\n def _post(self, path, data={}): ...\n def _put(self, path, data={}): ...\n def create_node(self, **kwargs): ...\n def list_nodes(self): ...\n def list_images(self): ...\n def list_sizes(self): ...\n def list_locations(self): ...\n def ex_list_cloud_ips(self): ...\n def ex_create_cloud_ip(self, reverse_dns=None): ...\n def ex_update_cloud_ip(self, cloud_ip_id, reverse_dns): ...\n def ex_map_cloud_ip(self, cloud_ip_id, interface_id): ...\n def ex_unmap_cloud_ip(self, cloud_ip_id): ...\n def ex_destroy_cloud_ip(self, cloud_ip_id): ...\n\n connectionCls = BrightboxConnection\n type = Provider.BRIGHTBOX\n name = 'Brightbox'\n website = 'http://www.brightbox.co.uk/'\n features = {'create_node': ['ssh_key']}\n NODE_STATE_MAP = {'creating': NodeState.PENDING, 'active': NodeState.RUNNING, 'inactive': NodeState.UNKNOWN, 'deleting': NodeState.UNKNOWN, 'deleted': NodeState.TERMINATED, 'failed': NodeState.UNKNOWN, 'unavailable': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_destroy_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000573.py"} {"focal_file": "libcloud/compute/drivers/brightbox.py", "focal_class": null, "focal_method": "create_node", "tests": "import unittest\n\nclass Test_create_node(unittest.TestCase):\n def test_create_node(self):\n size = self.driver.list_sizes()[0]\n image = self.driver.list_images()[0]\n node = self.driver.create_node(name='Test Node', image=image, size=size)\n self.assertEqual('srv-p61uj', node.id)\n self.assertEqual('Test Node', node.name)\n self.assertEqual('gb1-a', node.extra['zone'].name)\n", "method_code": " def create_node(self, **kwargs):\n \"\"\"Create a new Brightbox node\n \n Reference: https://api.gb1.brightbox.com/1.0/#server_create_server\n \n @inherits: L{NodeDriver.create_node}\n \n @keyword ex_userdata: User data\n @type ex_userdata: C{str}\n \n @keyword ex_servergroup: Name or list of server group ids to\n add server to\n @type ex_servergroup: C{str} or C{list} of C{str}\n \"\"\"\n data = {'name': kwargs['name'], 'server_type': kwargs['size'].id, 'image': kwargs['image'].id}\n if 'ex_userdata' in kwargs:\n data['user_data'] = base64.b64encode(b(kwargs['ex_userdata'])).decode('ascii')\n if 'location' in kwargs:\n data['zone'] = kwargs['location'].id\n if 'ex_servergroup' in kwargs:\n if not isinstance(kwargs['ex_servergroup'], list):\n kwargs['ex_servergroup'] = [kwargs['ex_servergroup']]\n data['server_groups'] = kwargs['ex_servergroup']\n data = self._post('/%s/servers' % self.api_version, data).object\n return self._to_node(data)\n ", "context": "class BrightboxNodeDriver(NodeDriver):\n def create_node(self, **kwargs): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None, api_version=API_VERSION, **kwargs): ...\n def _to_node(self, data): ...\n def _to_image(self, data): ...\n def _to_size(self, data): ...\n def _to_location(self, data): ...\n def _post(self, path, data={}): ...\n def _put(self, path, data={}): ...\n def destroy_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self): ...\n def list_sizes(self): ...\n def list_locations(self): ...\n def ex_list_cloud_ips(self): ...\n def ex_create_cloud_ip(self, reverse_dns=None): ...\n def ex_update_cloud_ip(self, cloud_ip_id, reverse_dns): ...\n def ex_map_cloud_ip(self, cloud_ip_id, interface_id): ...\n def ex_unmap_cloud_ip(self, cloud_ip_id): ...\n def ex_destroy_cloud_ip(self, cloud_ip_id): ...\n\n connectionCls = BrightboxConnection\n type = Provider.BRIGHTBOX\n name = 'Brightbox'\n website = 'http://www.brightbox.co.uk/'\n features = {'create_node': ['ssh_key']}\n NODE_STATE_MAP = {'creating': NodeState.PENDING, 'active': NodeState.RUNNING, 'inactive': NodeState.UNKNOWN, 'deleting': NodeState.UNKNOWN, 'deleted': NodeState.TERMINATED, 'failed': NodeState.UNKNOWN, 'unavailable': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000574.py"} {"focal_file": "libcloud/compute/drivers/brightbox.py", "focal_class": null, "focal_method": "ex_list_cloud_ips", "tests": "import unittest\n\nclass Test_ex_list_cloud_ips(unittest.TestCase):\n def test_list_cloud_ips(self):\n cip_list = self.driver.ex_list_cloud_ips()\n self.assertEqual(len(cip_list), 4)\n self.assertEqual(cip_list[2]['status'], 'mapped')\n cip_check = cip_list[0]\n self.assertEqual(cip_check['id'], 'cip-tlrp3')\n self.assertEqual(cip_check['public_ip'], '109.107.35.16')\n self.assertEqual(cip_check['reverse_dns'], 'cip-109-107-35-16.gb1.brightbox.com')\n self.assertEqual(cip_check['status'], 'unmapped')\n self.assertTrue(cip_check['server'] is None)\n self.assertTrue(cip_check['server_group'] is None)\n self.assertTrue(cip_check['interface'] is None)\n self.assertTrue(cip_check['load_balancer'] is None)\n", "method_code": " def ex_list_cloud_ips(self):\n \"\"\"\n List Cloud IPs\n \n @note: This is an API extension for use on Brightbox\n \n @rtype: C{list} of C{dict}\n \"\"\"\n return self.connection.request('/%s/cloud_ips' % self.api_version).object\n ", "context": "class BrightboxNodeDriver(NodeDriver):\n def ex_list_cloud_ips(self): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None, api_version=API_VERSION, **kwargs): ...\n def _to_node(self, data): ...\n def _to_image(self, data): ...\n def _to_size(self, data): ...\n def _to_location(self, data): ...\n def _post(self, path, data={}): ...\n def _put(self, path, data={}): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self): ...\n def list_sizes(self): ...\n def list_locations(self): ...\n def ex_create_cloud_ip(self, reverse_dns=None): ...\n def ex_update_cloud_ip(self, cloud_ip_id, reverse_dns): ...\n def ex_map_cloud_ip(self, cloud_ip_id, interface_id): ...\n def ex_unmap_cloud_ip(self, cloud_ip_id): ...\n def ex_destroy_cloud_ip(self, cloud_ip_id): ...\n\n connectionCls = BrightboxConnection\n type = Provider.BRIGHTBOX\n name = 'Brightbox'\n website = 'http://www.brightbox.co.uk/'\n features = {'create_node': ['ssh_key']}\n NODE_STATE_MAP = {'creating': NodeState.PENDING, 'active': NodeState.RUNNING, 'inactive': NodeState.UNKNOWN, 'deleting': NodeState.UNKNOWN, 'deleted': NodeState.TERMINATED, 'failed': NodeState.UNKNOWN, 'unavailable': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_cloud_ips", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000575.py"} {"focal_file": "libcloud/compute/drivers/brightbox.py", "focal_class": null, "focal_method": "ex_create_cloud_ip", "tests": "import unittest\n\nclass Test_ex_create_cloud_ip(unittest.TestCase):\n def test_create_cloud_ip(self):\n cip = self.driver.ex_create_cloud_ip()\n self.assertEqual(cip['id'], 'cip-jsjc5')\n self.assertEqual(cip['reverse_dns'], 'cip-109-107-37-234.gb1.brightbox.com')\n\n def test_create_cloud_ip_with_dns(self):\n cip = self.driver.ex_create_cloud_ip('fred.co.uk')\n self.assertEqual(cip['id'], 'cip-jsjc5')\n self.assertEqual(cip['reverse_dns'], 'fred.co.uk')\n", "method_code": " def ex_create_cloud_ip(self, reverse_dns=None):\n \"\"\"\n Requests a new cloud IP address for the account\n \n @note: This is an API extension for use on Brightbox\n \n @param reverse_dns: Reverse DNS hostname\n @type reverse_dns: C{str}\n \n @rtype: C{dict}\n \"\"\"\n params = {}\n if reverse_dns:\n params['reverse_dns'] = reverse_dns\n return self._post('/%s/cloud_ips' % self.api_version, params).object\n ", "context": "class BrightboxNodeDriver(NodeDriver):\n def ex_create_cloud_ip(self, reverse_dns=None): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None, api_version=API_VERSION, **kwargs): ...\n def _to_node(self, data): ...\n def _to_image(self, data): ...\n def _to_size(self, data): ...\n def _to_location(self, data): ...\n def _post(self, path, data={}): ...\n def _put(self, path, data={}): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self): ...\n def list_sizes(self): ...\n def list_locations(self): ...\n def ex_list_cloud_ips(self): ...\n def ex_update_cloud_ip(self, cloud_ip_id, reverse_dns): ...\n def ex_map_cloud_ip(self, cloud_ip_id, interface_id): ...\n def ex_unmap_cloud_ip(self, cloud_ip_id): ...\n def ex_destroy_cloud_ip(self, cloud_ip_id): ...\n\n connectionCls = BrightboxConnection\n type = Provider.BRIGHTBOX\n name = 'Brightbox'\n website = 'http://www.brightbox.co.uk/'\n features = {'create_node': ['ssh_key']}\n NODE_STATE_MAP = {'creating': NodeState.PENDING, 'active': NodeState.RUNNING, 'inactive': NodeState.UNKNOWN, 'deleting': NodeState.UNKNOWN, 'deleted': NodeState.TERMINATED, 'failed': NodeState.UNKNOWN, 'unavailable': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_cloud_ip", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000576.py"} {"focal_file": "libcloud/compute/drivers/brightbox.py", "focal_class": null, "focal_method": "ex_map_cloud_ip", "tests": "import unittest\n\nclass Test_ex_map_cloud_ip(unittest.TestCase):\n def test_map_cloud_ip(self):\n self.assertTrue(self.driver.ex_map_cloud_ip('cip-jsjc5', 'int-ztqbx'))\n", "method_code": " def ex_map_cloud_ip(self, cloud_ip_id, interface_id):\n \"\"\"\n Maps (or points) a cloud IP address at a server's interface\n or a load balancer to allow them to respond to public requests\n \n @note: This is an API extension for use on Brightbox\n \n @param cloud_ip_id: The id of the cloud ip.\n @type cloud_ip_id: C{str}\n \n @param interface_id: The Interface ID or LoadBalancer ID to\n which this Cloud IP should be mapped to\n @type interface_id: C{str}\n \n @return: True if the mapping was successful.\n @rtype: C{bool}\n \"\"\"\n response = self._post('/%s/cloud_ips/%s/map' % (self.api_version, cloud_ip_id), {'destination': interface_id})\n return response.status == httplib.ACCEPTED\n ", "context": "class BrightboxNodeDriver(NodeDriver):\n def ex_map_cloud_ip(self, cloud_ip_id, interface_id): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None, api_version=API_VERSION, **kwargs): ...\n def _to_node(self, data): ...\n def _to_image(self, data): ...\n def _to_size(self, data): ...\n def _to_location(self, data): ...\n def _post(self, path, data={}): ...\n def _put(self, path, data={}): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self): ...\n def list_sizes(self): ...\n def list_locations(self): ...\n def ex_list_cloud_ips(self): ...\n def ex_create_cloud_ip(self, reverse_dns=None): ...\n def ex_update_cloud_ip(self, cloud_ip_id, reverse_dns): ...\n def ex_unmap_cloud_ip(self, cloud_ip_id): ...\n def ex_destroy_cloud_ip(self, cloud_ip_id): ...\n\n connectionCls = BrightboxConnection\n type = Provider.BRIGHTBOX\n name = 'Brightbox'\n website = 'http://www.brightbox.co.uk/'\n features = {'create_node': ['ssh_key']}\n NODE_STATE_MAP = {'creating': NodeState.PENDING, 'active': NodeState.RUNNING, 'inactive': NodeState.UNKNOWN, 'deleting': NodeState.UNKNOWN, 'deleted': NodeState.TERMINATED, 'failed': NodeState.UNKNOWN, 'unavailable': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_map_cloud_ip", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000577.py"} {"focal_file": "libcloud/compute/drivers/brightbox.py", "focal_class": null, "focal_method": "ex_unmap_cloud_ip", "tests": "import unittest\n\nclass Test_ex_unmap_cloud_ip(unittest.TestCase):\n def test_unmap_cloud_ip(self):\n self.assertTrue(self.driver.ex_unmap_cloud_ip('cip-jsjc5'))\n", "method_code": " def ex_unmap_cloud_ip(self, cloud_ip_id):\n \"\"\"\n Unmaps a cloud IP address from its current destination making\n it available to remap. This remains in the account's pool\n of addresses\n \n @note: This is an API extension for use on Brightbox\n \n @param cloud_ip_id: The id of the cloud ip.\n @type cloud_ip_id: C{str}\n \n @return: True if the unmap was successful.\n @rtype: C{bool}\n \"\"\"\n response = self._post('/%s/cloud_ips/%s/unmap' % (self.api_version, cloud_ip_id))\n return response.status == httplib.ACCEPTED\n ", "context": "class BrightboxNodeDriver(NodeDriver):\n def ex_unmap_cloud_ip(self, cloud_ip_id): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None, api_version=API_VERSION, **kwargs): ...\n def _to_node(self, data): ...\n def _to_image(self, data): ...\n def _to_size(self, data): ...\n def _to_location(self, data): ...\n def _post(self, path, data={}): ...\n def _put(self, path, data={}): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self): ...\n def list_sizes(self): ...\n def list_locations(self): ...\n def ex_list_cloud_ips(self): ...\n def ex_create_cloud_ip(self, reverse_dns=None): ...\n def ex_update_cloud_ip(self, cloud_ip_id, reverse_dns): ...\n def ex_map_cloud_ip(self, cloud_ip_id, interface_id): ...\n def ex_destroy_cloud_ip(self, cloud_ip_id): ...\n\n connectionCls = BrightboxConnection\n type = Provider.BRIGHTBOX\n name = 'Brightbox'\n website = 'http://www.brightbox.co.uk/'\n features = {'create_node': ['ssh_key']}\n NODE_STATE_MAP = {'creating': NodeState.PENDING, 'active': NodeState.RUNNING, 'inactive': NodeState.UNKNOWN, 'deleting': NodeState.UNKNOWN, 'deleted': NodeState.TERMINATED, 'failed': NodeState.UNKNOWN, 'unavailable': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_unmap_cloud_ip", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000578.py"} {"focal_file": "libcloud/compute/drivers/brightbox.py", "focal_class": null, "focal_method": "ex_update_cloud_ip", "tests": "import unittest\n\nclass Test_ex_update_cloud_ip(unittest.TestCase):\n def test_update_cloud_ip(self):\n self.assertTrue(self.driver.ex_update_cloud_ip('cip-jsjc5', 'fred.co.uk'))\n", "method_code": " def ex_update_cloud_ip(self, cloud_ip_id, reverse_dns):\n \"\"\"\n Update some details of the cloud IP address\n \n @note: This is an API extension for use on Brightbox\n \n @param cloud_ip_id: The id of the cloud ip.\n @type cloud_ip_id: C{str}\n \n @param reverse_dns: Reverse DNS hostname\n @type reverse_dns: C{str}\n \n @rtype: C{dict}\n \"\"\"\n response = self._put('/%s/cloud_ips/%s' % (self.api_version, cloud_ip_id), {'reverse_dns': reverse_dns})\n return response.status == httplib.OK\n ", "context": "class BrightboxNodeDriver(NodeDriver):\n def ex_update_cloud_ip(self, cloud_ip_id, reverse_dns): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None, api_version=API_VERSION, **kwargs): ...\n def _to_node(self, data): ...\n def _to_image(self, data): ...\n def _to_size(self, data): ...\n def _to_location(self, data): ...\n def _post(self, path, data={}): ...\n def _put(self, path, data={}): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self): ...\n def list_sizes(self): ...\n def list_locations(self): ...\n def ex_list_cloud_ips(self): ...\n def ex_create_cloud_ip(self, reverse_dns=None): ...\n def ex_map_cloud_ip(self, cloud_ip_id, interface_id): ...\n def ex_unmap_cloud_ip(self, cloud_ip_id): ...\n def ex_destroy_cloud_ip(self, cloud_ip_id): ...\n\n connectionCls = BrightboxConnection\n type = Provider.BRIGHTBOX\n name = 'Brightbox'\n website = 'http://www.brightbox.co.uk/'\n features = {'create_node': ['ssh_key']}\n NODE_STATE_MAP = {'creating': NodeState.PENDING, 'active': NodeState.RUNNING, 'inactive': NodeState.UNKNOWN, 'deleting': NodeState.UNKNOWN, 'deleted': NodeState.TERMINATED, 'failed': NodeState.UNKNOWN, 'unavailable': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_update_cloud_ip", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000579.py"} {"focal_file": "libcloud/compute/drivers/brightbox.py", "focal_class": null, "focal_method": "ex_destroy_cloud_ip", "tests": "import unittest\n\nclass Test_ex_destroy_cloud_ip(unittest.TestCase):\n def test_destroy_cloud_ip(self):\n self.assertTrue(self.driver.ex_destroy_cloud_ip('cip-jsjc5'))\n", "method_code": " def ex_destroy_cloud_ip(self, cloud_ip_id):\n \"\"\"\n Release the cloud IP address from the account's ownership\n \n @note: This is an API extension for use on Brightbox\n \n @param cloud_ip_id: The id of the cloud ip.\n @type cloud_ip_id: C{str}\n \n @return: True if the unmap was successful.\n @rtype: C{bool}\n \"\"\"\n response = self.connection.request('/%s/cloud_ips/%s' % (self.api_version, cloud_ip_id), method='DELETE')\n return response.status == httplib.OK\n ", "context": "class BrightboxNodeDriver(NodeDriver):\n def ex_destroy_cloud_ip(self, cloud_ip_id): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None, api_version=API_VERSION, **kwargs): ...\n def _to_node(self, data): ...\n def _to_image(self, data): ...\n def _to_size(self, data): ...\n def _to_location(self, data): ...\n def _post(self, path, data={}): ...\n def _put(self, path, data={}): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self): ...\n def list_sizes(self): ...\n def list_locations(self): ...\n def ex_list_cloud_ips(self): ...\n def ex_create_cloud_ip(self, reverse_dns=None): ...\n def ex_update_cloud_ip(self, cloud_ip_id, reverse_dns): ...\n def ex_map_cloud_ip(self, cloud_ip_id, interface_id): ...\n def ex_unmap_cloud_ip(self, cloud_ip_id): ...\n\n connectionCls = BrightboxConnection\n type = Provider.BRIGHTBOX\n name = 'Brightbox'\n website = 'http://www.brightbox.co.uk/'\n features = {'create_node': ['ssh_key']}\n NODE_STATE_MAP = {'creating': NodeState.PENDING, 'active': NodeState.RUNNING, 'inactive': NodeState.UNKNOWN, 'deleting': NodeState.UNKNOWN, 'deleted': NodeState.TERMINATED, 'failed': NodeState.UNKNOWN, 'unavailable': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_destroy_cloud_ip", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000580.py"} {"focal_file": "libcloud/compute/drivers/cloudsigma.py", "focal_class": null, "focal_method": "list_nodes", "tests": "import unittest\n\nclass Test_list_nodes(unittest.TestCase):\n def test_list_nodes(self):\n nodes = self.driver.list_nodes()\n self.assertTrue(isinstance(nodes, list))\n self.assertEqual(len(nodes), 1)\n node = nodes[0]\n self.assertEqual(node.public_ips[0], '1.2.3.4')\n self.assertEqual(node.extra['smp'], 1)\n self.assertEqual(node.extra['cpu'], 1100)\n self.assertEqual(node.extra['mem'], 640)\n", "method_code": " def list_nodes(self):\n response = self.connection.request(action='/servers/info').object\n nodes = []\n for data in response:\n node = self._to_node(data)\n if node:\n nodes.append(node)\n return nodes\n ", "context": "class CloudSigmaBaseNodeDriver(NodeDriver):\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def create_node(self, **kwargs): ...\n def ex_destroy_node_and_drives(self, node): ...\n def ex_static_ip_list(self): ...\n def ex_drives_list(self): ...\n def ex_static_ip_create(self): ...\n def ex_static_ip_destroy(self, ip_address): ...\n def ex_drive_destroy(self, drive_uuid): ...\n def ex_set_node_configuration(self, node, **kwargs): ...\n def ex_start_node(self, node): ...\n def ex_stop_node(self, node): ...\n def ex_shutdown_node(self, node): ...\n def ex_destroy_drive(self, drive_uuid): ...\n def _to_node(self, data): ...\n def _get_node(self, node_id): ...\n def _get_node_info(self, node): ...\n\n type = Provider.CLOUDSIGMA\n name = 'CloudSigma'\n website = 'http://www.cloudsigma.com/'\n connectionCls = CloudSigmaBaseConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_nodes", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000581.py"} {"focal_file": "libcloud/compute/drivers/cloudsigma.py", "focal_class": null, "focal_method": "list_sizes", "tests": "import unittest\n\nclass Test_list_sizes(unittest.TestCase):\n def test_list_sizes(self):\n images = self.driver.list_sizes()\n self.assertEqual(len(images), 9)\n", "method_code": " def list_sizes(self, location=None):\n sizes = []\n for key, value in INSTANCE_TYPES.items():\n size = CloudSigmaNodeSize(id=value['id'], name=value['name'], cpu=value['cpu'], ram=value['memory'], disk=value['disk'], bandwidth=value['bandwidth'], price=self._get_size_price(size_id=key), driver=self.connection.driver)\n sizes.append(size)\n return sizes\n ", "context": "class CloudSigmaBaseNodeDriver(NodeDriver):\n def list_sizes(self, location=None): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def list_images(self, location=None): ...\n def list_nodes(self): ...\n def create_node(self, **kwargs): ...\n def ex_destroy_node_and_drives(self, node): ...\n def ex_static_ip_list(self): ...\n def ex_drives_list(self): ...\n def ex_static_ip_create(self): ...\n def ex_static_ip_destroy(self, ip_address): ...\n def ex_drive_destroy(self, drive_uuid): ...\n def ex_set_node_configuration(self, node, **kwargs): ...\n def ex_start_node(self, node): ...\n def ex_stop_node(self, node): ...\n def ex_shutdown_node(self, node): ...\n def ex_destroy_drive(self, drive_uuid): ...\n def _to_node(self, data): ...\n def _get_node(self, node_id): ...\n def _get_node_info(self, node): ...\n\n type = Provider.CLOUDSIGMA\n name = 'CloudSigma'\n website = 'http://www.cloudsigma.com/'\n connectionCls = CloudSigmaBaseConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_sizes", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000582.py"} {"focal_file": "libcloud/compute/drivers/cloudsigma.py", "focal_class": null, "focal_method": "list_images", "tests": "import unittest\n\nclass Test_list_images(unittest.TestCase):\n def test_list_images(self):\n sizes = self.driver.list_images()\n self.assertEqual(len(sizes), 10)\n", "method_code": " def list_images(self, location=None):\n \"\"\"\n Return a list of available standard images (this call might take up\n to 15 seconds to return).\n \n @inherits: L{NodeDriver.list_images}\n \"\"\"\n response = self.connection.request(action='/drives/standard/info').object\n images = []\n for value in response:\n if value.get('type'):\n if value['type'] == 'disk':\n image = NodeImage(id=value['drive'], name=value['name'], driver=self.connection.driver, extra={'size': value['size']})\n images.append(image)\n return images\n ", "context": "class CloudSigmaBaseNodeDriver(NodeDriver):\n def list_images(self, location=None): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def list_sizes(self, location=None): ...\n def list_nodes(self): ...\n def create_node(self, **kwargs): ...\n def ex_destroy_node_and_drives(self, node): ...\n def ex_static_ip_list(self): ...\n def ex_drives_list(self): ...\n def ex_static_ip_create(self): ...\n def ex_static_ip_destroy(self, ip_address): ...\n def ex_drive_destroy(self, drive_uuid): ...\n def ex_set_node_configuration(self, node, **kwargs): ...\n def ex_start_node(self, node): ...\n def ex_stop_node(self, node): ...\n def ex_shutdown_node(self, node): ...\n def ex_destroy_drive(self, drive_uuid): ...\n def _to_node(self, data): ...\n def _get_node(self, node_id): ...\n def _get_node_info(self, node): ...\n\n type = Provider.CLOUDSIGMA\n name = 'CloudSigma'\n website = 'http://www.cloudsigma.com/'\n connectionCls = CloudSigmaBaseConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_images", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/compute/drivers/cloudsigma.py", "focal_class": null, "focal_method": "ex_start_node", "tests": "import unittest\n\nclass Test_ex_start_node(unittest.TestCase):\n def test_start_node(self):\n nodes = self.driver.list_nodes()\n node = nodes[0]\n self.assertTrue(self.driver.ex_start_node(node))\n", "method_code": " def ex_start_node(self, node):\n \"\"\"\n Start a node.\n \n @param node: Node which should be used\n @type node: L{Node}\n \n @rtype: C{bool}\n \"\"\"\n response = self.connection.request(action='/servers/%s/start' % node.id, method='POST')\n return response.status == 200\n ", "context": "class CloudSigmaBaseNodeDriver(NodeDriver):\n def ex_start_node(self, node): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_nodes(self): ...\n def create_node(self, **kwargs): ...\n def ex_destroy_node_and_drives(self, node): ...\n def ex_static_ip_list(self): ...\n def ex_drives_list(self): ...\n def ex_static_ip_create(self): ...\n def ex_static_ip_destroy(self, ip_address): ...\n def ex_drive_destroy(self, drive_uuid): ...\n def ex_set_node_configuration(self, node, **kwargs): ...\n def ex_stop_node(self, node): ...\n def ex_shutdown_node(self, node): ...\n def ex_destroy_drive(self, drive_uuid): ...\n def _to_node(self, data): ...\n def _get_node(self, node_id): ...\n def _get_node_info(self, node): ...\n\n type = Provider.CLOUDSIGMA\n name = 'CloudSigma'\n website = 'http://www.cloudsigma.com/'\n connectionCls = CloudSigmaBaseConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_start_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 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": "libcloud/compute/drivers/cloudsigma.py", "focal_class": null, "focal_method": "ex_shutdown_node", "tests": "import unittest\n\nclass Test_ex_shutdown_node(unittest.TestCase):\n def test_shutdown_node(self):\n nodes = self.driver.list_nodes()\n node = nodes[0]\n self.assertTrue(self.driver.ex_stop_node(node))\n self.assertTrue(self.driver.ex_shutdown_node(node))\n", "method_code": " def ex_shutdown_node(self, node):\n \"\"\"\n Stop (shutdown) a node.\n \n @inherits: L{CloudSigmaBaseNodeDriver.ex_stop_node}\n \"\"\"\n return self.ex_stop_node(node)\n ", "context": "class CloudSigmaBaseNodeDriver(NodeDriver):\n def ex_shutdown_node(self, node): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_nodes(self): ...\n def create_node(self, **kwargs): ...\n def ex_destroy_node_and_drives(self, node): ...\n def ex_static_ip_list(self): ...\n def ex_drives_list(self): ...\n def ex_static_ip_create(self): ...\n def ex_static_ip_destroy(self, ip_address): ...\n def ex_drive_destroy(self, drive_uuid): ...\n def ex_set_node_configuration(self, node, **kwargs): ...\n def ex_start_node(self, node): ...\n def ex_stop_node(self, node): ...\n def ex_destroy_drive(self, drive_uuid): ...\n def _to_node(self, data): ...\n def _get_node(self, node_id): ...\n def _get_node_info(self, node): ...\n\n type = Provider.CLOUDSIGMA\n name = 'CloudSigma'\n website = 'http://www.cloudsigma.com/'\n connectionCls = CloudSigmaBaseConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_shutdown_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000585.py"} {"focal_file": "libcloud/compute/drivers/cloudsigma.py", "focal_class": null, "focal_method": "reboot_node", "tests": "import unittest\n\nclass Test_reboot_node(unittest.TestCase):\n def test_reboot_node(self):\n node = self.driver.list_nodes()[0]\n self.assertTrue(self.driver.reboot_node(node))\n", "method_code": " def reboot_node(self, node):\n \"\"\"\n Reboot a node.\n \n Because Cloudsigma API does not provide native reboot call,\n it's emulated using stop and start.\n \n @inherits: L{NodeDriver.reboot_node}\n \"\"\"\n node = self._get_node(node.id)\n state = node.state\n if state == NodeState.RUNNING:\n stopped = self.ex_stop_node(node)\n else:\n stopped = True\n if not stopped:\n raise CloudSigmaException('Could not stop node with id %s' % node.id)\n success = self.ex_start_node(node)\n return success\n ", "context": "class CloudSigmaBaseNodeDriver(NodeDriver):\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_nodes(self): ...\n def create_node(self, **kwargs): ...\n def ex_destroy_node_and_drives(self, node): ...\n def ex_static_ip_list(self): ...\n def ex_drives_list(self): ...\n def ex_static_ip_create(self): ...\n def ex_static_ip_destroy(self, ip_address): ...\n def ex_drive_destroy(self, drive_uuid): ...\n def ex_set_node_configuration(self, node, **kwargs): ...\n def ex_start_node(self, node): ...\n def ex_stop_node(self, node): ...\n def ex_shutdown_node(self, node): ...\n def ex_destroy_drive(self, drive_uuid): ...\n def _to_node(self, data): ...\n def _get_node(self, node_id): ...\n def _get_node_info(self, node): ...\n\n type = Provider.CLOUDSIGMA\n name = 'CloudSigma'\n website = 'http://www.cloudsigma.com/'\n connectionCls = CloudSigmaBaseConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_reboot_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000586.py"} {"focal_file": "libcloud/compute/drivers/cloudsigma.py", "focal_class": null, "focal_method": "destroy_node", "tests": "import unittest\n\nclass Test_destroy_node(unittest.TestCase):\n def test_destroy_node(self):\n node = self.driver.list_nodes()[0]\n self.assertTrue(self.driver.destroy_node(node))\n self.driver.list_nodes()\n", "method_code": " def destroy_node(self, node):\n \"\"\"\n Destroy a node (all the drives associated with it are NOT destroyed).\n \n If a node is still running, it's stopped before it's destroyed.\n \n @inherits: L{NodeDriver.destroy_node}\n \"\"\"\n node = self._get_node(node.id)\n state = node.state\n if state == NodeState.RUNNING:\n stopped = self.ex_stop_node(node)\n else:\n stopped = True\n if not stopped:\n raise CloudSigmaException('Could not stop node with id %s' % node.id)\n response = self.connection.request(action='/servers/%s/destroy' % node.id, method='POST')\n return response.status == 204\n ", "context": "class CloudSigmaBaseNodeDriver(NodeDriver):\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_nodes(self): ...\n def create_node(self, **kwargs): ...\n def ex_destroy_node_and_drives(self, node): ...\n def ex_static_ip_list(self): ...\n def ex_drives_list(self): ...\n def ex_static_ip_create(self): ...\n def ex_static_ip_destroy(self, ip_address): ...\n def ex_drive_destroy(self, drive_uuid): ...\n def ex_set_node_configuration(self, node, **kwargs): ...\n def ex_start_node(self, node): ...\n def ex_stop_node(self, node): ...\n def ex_shutdown_node(self, node): ...\n def ex_destroy_drive(self, drive_uuid): ...\n def _to_node(self, data): ...\n def _get_node(self, node_id): ...\n def _get_node_info(self, node): ...\n\n type = Provider.CLOUDSIGMA\n name = 'CloudSigma'\n website = 'http://www.cloudsigma.com/'\n connectionCls = CloudSigmaBaseConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_destroy_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/compute/drivers/cloudsigma.py", "focal_class": null, "focal_method": "create_node", "tests": "import unittest\n\nclass Test_create_node(unittest.TestCase):\n def test_create_node(self):\n size = self.driver.list_sizes()[0]\n image = self.driver.list_images()[0]\n node = self.driver.create_node(name='cloudsigma node', image=image, size=size)\n self.assertTrue(isinstance(node, Node))\n", "method_code": " def create_node(self, **kwargs):\n \"\"\"\n Creates a CloudSigma instance\n \n @inherits: L{NodeDriver.create_node}\n \n @keyword name: String with a name for this new node (required)\n @type name: C{str}\n \n @keyword smp: Number of virtual processors or None to calculate\n based on the cpu speed\n @type smp: C{int}\n \n @keyword nic_model: e1000, rtl8139 or virtio (is not specified,\n e1000 is used)\n @type nic_model: C{str}\n \n @keyword vnc_password: If not set, VNC access is disabled.\n @type vnc_password: C{bool}\n \n @keyword drive_type: Drive type (ssd|hdd). Defaults to hdd.\n @type drive_type: C{str}\n \"\"\"\n size = kwargs['size']\n image = kwargs['image']\n smp = kwargs.get('smp', 'auto')\n nic_model = kwargs.get('nic_model', 'e1000')\n vnc_password = kwargs.get('vnc_password', None)\n drive_type = kwargs.get('drive_type', 'hdd')\n if nic_model not in ['e1000', 'rtl8139', 'virtio']:\n raise CloudSigmaException('Invalid NIC model specified')\n if drive_type not in ['hdd', 'ssd']:\n raise CloudSigmaException('Invalid drive type \"%s\". Valid types are: hdd, ssd' % drive_type)\n drive_data = {}\n drive_data.update({'name': kwargs['name'], 'size': '%sG' % kwargs['size'].disk, 'driveType': drive_type})\n response = self.connection.request(action='/drives/%s/clone' % image.id, data=dict2str(drive_data), method='POST').object\n if not response:\n raise CloudSigmaException('Drive creation failed')\n drive_uuid = response[0]['drive']\n response = self.connection.request(action='/drives/%s/info' % drive_uuid).object\n imaging_start = time.time()\n while 'imaging' in response[0]:\n response = self.connection.request(action='/drives/%s/info' % drive_uuid).object\n elapsed_time = time.time() - imaging_start\n if 'imaging' in response[0] and elapsed_time >= IMAGING_TIMEOUT:\n raise CloudSigmaException('Drive imaging timed out')\n time.sleep(1)\n node_data = {}\n node_data.update({'name': kwargs['name'], 'cpu': size.cpu, 'mem': size.ram, 'ide:0:0': drive_uuid, 'boot': 'ide:0:0', 'smp': smp})\n node_data.update({'nic:0:model': nic_model, 'nic:0:dhcp': 'auto'})\n if vnc_password:\n node_data.update({'vnc:ip': 'auto', 'vnc:password': vnc_password})\n response = self.connection.request(action='/servers/create', data=dict2str(node_data), method='POST').object\n if not isinstance(response, list):\n response = [response]\n node = self._to_node(response[0])\n if node is None:\n self.ex_drive_destroy(drive_uuid)\n raise CloudSigmaInsufficientFundsException('Insufficient funds, node creation failed')\n started = self.ex_start_node(node)\n if started:\n node.state = NodeState.RUNNING\n return node\n ", "context": "class CloudSigmaBaseNodeDriver(NodeDriver):\n def create_node(self, **kwargs): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_nodes(self): ...\n def ex_destroy_node_and_drives(self, node): ...\n def ex_static_ip_list(self): ...\n def ex_drives_list(self): ...\n def ex_static_ip_create(self): ...\n def ex_static_ip_destroy(self, ip_address): ...\n def ex_drive_destroy(self, drive_uuid): ...\n def ex_set_node_configuration(self, node, **kwargs): ...\n def ex_start_node(self, node): ...\n def ex_stop_node(self, node): ...\n def ex_shutdown_node(self, node): ...\n def ex_destroy_drive(self, drive_uuid): ...\n def _to_node(self, data): ...\n def _get_node(self, node_id): ...\n def _get_node_info(self, node): ...\n\n type = Provider.CLOUDSIGMA\n name = 'CloudSigma'\n website = 'http://www.cloudsigma.com/'\n connectionCls = CloudSigmaBaseConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000588.py"} {"focal_file": "libcloud/compute/drivers/cloudsigma.py", "focal_class": null, "focal_method": "ex_static_ip_list", "tests": "import unittest\n\nclass Test_ex_static_ip_list(unittest.TestCase):\n def test_ex_static_ip_list(self):\n ips = self.driver.ex_static_ip_list()\n self.assertEqual(len(ips), 3)\n", "method_code": " def ex_static_ip_list(self):\n \"\"\"\n Return a list of available static IP addresses.\n \n @rtype: C{list} of C{str}\n \"\"\"\n response = self.connection.request(action='/resources/ip/list', method='GET')\n if response.status != 200:\n raise CloudSigmaException('Could not retrieve IP list')\n ips = str2list(response.body)\n return ips\n ", "context": "class CloudSigmaBaseNodeDriver(NodeDriver):\n def ex_static_ip_list(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_nodes(self): ...\n def create_node(self, **kwargs): ...\n def ex_destroy_node_and_drives(self, node): ...\n def ex_drives_list(self): ...\n def ex_static_ip_create(self): ...\n def ex_static_ip_destroy(self, ip_address): ...\n def ex_drive_destroy(self, drive_uuid): ...\n def ex_set_node_configuration(self, node, **kwargs): ...\n def ex_start_node(self, node): ...\n def ex_stop_node(self, node): ...\n def ex_shutdown_node(self, node): ...\n def ex_destroy_drive(self, drive_uuid): ...\n def _to_node(self, data): ...\n def _get_node(self, node_id): ...\n def _get_node_info(self, node): ...\n\n type = Provider.CLOUDSIGMA\n name = 'CloudSigma'\n website = 'http://www.cloudsigma.com/'\n connectionCls = CloudSigmaBaseConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_static_ip_list", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000589.py"} {"focal_file": "libcloud/compute/drivers/cloudsigma.py", "focal_class": null, "focal_method": "ex_static_ip_create", "tests": "import unittest\n\nclass Test_ex_static_ip_create(unittest.TestCase):\n def test_ex_static_ip_create(self):\n result = self.driver.ex_static_ip_create()\n self.assertEqual(len(result), 2)\n self.assertEqual(len(list(result[0].keys())), 6)\n self.assertEqual(len(list(result[1].keys())), 6)\n", "method_code": " def ex_static_ip_create(self):\n \"\"\"\n Create a new static IP address.p\n \n @rtype: C{list} of C{dict}\n \"\"\"\n response = self.connection.request(action='/resources/ip/create', method='GET')\n result = str2dicts(response.body)\n return result\n ", "context": "class CloudSigmaBaseNodeDriver(NodeDriver):\n def ex_static_ip_create(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_nodes(self): ...\n def create_node(self, **kwargs): ...\n def ex_destroy_node_and_drives(self, node): ...\n def ex_static_ip_list(self): ...\n def ex_drives_list(self): ...\n def ex_static_ip_destroy(self, ip_address): ...\n def ex_drive_destroy(self, drive_uuid): ...\n def ex_set_node_configuration(self, node, **kwargs): ...\n def ex_start_node(self, node): ...\n def ex_stop_node(self, node): ...\n def ex_shutdown_node(self, node): ...\n def ex_destroy_drive(self, drive_uuid): ...\n def _to_node(self, data): ...\n def _get_node(self, node_id): ...\n def _get_node_info(self, node): ...\n\n type = Provider.CLOUDSIGMA\n name = 'CloudSigma'\n website = 'http://www.cloudsigma.com/'\n connectionCls = CloudSigmaBaseConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_static_ip_create", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000590.py"} {"focal_file": "libcloud/compute/drivers/cloudsigma.py", "focal_class": null, "focal_method": "ex_static_ip_destroy", "tests": "import unittest\n\nclass Test_ex_static_ip_destroy(unittest.TestCase):\n def test_ex_static_ip_destroy(self):\n result = self.driver.ex_static_ip_destroy('1.2.3.4')\n self.assertTrue(result)\n", "method_code": " def ex_static_ip_destroy(self, ip_address):\n \"\"\"\n Destroy a static IP address.\n \n @param ip_address: IP address which should be used\n @type ip_address: C{str}\n \n @rtype: C{bool}\n \"\"\"\n response = self.connection.request(action='/resources/ip/%s/destroy' % ip_address, method='GET')\n return response.status == 204\n ", "context": "class CloudSigmaBaseNodeDriver(NodeDriver):\n def ex_static_ip_destroy(self, ip_address): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_nodes(self): ...\n def create_node(self, **kwargs): ...\n def ex_destroy_node_and_drives(self, node): ...\n def ex_static_ip_list(self): ...\n def ex_drives_list(self): ...\n def ex_static_ip_create(self): ...\n def ex_drive_destroy(self, drive_uuid): ...\n def ex_set_node_configuration(self, node, **kwargs): ...\n def ex_start_node(self, node): ...\n def ex_stop_node(self, node): ...\n def ex_shutdown_node(self, node): ...\n def ex_destroy_drive(self, drive_uuid): ...\n def _to_node(self, data): ...\n def _get_node(self, node_id): ...\n def _get_node_info(self, node): ...\n\n type = Provider.CLOUDSIGMA\n name = 'CloudSigma'\n website = 'http://www.cloudsigma.com/'\n connectionCls = CloudSigmaBaseConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_static_ip_destroy", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000591.py"} {"focal_file": "libcloud/compute/drivers/cloudsigma.py", "focal_class": null, "focal_method": "ex_drives_list", "tests": "import unittest\n\nclass Test_ex_drives_list(unittest.TestCase):\n def test_ex_drives_list(self):\n result = self.driver.ex_drives_list()\n self.assertEqual(len(result), 2)\n", "method_code": " def ex_drives_list(self):\n \"\"\"\n Return a list of all the available drives.\n \n @rtype: C{list} of C{dict}\n \"\"\"\n response = self.connection.request(action='/drives/info', method='GET')\n result = str2dicts(response.body)\n return result\n ", "context": "class CloudSigmaBaseNodeDriver(NodeDriver):\n def ex_drives_list(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_nodes(self): ...\n def create_node(self, **kwargs): ...\n def ex_destroy_node_and_drives(self, node): ...\n def ex_static_ip_list(self): ...\n def ex_static_ip_create(self): ...\n def ex_static_ip_destroy(self, ip_address): ...\n def ex_drive_destroy(self, drive_uuid): ...\n def ex_set_node_configuration(self, node, **kwargs): ...\n def ex_start_node(self, node): ...\n def ex_stop_node(self, node): ...\n def ex_shutdown_node(self, node): ...\n def ex_destroy_drive(self, drive_uuid): ...\n def _to_node(self, data): ...\n def _get_node(self, node_id): ...\n def _get_node_info(self, node): ...\n\n type = Provider.CLOUDSIGMA\n name = 'CloudSigma'\n website = 'http://www.cloudsigma.com/'\n connectionCls = CloudSigmaBaseConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_drives_list", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000592.py"} {"focal_file": "libcloud/compute/drivers/cloudsigma.py", "focal_class": null, "focal_method": "ex_drive_destroy", "tests": "import unittest\n\nclass Test_ex_drive_destroy(unittest.TestCase):\n def test_ex_drive_destroy(self):\n result = self.driver.ex_drive_destroy('d18119ce_7afa_474a_9242_e0384b160220')\n self.assertTrue(result)\n", "method_code": " def ex_drive_destroy(self, drive_uuid):\n \"\"\"\n Destroy a drive with a specified uuid.\n If the drive is currently mounted an exception is thrown.\n \n @param drive_uuid: Drive uuid which should be used\n @type drive_uuid: C{str}\n \n @rtype: C{bool}\n \"\"\"\n response = self.connection.request(action='/drives/%s/destroy' % drive_uuid, method='POST')\n return response.status == 204\n ", "context": "class CloudSigmaBaseNodeDriver(NodeDriver):\n def ex_drive_destroy(self, drive_uuid): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_nodes(self): ...\n def create_node(self, **kwargs): ...\n def ex_destroy_node_and_drives(self, node): ...\n def ex_static_ip_list(self): ...\n def ex_drives_list(self): ...\n def ex_static_ip_create(self): ...\n def ex_static_ip_destroy(self, ip_address): ...\n def ex_set_node_configuration(self, node, **kwargs): ...\n def ex_start_node(self, node): ...\n def ex_stop_node(self, node): ...\n def ex_shutdown_node(self, node): ...\n def ex_destroy_drive(self, drive_uuid): ...\n def _to_node(self, data): ...\n def _get_node(self, node_id): ...\n def _get_node_info(self, node): ...\n\n type = Provider.CLOUDSIGMA\n name = 'CloudSigma'\n website = 'http://www.cloudsigma.com/'\n connectionCls = CloudSigmaBaseConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_drive_destroy", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000593.py"} {"focal_file": "libcloud/compute/drivers/cloudsigma.py", "focal_class": null, "focal_method": "ex_set_node_configuration", "tests": "import unittest\n\nclass Test_ex_set_node_configuration(unittest.TestCase):\n def test_ex_set_node_configuration(self):\n node = self.driver.list_nodes()[0]\n result = self.driver.ex_set_node_configuration(node, **{'smp': 2})\n self.assertTrue(result)\n", "method_code": " def ex_set_node_configuration(self, node, **kwargs):\n \"\"\"\n Update a node configuration.\n Changing most of the parameters requires node to be stopped.\n \n @param node: Node which should be used\n @type node: L{Node}\n \n @param kwargs: keyword arguments\n @type kwargs: C{dict}\n \n @rtype: C{bool}\n \"\"\"\n valid_keys = ('^name$', '^parent$', '^cpu$', '^smp$', '^mem$', '^boot$', '^nic:0:model$', '^nic:0:dhcp', '^nic:1:model$', '^nic:1:vlan$', '^nic:1:mac$', '^vnc:ip$', '^vnc:password$', '^vnc:tls', '^ide:[0-1]:[0-1](:media)?$', '^scsi:0:[0-7](:media)?$', '^block:[0-7](:media)?$')\n invalid_keys = []\n keys = list(kwargs.keys())\n for key in keys:\n matches = False\n for regex in valid_keys:\n if re.match(regex, key):\n matches = True\n break\n if not matches:\n invalid_keys.append(key)\n if invalid_keys:\n raise CloudSigmaException('Invalid configuration key specified: %s' % ','.join(invalid_keys))\n response = self.connection.request(action='/servers/%s/set' % node.id, data=dict2str(kwargs), method='POST')\n return response.status == 200 and response.body != ''\n ", "context": "class CloudSigmaBaseNodeDriver(NodeDriver):\n def ex_set_node_configuration(self, node, **kwargs): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_nodes(self): ...\n def create_node(self, **kwargs): ...\n def ex_destroy_node_and_drives(self, node): ...\n def ex_static_ip_list(self): ...\n def ex_drives_list(self): ...\n def ex_static_ip_create(self): ...\n def ex_static_ip_destroy(self, ip_address): ...\n def ex_drive_destroy(self, drive_uuid): ...\n def ex_start_node(self, node): ...\n def ex_stop_node(self, node): ...\n def ex_shutdown_node(self, node): ...\n def ex_destroy_drive(self, drive_uuid): ...\n def _to_node(self, data): ...\n def _get_node(self, node_id): ...\n def _get_node_info(self, node): ...\n\n type = Provider.CLOUDSIGMA\n name = 'CloudSigma'\n website = 'http://www.cloudsigma.com/'\n connectionCls = CloudSigmaBaseConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_set_node_configuration", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000594.py"} {"focal_file": "libcloud/compute/drivers/digitalocean.py", "focal_class": null, "focal_method": "list_images", "tests": "import unittest\n\nclass Test_list_images(unittest.TestCase):\n def test_list_images_success(self):\n images = self.driver.list_images()\n self.assertTrue(len(images) >= 1)\n image = images[0]\n self.assertTrue(image.id is not None)\n self.assertTrue(image.name is not None)\n", "method_code": " def list_images(self):\n data = self.connection.request('/images').object['images']\n return list(map(self._to_image, data))\n ", "context": "class DigitalOceanNodeDriver(NodeDriver):\n def list_images(self): ...\n def list_nodes(self): ...\n def list_locations(self): ...\n def list_sizes(self): ...\n def create_node(self, name, size, image, location, ex_ssh_key_ids=None, **kwargs): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def ex_list_ssh_keys(self): ...\n def ex_create_ssh_key(self, name, ssh_key_pub): ...\n def ex_destroy_ssh_key(self, key_id): ...\n def _to_node(self, data): ...\n def _to_image(self, data): ...\n def _to_location(self, data): ...\n def _to_size(self, data): ...\n def _to_ssh_key(self, data): ...\n\n connectionCls = DigitalOceanConnection\n type = Provider.DIGITAL_OCEAN\n name = 'Digital Ocean'\n website = 'https://www.digitalocean.com'\n features = {'create_node': ['ssh_key']}\n NODE_STATE_MAP = {'new': NodeState.PENDING, 'off': NodeState.REBOOTING, 'active': NodeState.RUNNING}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_images_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000595.py"} {"focal_file": "libcloud/compute/drivers/digitalocean.py", "focal_class": null, "focal_method": "list_locations", "tests": "import unittest\n\nclass Test_list_locations(unittest.TestCase):\n def test_list_locations_success(self):\n locations = self.driver.list_locations()\n self.assertTrue(len(locations) >= 1)\n location = locations[0]\n self.assertEqual(location.id, '1')\n self.assertEqual(location.name, 'New York 1')\n", "method_code": " def list_locations(self):\n data = self.connection.request('/regions').object['regions']\n return list(map(self._to_location, data))\n ", "context": "class DigitalOceanNodeDriver(NodeDriver):\n def list_locations(self): ...\n def list_nodes(self): ...\n def list_images(self): ...\n def list_sizes(self): ...\n def create_node(self, name, size, image, location, ex_ssh_key_ids=None, **kwargs): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def ex_list_ssh_keys(self): ...\n def ex_create_ssh_key(self, name, ssh_key_pub): ...\n def ex_destroy_ssh_key(self, key_id): ...\n def _to_node(self, data): ...\n def _to_image(self, data): ...\n def _to_location(self, data): ...\n def _to_size(self, data): ...\n def _to_ssh_key(self, data): ...\n\n connectionCls = DigitalOceanConnection\n type = Provider.DIGITAL_OCEAN\n name = 'Digital Ocean'\n website = 'https://www.digitalocean.com'\n features = {'create_node': ['ssh_key']}\n NODE_STATE_MAP = {'new': NodeState.PENDING, 'off': NodeState.REBOOTING, 'active': NodeState.RUNNING}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_locations_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000596.py"} {"focal_file": "libcloud/compute/drivers/digitalocean.py", "focal_class": null, "focal_method": "reboot_node", "tests": "import unittest\n\nclass Test_reboot_node(unittest.TestCase):\n def test_reboot_node_success(self):\n node = self.driver.list_nodes()[0]\n result = self.driver.reboot_node(node)\n self.assertTrue(result)\n", "method_code": " def reboot_node(self, node):\n res = self.connection.request('/droplets/%s/reboot/' % node.id)\n return res.status == httplib.OK\n ", "context": "class DigitalOceanNodeDriver(NodeDriver):\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def list_locations(self): ...\n def list_images(self): ...\n def list_sizes(self): ...\n def create_node(self, name, size, image, location, ex_ssh_key_ids=None, **kwargs): ...\n def destroy_node(self, node): ...\n def ex_list_ssh_keys(self): ...\n def ex_create_ssh_key(self, name, ssh_key_pub): ...\n def ex_destroy_ssh_key(self, key_id): ...\n def _to_node(self, data): ...\n def _to_image(self, data): ...\n def _to_location(self, data): ...\n def _to_size(self, data): ...\n def _to_ssh_key(self, data): ...\n\n connectionCls = DigitalOceanConnection\n type = Provider.DIGITAL_OCEAN\n name = 'Digital Ocean'\n website = 'https://www.digitalocean.com'\n features = {'create_node': ['ssh_key']}\n NODE_STATE_MAP = {'new': NodeState.PENDING, 'off': NodeState.REBOOTING, 'active': NodeState.RUNNING}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_reboot_node_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000597.py"} {"focal_file": "libcloud/compute/drivers/digitalocean.py", "focal_class": null, "focal_method": "destroy_node", "tests": "import unittest\n\nclass Test_destroy_node(unittest.TestCase):\n def test_destroy_node_success(self):\n node = self.driver.list_nodes()[0]\n result = self.driver.destroy_node(node)\n self.assertTrue(result)\n", "method_code": " def destroy_node(self, node):\n res = self.connection.request('/droplets/%s/destroy/' % node.id)\n return res.status == httplib.OK\n ", "context": "class DigitalOceanNodeDriver(NodeDriver):\n def destroy_node(self, node): ...\n def list_nodes(self): ...\n def list_locations(self): ...\n def list_images(self): ...\n def list_sizes(self): ...\n def create_node(self, name, size, image, location, ex_ssh_key_ids=None, **kwargs): ...\n def reboot_node(self, node): ...\n def ex_list_ssh_keys(self): ...\n def ex_create_ssh_key(self, name, ssh_key_pub): ...\n def ex_destroy_ssh_key(self, key_id): ...\n def _to_node(self, data): ...\n def _to_image(self, data): ...\n def _to_location(self, data): ...\n def _to_size(self, data): ...\n def _to_ssh_key(self, data): ...\n\n connectionCls = DigitalOceanConnection\n type = Provider.DIGITAL_OCEAN\n name = 'Digital Ocean'\n website = 'https://www.digitalocean.com'\n features = {'create_node': ['ssh_key']}\n NODE_STATE_MAP = {'new': NodeState.PENDING, 'off': NodeState.REBOOTING, 'active': NodeState.RUNNING}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_destroy_node_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000598.py"} {"focal_file": "libcloud/compute/drivers/digitalocean.py", "focal_class": null, "focal_method": "ex_list_ssh_keys", "tests": "import unittest\n\nclass Test_ex_list_ssh_keys(unittest.TestCase):\n def test_ex_list_ssh_keys(self):\n keys = self.driver.ex_list_ssh_keys()\n self.assertEqual(len(keys), 1)\n self.assertEqual(keys[0].id, 7717)\n self.assertEqual(keys[0].name, 'test1')\n self.assertEqual(keys[0].pub_key, None)\n", "method_code": " def ex_list_ssh_keys(self):\n \"\"\"\n List all the available SSH keys.\n \n @return: Available SSH keys.\n @rtype: C{list} of L{SSHKey}\n \"\"\"\n data = self.connection.request('/ssh_keys').object['ssh_keys']\n return list(map(self._to_ssh_key, data))\n ", "context": "class DigitalOceanNodeDriver(NodeDriver):\n def ex_list_ssh_keys(self): ...\n def list_nodes(self): ...\n def list_locations(self): ...\n def list_images(self): ...\n def list_sizes(self): ...\n def create_node(self, name, size, image, location, ex_ssh_key_ids=None, **kwargs): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def ex_create_ssh_key(self, name, ssh_key_pub): ...\n def ex_destroy_ssh_key(self, key_id): ...\n def _to_node(self, data): ...\n def _to_image(self, data): ...\n def _to_location(self, data): ...\n def _to_size(self, data): ...\n def _to_ssh_key(self, data): ...\n\n connectionCls = DigitalOceanConnection\n type = Provider.DIGITAL_OCEAN\n name = 'Digital Ocean'\n website = 'https://www.digitalocean.com'\n features = {'create_node': ['ssh_key']}\n NODE_STATE_MAP = {'new': NodeState.PENDING, 'off': NodeState.REBOOTING, 'active': NodeState.RUNNING}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_list_ssh_keys", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000599.py"} {"focal_file": "libcloud/compute/drivers/digitalocean.py", "focal_class": null, "focal_method": "ex_destroy_ssh_key", "tests": "import unittest\n\nclass Test_ex_destroy_ssh_key(unittest.TestCase):\n def test_ex_destroy_ssh_key(self):\n key = self.driver.ex_list_ssh_keys()[0]\n result = self.driver.ex_destroy_ssh_key(key.id)\n self.assertTrue(result)\n", "method_code": " def ex_destroy_ssh_key(self, key_id):\n \"\"\"\n Delete an existing SSH key.\n \n @param key_id: SSH key id (required)\n @type key_id: C{str}\n \"\"\"\n res = self.connection.request('/ssh_keys/%s/destroy/' % key_id)\n return res.status == httplib.OK\n ", "context": "class DigitalOceanNodeDriver(NodeDriver):\n def ex_destroy_ssh_key(self, key_id): ...\n def list_nodes(self): ...\n def list_locations(self): ...\n def list_images(self): ...\n def list_sizes(self): ...\n def create_node(self, name, size, image, location, ex_ssh_key_ids=None, **kwargs): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def ex_list_ssh_keys(self): ...\n def ex_create_ssh_key(self, name, ssh_key_pub): ...\n def _to_node(self, data): ...\n def _to_image(self, data): ...\n def _to_location(self, data): ...\n def _to_size(self, data): ...\n def _to_ssh_key(self, data): ...\n\n connectionCls = DigitalOceanConnection\n type = Provider.DIGITAL_OCEAN\n name = 'Digital Ocean'\n website = 'https://www.digitalocean.com'\n features = {'create_node': ['ssh_key']}\n NODE_STATE_MAP = {'new': NodeState.PENDING, 'off': NodeState.REBOOTING, 'active': NodeState.RUNNING}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_destroy_ssh_key", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000600.py"} {"focal_file": "libcloud/compute/drivers/dreamhost.py", "focal_class": null, "focal_method": "list_nodes", "tests": "import unittest\n\nclass Test_list_nodes(unittest.TestCase):\n def test_list_nodes(self):\n \"\"\"\n Test list_nodes for DreamHost PS driver. Should return a list of two nodes:\n - account_id: 000000\n ip: 75.119.203.51\n memory_mb: 500\n ps: ps22174\n start_date: 2010-02-25\n type: web\n - account_id: 000000\n ip: 75.119.203.52\n memory_mb: 1500\n ps: ps22175\n start_date: 2010-02-25\n type: mysql\n \"\"\"\n nodes = self.driver.list_nodes()\n self.assertEqual(len(nodes), 2)\n web_node = nodes[0]\n mysql_node = nodes[1]\n self.assertEqual(web_node.id, 'ps22174')\n self.assertEqual(web_node.state, NodeState.UNKNOWN)\n self.assertTrue('75.119.203.51' in web_node.public_ips)\n self.assertTrue('current_size' in web_node.extra and web_node.extra['current_size'] == 500)\n self.assertTrue('account_id' in web_node.extra and web_node.extra['account_id'] == 0)\n self.assertTrue('type' in web_node.extra and web_node.extra['type'] == 'web')\n self.assertEqual(mysql_node.id, 'ps22175')\n self.assertEqual(mysql_node.state, NodeState.UNKNOWN)\n self.assertTrue('75.119.203.52' in mysql_node.public_ips)\n self.assertTrue('current_size' in mysql_node.extra and mysql_node.extra['current_size'] == 1500)\n self.assertTrue('account_id' in mysql_node.extra and mysql_node.extra['account_id'] == 0)\n self.assertTrue('type' in mysql_node.extra and mysql_node.extra['type'] == 'mysql')\n", "method_code": " def list_nodes(self, **kwargs):\n data = self.connection.request('/', {'cmd': 'dreamhost_ps-list_ps'}).object\n return [self._to_node(n) for n in data]\n ", "context": "class DreamhostNodeDriver(NodeDriver):\n def list_nodes(self, **kwargs): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def list_images(self, **kwargs): ...\n def list_sizes(self, **kwargs): ...\n def list_locations(self, **kwargs): ...\n def _resize_node(self, node, size): ...\n def _to_node(self, data): ...\n\n type = Provider.DREAMHOST\n api_name = 'dreamhost'\n name = 'Dreamhost'\n website = 'http://dreamhost.com/'\n connectionCls = DreamhostConnection\n _sizes = DH_PS_SIZES\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_nodes", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000601.py"} {"focal_file": "libcloud/compute/drivers/dreamhost.py", "focal_class": null, "focal_method": "create_node", "tests": "import unittest\n\nclass Test_create_node(unittest.TestCase):\n def test_create_node(self):\n \"\"\"\n Test create_node for DreamHost PS driver.\n This is not remarkably compatible with libcloud. The DH API allows\n users to specify what image they want to create and whether to move\n all their data to the (web) PS. It does NOT accept a name, size, or\n location. The only information it returns is the PS's context id\n Once the PS is ready it will appear in the list generated by list_ps.\n \"\"\"\n new_node = self.driver.create_node(image=self.driver.list_images()[0], size=self.driver.list_sizes()[0], movedata='no')\n self.assertEqual(new_node.id, 'ps12345')\n self.assertEqual(new_node.state, NodeState.PENDING)\n self.assertTrue('type' in new_node.extra and new_node.extra['type'] == 'web')\n", "method_code": " def create_node(self, **kwargs):\n \"\"\"Create a new Dreamhost node\n \n @inherits: L{NodeDriver.create_node}\n \n @keyword ex_movedata: Copy all your existing users to this new PS\n @type ex_movedata: C{str}\n \"\"\"\n size = kwargs['size'].ram\n params = {'cmd': 'dreamhost_ps-add_ps', 'movedata': kwargs.get('movedata', 'no'), 'type': kwargs['image'].name, 'size': size}\n data = self.connection.request('/', params).object\n return Node(id=data['added_web'], name=data['added_web'], state=NodeState.PENDING, public_ips=[], private_ips=[], driver=self.connection.driver, extra={'type': kwargs['image'].name})\n ", "context": "class DreamhostNodeDriver(NodeDriver):\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def list_nodes(self, **kwargs): ...\n def list_images(self, **kwargs): ...\n def list_sizes(self, **kwargs): ...\n def list_locations(self, **kwargs): ...\n def _resize_node(self, node, size): ...\n def _to_node(self, data): ...\n\n type = Provider.DREAMHOST\n api_name = 'dreamhost'\n name = 'Dreamhost'\n website = 'http://dreamhost.com/'\n connectionCls = DreamhostConnection\n _sizes = DH_PS_SIZES\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000602.py"} {"focal_file": "libcloud/compute/drivers/dreamhost.py", "focal_class": null, "focal_method": "destroy_node", "tests": "import unittest\n\nclass Test_destroy_node(unittest.TestCase):\n def test_destroy_node(self):\n \"\"\"\n Test destroy_node for DreamHost PS driver\n \"\"\"\n node = self.driver.list_nodes()[0]\n self.assertTrue(self.driver.destroy_node(node))\n\n def test_destroy_node_failure(self):\n \"\"\"\n Test destroy_node failure for DreamHost PS driver\n \"\"\"\n node = self.driver.list_nodes()[0]\n DreamhostMockHttp.type = 'API_FAILURE'\n self.assertFalse(self.driver.destroy_node(node))\n", "method_code": " def destroy_node(self, node):\n params = {'cmd': 'dreamhost_ps-remove_ps', 'ps': node.id}\n try:\n return self.connection.request('/', params).success()\n except DreamhostAPIException:\n return False\n ", "context": "class DreamhostNodeDriver(NodeDriver):\n def destroy_node(self, node): ...\n def create_node(self, **kwargs): ...\n def reboot_node(self, node): ...\n def list_nodes(self, **kwargs): ...\n def list_images(self, **kwargs): ...\n def list_sizes(self, **kwargs): ...\n def list_locations(self, **kwargs): ...\n def _resize_node(self, node, size): ...\n def _to_node(self, data): ...\n\n type = Provider.DREAMHOST\n api_name = 'dreamhost'\n name = 'Dreamhost'\n website = 'http://dreamhost.com/'\n connectionCls = DreamhostConnection\n _sizes = DH_PS_SIZES\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_destroy_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000603.py"} {"focal_file": "libcloud/compute/drivers/dreamhost.py", "focal_class": null, "focal_method": "reboot_node", "tests": "import unittest\n\nclass Test_reboot_node(unittest.TestCase):\n def test_reboot_node(self):\n \"\"\"\n Test reboot_node for DreamHost PS driver.\n \"\"\"\n node = self.driver.list_nodes()[0]\n self.assertTrue(self.driver.reboot_node(node))\n\n def test_reboot_node_failure(self):\n \"\"\"\n Test reboot_node failure for DreamHost PS driver\n \"\"\"\n node = self.driver.list_nodes()[0]\n DreamhostMockHttp.type = 'API_FAILURE'\n self.assertFalse(self.driver.reboot_node(node))\n", "method_code": " def reboot_node(self, node):\n params = {'cmd': 'dreamhost_ps-reboot', 'ps': node.id}\n try:\n return self.connection.request('/', params).success()\n except DreamhostAPIException:\n return False\n ", "context": "class DreamhostNodeDriver(NodeDriver):\n def reboot_node(self, node): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def list_nodes(self, **kwargs): ...\n def list_images(self, **kwargs): ...\n def list_sizes(self, **kwargs): ...\n def list_locations(self, **kwargs): ...\n def _resize_node(self, node, size): ...\n def _to_node(self, data): ...\n\n type = Provider.DREAMHOST\n api_name = 'dreamhost'\n name = 'Dreamhost'\n website = 'http://dreamhost.com/'\n connectionCls = DreamhostConnection\n _sizes = DH_PS_SIZES\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_reboot_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000604.py"} {"focal_file": "libcloud/compute/drivers/dreamhost.py", "focal_class": null, "focal_method": "_resize_node", "tests": "import unittest\n\nclass Test_resize_node(unittest.TestCase):\n def test_resize_node(self):\n \"\"\"\n Test resize_node for DreamHost PS driver\n \"\"\"\n node = self.driver.list_nodes()[0]\n self.assertTrue(self.driver._resize_node(node, 400))\n\n def test_resize_node_failure(self):\n \"\"\"\n Test reboot_node faliure for DreamHost PS driver\n \"\"\"\n node = self.driver.list_nodes()[0]\n DreamhostMockHttp.type = 'API_FAILURE'\n self.assertFalse(self.driver._resize_node(node, 400))\n", "method_code": " def _resize_node(self, node, size):\n if size < 300 or size > 4000:\n return False\n params = {'cmd': 'dreamhost_ps-set_size', 'ps': node.id, 'size': size}\n try:\n return self.connection.request('/', params).success()\n except DreamhostAPIException:\n return False\n ", "context": "class DreamhostNodeDriver(NodeDriver):\n def _resize_node(self, node, size): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def list_nodes(self, **kwargs): ...\n def list_images(self, **kwargs): ...\n def list_sizes(self, **kwargs): ...\n def list_locations(self, **kwargs): ...\n def _to_node(self, data): ...\n\n type = Provider.DREAMHOST\n api_name = 'dreamhost'\n name = 'Dreamhost'\n website = 'http://dreamhost.com/'\n connectionCls = DreamhostConnection\n _sizes = DH_PS_SIZES\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_resize_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 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": "libcloud/compute/drivers/dreamhost.py", "focal_class": null, "focal_method": "list_images", "tests": "import unittest\n\nclass Test_list_images(unittest.TestCase):\n def test_list_images(self):\n \"\"\"\n Test list_images for DreamHost PS driver.\n \"\"\"\n images = self.driver.list_images()\n self.assertEqual(len(images), 2)\n self.assertEqual(images[0].id, 'web')\n self.assertEqual(images[0].name, 'web')\n self.assertEqual(images[1].id, 'mysql')\n self.assertEqual(images[1].name, 'mysql')\n", "method_code": " def list_images(self, **kwargs):\n data = self.connection.request('/', {'cmd': 'dreamhost_ps-list_images'}).object\n images = []\n for img in data:\n images.append(NodeImage(id=img['image'], name=img['image'], driver=self.connection.driver))\n return images\n ", "context": "class DreamhostNodeDriver(NodeDriver):\n def list_images(self, **kwargs): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def list_nodes(self, **kwargs): ...\n def list_sizes(self, **kwargs): ...\n def list_locations(self, **kwargs): ...\n def _resize_node(self, node, size): ...\n def _to_node(self, data): ...\n\n type = Provider.DREAMHOST\n api_name = 'dreamhost'\n name = 'Dreamhost'\n website = 'http://dreamhost.com/'\n connectionCls = DreamhostConnection\n _sizes = DH_PS_SIZES\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_images", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000606.py"} {"focal_file": "libcloud/compute/drivers/dreamhost.py", "focal_class": null, "focal_method": "list_sizes", "tests": "import unittest\n\nclass Test_list_sizes(unittest.TestCase):\n def test_list_sizes(self):\n sizes = self.driver.list_sizes()\n self.assertEqual(len(sizes), 5)\n size = [s for s in sizes if s.id == 'default'][0]\n self.assertEqual(size.id, 'default')\n self.assertEqual(size.bandwidth, None)\n self.assertEqual(size.disk, None)\n self.assertEqual(size.ram, 2300)\n self.assertEqual(size.price, 115)\n", "method_code": " def list_sizes(self, **kwargs):\n sizes = []\n for key, values in self._sizes.items():\n attributes = copy.deepcopy(values)\n attributes.update({'price': self._get_size_price(size_id=key)})\n sizes.append(NodeSize(driver=self.connection.driver, **attributes))\n return sizes\n ", "context": "class DreamhostNodeDriver(NodeDriver):\n def list_sizes(self, **kwargs): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def list_nodes(self, **kwargs): ...\n def list_images(self, **kwargs): ...\n def list_locations(self, **kwargs): ...\n def _resize_node(self, node, size): ...\n def _to_node(self, data): ...\n\n type = Provider.DREAMHOST\n api_name = 'dreamhost'\n name = 'Dreamhost'\n website = 'http://dreamhost.com/'\n connectionCls = DreamhostConnection\n _sizes = DH_PS_SIZES\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_sizes", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 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": "libcloud/compute/drivers/dreamhost.py", "focal_class": null, "focal_method": "list_locations", "tests": "import unittest\n\nclass Test_list_locations(unittest.TestCase):\n def test_list_locations(self):\n try:\n self.driver.list_locations()\n except NotImplementedError:\n pass\n", "method_code": " def list_locations(self, **kwargs):\n raise NotImplementedError('You cannot select a location for DreamHost Private Servers at this time.')\n ", "context": "class DreamhostNodeDriver(NodeDriver):\n def list_locations(self, **kwargs): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def list_nodes(self, **kwargs): ...\n def list_images(self, **kwargs): ...\n def list_sizes(self, **kwargs): ...\n def _resize_node(self, node, size): ...\n def _to_node(self, data): ...\n\n type = Provider.DREAMHOST\n api_name = 'dreamhost'\n name = 'Dreamhost'\n website = 'http://dreamhost.com/'\n connectionCls = DreamhostConnection\n _sizes = DH_PS_SIZES\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_locations", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000608.py"} {"focal_file": "libcloud/compute/drivers/ecp.py", "focal_class": null, "focal_method": "list_nodes", "tests": "import unittest\n\nclass Test_list_nodes(unittest.TestCase):\n def test_list_nodes(self):\n nodes = self.driver.list_nodes()\n self.assertEqual(len(nodes), 2)\n node = nodes[0]\n self.assertEqual(node.id, '1')\n self.assertEqual(node.name, 'dummy-1')\n self.assertEqual(node.public_ips[0], '42.78.124.75')\n self.assertEqual(node.state, NodeState.RUNNING)\n", "method_code": " def list_nodes(self):\n \"\"\"\n Returns a list of all running Nodes\n \n @rtype: C{list} of L{Node}\n \"\"\"\n res = self.connection.request('/rest/hosting/vm/list').parse_body()\n nodes = []\n for vm in res['vms']:\n node = self._to_node(vm)\n if not node is None:\n nodes.append(node)\n return nodes\n ", "context": "class ECPNodeDriver(NodeDriver):\n def list_nodes(self): ...\n def _to_node(self, vm): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def create_node(self, **kwargs): ...\n\n name = 'Enomaly Elastic Computing Platform'\n website = 'http://www.enomaly.com/'\n type = Provider.ECP\n connectionCls = ECPConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_nodes", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000609.py"} {"focal_file": "libcloud/compute/drivers/ecp.py", "focal_class": null, "focal_method": "list_sizes", "tests": "import unittest\n\nclass Test_list_sizes(unittest.TestCase):\n def test_list_sizes(self):\n sizes = self.driver.list_sizes()\n self.assertEqual(len(sizes), 3)\n size = sizes[0]\n self.assertEqual(size.id, '1')\n self.assertEqual(size.ram, 512)\n self.assertEqual(size.disk, 0)\n self.assertEqual(size.bandwidth, 0)\n self.assertEqual(size.price, 0)\n", "method_code": " def list_sizes(self, location=None):\n \"\"\"\n Returns a list of all hardware templates\n \n @inherits: L{NodeDriver.list_sizes}\n \"\"\"\n response = self.connection.request('/rest/hosting/htemplate/list').parse_body()\n sizes = []\n for htemplate in response['templates']:\n sizes.append(NodeSize(id=htemplate['uuid'], name=htemplate['name'], ram=htemplate['memory'], disk=0, bandwidth=0, price=0, driver=self))\n return sizes\n ", "context": "class ECPNodeDriver(NodeDriver):\n def list_sizes(self, location=None): ...\n def list_nodes(self): ...\n def _to_node(self, vm): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def list_images(self, location=None): ...\n def list_locations(self): ...\n def create_node(self, **kwargs): ...\n\n name = 'Enomaly Elastic Computing Platform'\n website = 'http://www.enomaly.com/'\n type = Provider.ECP\n connectionCls = ECPConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_sizes", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000610.py"} {"focal_file": "libcloud/compute/drivers/ecp.py", "focal_class": null, "focal_method": "list_images", "tests": "import unittest\n\nclass Test_list_images(unittest.TestCase):\n def test_list_images(self):\n images = self.driver.list_images()\n self.assertEqual(len(images), 2)\n self.assertEqual(images[0].name, 'centos54: AUTO import from /opt/enomalism2/repo/5d407a68-c76c-11de-86e5-000475cb7577.xvm2')\n self.assertEqual(images[0].id, '1')\n self.assertEqual(images[1].name, 'centos54 two: AUTO import from /opt/enomalism2/repo/5d407a68-c76c-11de-86e5-000475cb7577.xvm2')\n self.assertEqual(images[1].id, '2')\n", "method_code": " def list_images(self, location=None):\n \"\"\"\n Returns a list of all package templates aka appiances aka images.\n \n @inherits: L{NodeDriver.list_images}\n \"\"\"\n response = self.connection.request('/rest/hosting/ptemplate/list').parse_body()\n images = []\n for ptemplate in response['packages']:\n images.append(NodeImage(id=ptemplate['uuid'], name='%s: %s' % (ptemplate['name'], ptemplate['description']), driver=self))\n return images\n ", "context": "class ECPNodeDriver(NodeDriver):\n def list_images(self, location=None): ...\n def list_nodes(self): ...\n def _to_node(self, vm): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def create_node(self, **kwargs): ...\n\n name = 'Enomaly Elastic Computing Platform'\n website = 'http://www.enomaly.com/'\n type = Provider.ECP\n connectionCls = ECPConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_images", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000611.py"} {"focal_file": "libcloud/compute/drivers/ecp.py", "focal_class": null, "focal_method": "reboot_node", "tests": "import unittest\n\nclass Test_reboot_node(unittest.TestCase):\n def test_reboot_node(self):\n node = self.driver.list_nodes()[0]\n self.driver.reboot_node(node)\n", "method_code": " def reboot_node(self, node):\n \"\"\"\n Shuts down a VM and then starts it again.\n \n @inherits: L{NodeDriver.reboot_node}\n \"\"\"\n d = self.connection._encode_multipart_formdata({'action': 'stop'})\n self.connection.request('/rest/hosting/vm/%s' % node.id, method='POST', headers=d[0], data=d[1]).parse_body()\n node.state = NodeState.REBOOTING\n while node.state == NodeState.REBOOTING:\n response = self.connection.request('/rest/hosting/vm/%s' % node.id).parse_body()\n if response['vm']['state'] == 'off':\n node.state = NodeState.TERMINATED\n else:\n time.sleep(5)\n d = self.connection._encode_multipart_formdata({'action': 'start'})\n self.connection.request('/rest/hosting/vm/%s' % node.id, method='POST', headers=d[0], data=d[1]).parse_body()\n node.state = NodeState.RUNNING\n return True\n ", "context": "class ECPNodeDriver(NodeDriver):\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def _to_node(self, vm): ...\n def destroy_node(self, node): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def create_node(self, **kwargs): ...\n\n name = 'Enomaly Elastic Computing Platform'\n website = 'http://www.enomaly.com/'\n type = Provider.ECP\n connectionCls = ECPConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_reboot_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000612.py"} {"focal_file": "libcloud/compute/drivers/ecp.py", "focal_class": null, "focal_method": "destroy_node", "tests": "import unittest\n\nclass Test_destroy_node(unittest.TestCase):\n def test_destroy_node(self):\n node = self.driver.list_nodes()[0]\n self.driver.destroy_node(node)\n", "method_code": " def destroy_node(self, node):\n \"\"\"\n Shuts down and deletes a VM.\n \n @inherits: L{NodeDriver.destroy_node}\n \"\"\"\n d = self.connection._encode_multipart_formdata({'action': 'stop'})\n self.connection.request('/rest/hosting/vm/%s' % node.id, method='POST', headers=d[0], data=d[1]).parse_body()\n node.state = NodeState.PENDING\n while node.state == NodeState.PENDING:\n response = self.connection.request('/rest/hosting/vm/%s' % node.id).parse_body()\n if response['vm']['state'] == 'off':\n node.state = NodeState.TERMINATED\n else:\n time.sleep(5)\n d = self.connection._encode_multipart_formdata({'action': 'delete'})\n self.connection.request('/rest/hosting/vm/%s' % node.id, method='POST', headers=d[0], data=d[1]).parse_body()\n return True\n ", "context": "class ECPNodeDriver(NodeDriver):\n def destroy_node(self, node): ...\n def list_nodes(self): ...\n def _to_node(self, vm): ...\n def reboot_node(self, node): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def create_node(self, **kwargs): ...\n\n name = 'Enomaly Elastic Computing Platform'\n website = 'http://www.enomaly.com/'\n type = Provider.ECP\n connectionCls = ECPConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_destroy_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000613.py"} {"focal_file": "libcloud/compute/drivers/ecp.py", "focal_class": null, "focal_method": "create_node", "tests": "import unittest\n\nclass Test_create_node(unittest.TestCase):\n def test_create_node(self):\n size = self.driver.list_sizes()[0]\n image = self.driver.list_images()[0]\n node = self.driver.create_node(name='api.ivan.net.nz', image=image, size=size)\n self.assertEqual(node.name, 'api.ivan.net.nz')\n self.assertEqual(node.id, '1234')\n", "method_code": " def create_node(self, **kwargs):\n \"\"\"\n Creates a virtual machine.\n \n @keyword name: String with a name for this new node (required)\n @type name: C{str}\n \n @keyword size: The size of resources allocated to this node .\n (required)\n @type size: L{NodeSize}\n \n @keyword image: OS Image to boot on node. (required)\n @type image: L{NodeImage}\n \n @rtype: L{Node}\n \"\"\"\n res = self.connection.request('/rest/hosting/network/list').parse_body()\n network = res['networks'][0]['uuid']\n data = {'name': str(kwargs['name']), 'package': str(kwargs['image'].id), 'hardware': str(kwargs['size'].id), 'network_uuid': str(network), 'disk': ''}\n d = self.connection._encode_multipart_formdata(data)\n response = self.connection.request('/rest/hosting/vm/', method='PUT', headers=d[0], data=d[1]).parse_body()\n n = Node(id=response['machine_id'], name=data['name'], state=NodeState.PENDING, public_ips=[], private_ips=[], driver=self)\n return n\n ", "context": "class ECPNodeDriver(NodeDriver):\n def create_node(self, **kwargs): ...\n def list_nodes(self): ...\n def _to_node(self, vm): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n\n name = 'Enomaly Elastic Computing Platform'\n website = 'http://www.enomaly.com/'\n type = Provider.ECP\n connectionCls = ECPConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000614.py"} {"focal_file": "libcloud/compute/drivers/elasticstack.py", "focal_class": null, "focal_method": "ex_set_node_configuration", "tests": "import unittest\n\nclass Test_ex_set_node_configuration(unittest.TestCase):\n def test_ex_set_node_configuration(self):\n success = self.driver.ex_set_node_configuration(node=self.node, name='name', cpu='2')\n self.assertTrue(success)\n\n def test_ex_set_node_configuration_invalid_keys(self):\n try:\n self.driver.ex_set_node_configuration(node=self.node, foo='bar')\n except ElasticStackException:\n pass\n else:\n self.fail('Invalid option specified, but an exception was not thrown')\n", "method_code": " def ex_set_node_configuration(self, node, **kwargs):\n \"\"\"\n Changes the configuration of the running server\n \n @param node: Node which should be used\n @type node: L{Node}\n \n @param kwargs: keyword arguments\n @type kwargs: C{dict}\n \n @rtype: C{bool}\n \"\"\"\n valid_keys = ('^name$', '^parent$', '^cpu$', '^smp$', '^mem$', '^boot$', '^nic:0:model$', '^nic:0:dhcp', '^nic:1:model$', '^nic:1:vlan$', '^nic:1:mac$', '^vnc:ip$', '^vnc:password$', '^vnc:tls', '^ide:[0-1]:[0-1](:media)?$', '^scsi:0:[0-7](:media)?$', '^block:[0-7](:media)?$')\n invalid_keys = []\n keys = list(kwargs.keys())\n for key in keys:\n matches = False\n for regex in valid_keys:\n if re.match(regex, key):\n matches = True\n break\n if not matches:\n invalid_keys.append(key)\n if invalid_keys:\n raise ElasticStackException('Invalid configuration key specified: %s' % ','.join(invalid_keys))\n response = self.connection.request(action='/servers/%s/set' % node.id, data=json.dumps(kwargs), method='POST')\n return response.status == httplib.OK and response.body != ''\n ", "context": "class ElasticStackBaseNodeDriver(NodeDriver):\n def ex_set_node_configuration(self, node, **kwargs): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_nodes(self): ...\n def create_node(self, **kwargs): ...\n def deploy_node(self, **kwargs): ...\n def ex_shutdown_node(self, node): ...\n def ex_destroy_drive(self, drive_uuid): ...\n def _to_node(self, data, ssh_password=None): ...\n\n website = 'http://www.elasticstack.com'\n connectionCls = ElasticStackBaseConnection\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_set_node_configuration", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000615.py"} {"focal_file": "libcloud/compute/drivers/elasticstack.py", "focal_class": null, "focal_method": "list_nodes", "tests": "import unittest\n\nclass Test_list_nodes(unittest.TestCase):\n def test_list_nodes(self):\n nodes = self.driver.list_nodes()\n self.assertTrue(isinstance(nodes, list))\n self.assertEqual(len(nodes), 1)\n node = nodes[0]\n self.assertEqual(node.public_ips[0], '1.2.3.4')\n self.assertEqual(node.public_ips[1], '1.2.3.5')\n self.assertEqual(node.extra['smp'], 1)\n self.assertEqual(node.extra['ide:0:0'], 'b6049e7a-aa1b-47f9-b21d-cdf2354e28d3')\n", "method_code": " def list_nodes(self):\n response = self.connection.request(action='/servers/info').object\n nodes = []\n for data in response:\n node = self._to_node(data)\n nodes.append(node)\n return nodes\n ", "context": "class ElasticStackBaseNodeDriver(NodeDriver):\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def create_node(self, **kwargs): ...\n def ex_set_node_configuration(self, node, **kwargs): ...\n def deploy_node(self, **kwargs): ...\n def ex_shutdown_node(self, node): ...\n def ex_destroy_drive(self, drive_uuid): ...\n def _to_node(self, data, ssh_password=None): ...\n\n website = 'http://www.elasticstack.com'\n connectionCls = ElasticStackBaseConnection\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_nodes", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000616.py"} {"focal_file": "libcloud/compute/drivers/elasticstack.py", "focal_class": null, "focal_method": "list_sizes", "tests": "import unittest\n\nclass Test_list_sizes(unittest.TestCase):\n def test_list_sizes(self):\n images = self.driver.list_sizes()\n self.assertEqual(len(images), 6)\n image = [i for i in images if i.id == 'small'][0]\n self.assertEqual(image.id, 'small')\n self.assertEqual(image.name, 'Small instance')\n self.assertEqual(image.cpu, 2000)\n self.assertEqual(image.ram, 1700)\n self.assertEqual(image.disk, 160)\n self.assertTrue(isinstance(image.price, float))\n", "method_code": " def list_sizes(self, location=None):\n sizes = []\n for key, value in INSTANCE_TYPES.items():\n size = ElasticStackNodeSize(id=value['id'], name=value['name'], cpu=value['cpu'], ram=value['memory'], disk=value['disk'], bandwidth=value['bandwidth'], price=self._get_size_price(size_id=value['id']), driver=self.connection.driver)\n sizes.append(size)\n return sizes\n ", "context": "class ElasticStackBaseNodeDriver(NodeDriver):\n def list_sizes(self, location=None): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def list_images(self, location=None): ...\n def list_nodes(self): ...\n def create_node(self, **kwargs): ...\n def ex_set_node_configuration(self, node, **kwargs): ...\n def deploy_node(self, **kwargs): ...\n def ex_shutdown_node(self, node): ...\n def ex_destroy_drive(self, drive_uuid): ...\n def _to_node(self, data, ssh_password=None): ...\n\n website = 'http://www.elasticstack.com'\n connectionCls = ElasticStackBaseConnection\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_sizes", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000617.py"} {"focal_file": "libcloud/compute/drivers/elasticstack.py", "focal_class": null, "focal_method": "list_images", "tests": "import unittest\n\nclass Test_list_images(unittest.TestCase):\n def test_list_images(self):\n images = self.driver.list_images()\n self.assertEqual(len(images), len(self.driver._standard_drives))\n for uuid, values in list(self.driver._standard_drives.items()):\n self.assertEqual(len([image for image in images if image.id == uuid]), 1)\n", "method_code": " def list_images(self, location=None):\n images = []\n for key, value in self._standard_drives.items():\n image = NodeImage(id=value['uuid'], name=value['description'], driver=self.connection.driver, extra={'size_gunzipped': value['size_gunzipped']})\n images.append(image)\n return images\n ", "context": "class ElasticStackBaseNodeDriver(NodeDriver):\n def list_images(self, location=None): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def list_sizes(self, location=None): ...\n def list_nodes(self): ...\n def create_node(self, **kwargs): ...\n def ex_set_node_configuration(self, node, **kwargs): ...\n def deploy_node(self, **kwargs): ...\n def ex_shutdown_node(self, node): ...\n def ex_destroy_drive(self, drive_uuid): ...\n def _to_node(self, data, ssh_password=None): ...\n\n website = 'http://www.elasticstack.com'\n connectionCls = ElasticStackBaseConnection\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_images", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000618.py"} {"focal_file": "libcloud/compute/drivers/elasticstack.py", "focal_class": null, "focal_method": "reboot_node", "tests": "import unittest\n\nclass Test_reboot_node(unittest.TestCase):\n def test_reboot_node(self):\n node = self.driver.list_nodes()[0]\n self.assertTrue(self.driver.reboot_node(node))\n", "method_code": " def reboot_node(self, node):\n response = self.connection.request(action='/servers/%s/reset' % node.id, method='POST')\n return response.status == 204\n ", "context": "class ElasticStackBaseNodeDriver(NodeDriver):\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_nodes(self): ...\n def create_node(self, **kwargs): ...\n def ex_set_node_configuration(self, node, **kwargs): ...\n def deploy_node(self, **kwargs): ...\n def ex_shutdown_node(self, node): ...\n def ex_destroy_drive(self, drive_uuid): ...\n def _to_node(self, data, ssh_password=None): ...\n\n website = 'http://www.elasticstack.com'\n connectionCls = ElasticStackBaseConnection\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_reboot_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/compute/drivers/elasticstack.py", "focal_class": null, "focal_method": "destroy_node", "tests": "import unittest\n\nclass Test_destroy_node(unittest.TestCase):\n def test_destroy_node(self):\n node = self.driver.list_nodes()[0]\n self.assertTrue(self.driver.destroy_node(node))\n", "method_code": " def destroy_node(self, node):\n response = self.connection.request(action='/servers/%s/destroy' % node.id, method='POST')\n return response.status == 204\n ", "context": "class ElasticStackBaseNodeDriver(NodeDriver):\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_nodes(self): ...\n def create_node(self, **kwargs): ...\n def ex_set_node_configuration(self, node, **kwargs): ...\n def deploy_node(self, **kwargs): ...\n def ex_shutdown_node(self, node): ...\n def ex_destroy_drive(self, drive_uuid): ...\n def _to_node(self, data, ssh_password=None): ...\n\n website = 'http://www.elasticstack.com'\n connectionCls = ElasticStackBaseConnection\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_destroy_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000620.py"} {"focal_file": "libcloud/compute/drivers/elasticstack.py", "focal_class": null, "focal_method": "create_node", "tests": "import unittest\n\nclass Test_create_node(unittest.TestCase):\n def test_create_node(self):\n sizes = self.driver.list_sizes()\n size = [s for s in sizes if s.id == 'large'][0]\n image = self.image\n self.assertTrue(self.driver.create_node(name='api.ivan.net.nz', image=image, size=size))\n", "method_code": " def create_node(self, **kwargs):\n \"\"\"Creates a ElasticStack instance\n \n @inherits: L{NodeDriver.create_node}\n \n @keyword name: String with a name for this new node (required)\n @type name: C{str}\n \n @keyword smp: Number of virtual processors or None to calculate\n based on the cpu speed\n @type smp: C{int}\n \n @keyword nic_model: e1000, rtl8139 or virtio\n (if not specified, e1000 is used)\n @type nic_model: C{str}\n \n @keyword vnc_password: If set, the same password is also used for\n SSH access with user toor,\n otherwise VNC access is disabled and\n no SSH login is possible.\n @type vnc_password: C{str}\n \"\"\"\n size = kwargs['size']\n image = kwargs['image']\n smp = kwargs.get('smp', 'auto')\n nic_model = kwargs.get('nic_model', 'e1000')\n vnc_password = ssh_password = kwargs.get('vnc_password', None)\n if nic_model not in ('e1000', 'rtl8139', 'virtio'):\n raise ElasticStackException('Invalid NIC model specified')\n drive_data = {}\n drive_data.update({'name': kwargs['name'], 'size': '%sG' % kwargs['size'].disk})\n response = self.connection.request(action='/drives/create', data=json.dumps(drive_data), method='POST').object\n if not response:\n raise ElasticStackException('Drive creation failed')\n drive_uuid = response['drive']\n response = self.connection.request(action='/drives/%s/image/%s/gunzip' % (drive_uuid, image.id), method='POST')\n if response.status not in (200, 204):\n raise ElasticStackException('Drive imaging failed')\n response = self.connection.request(action='/drives/%s/info' % drive_uuid).object\n imaging_start = time.time()\n while 'imaging' in response:\n response = self.connection.request(action='/drives/%s/info' % drive_uuid).object\n elapsed_time = time.time() - imaging_start\n if 'imaging' in response and elapsed_time >= IMAGING_TIMEOUT:\n raise ElasticStackException('Drive imaging timed out')\n time.sleep(1)\n node_data = {}\n node_data.update({'name': kwargs['name'], 'cpu': size.cpu, 'mem': size.ram, 'ide:0:0': drive_uuid, 'boot': 'ide:0:0', 'smp': smp})\n node_data.update({'nic:0:model': nic_model, 'nic:0:dhcp': 'auto'})\n if vnc_password:\n node_data.update({'vnc': 'auto', 'vnc:password': vnc_password})\n response = self.connection.request(action='/servers/create', data=json.dumps(node_data), method='POST').object\n if isinstance(response, list):\n nodes = [self._to_node(node, ssh_password) for node in response]\n else:\n nodes = self._to_node(response, ssh_password)\n return nodes\n ", "context": "class ElasticStackBaseNodeDriver(NodeDriver):\n def create_node(self, **kwargs): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_nodes(self): ...\n def ex_set_node_configuration(self, node, **kwargs): ...\n def deploy_node(self, **kwargs): ...\n def ex_shutdown_node(self, node): ...\n def ex_destroy_drive(self, drive_uuid): ...\n def _to_node(self, data, ssh_password=None): ...\n\n website = 'http://www.elasticstack.com'\n connectionCls = ElasticStackBaseConnection\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000621.py"} {"focal_file": "libcloud/compute/drivers/gandi.py", "focal_class": null, "focal_method": "list_nodes", "tests": "import unittest\n\nclass Test_list_nodes(unittest.TestCase):\n def test_list_nodes(self):\n nodes = self.driver.list_nodes()\n self.assertTrue(len(nodes) > 0)\n self.assertTrue(len(nodes[0].public_ips) > 1)\n", "method_code": " def list_nodes(self):\n vms = self.connection.request('hosting.vm.list').object\n ips = self.connection.request('hosting.ip.list').object\n for vm in vms:\n vm['ips'] = []\n for ip in ips:\n if vm['ifaces_id'][0] == ip['iface_id']:\n ip = ip.get('ip', None)\n if ip:\n vm['ips'].append(ip)\n nodes = self._to_nodes(vms)\n return nodes\n ", "context": "class GandiNodeDriver(BaseGandiDriverNodeDriver):\n def list_nodes(self): ...\n def __init__(self, *args, **kwargs): ...\n def _resource_info(self, type, id): ...\n def _node_info(self, id): ...\n def _volume_info(self, id): ...\n def _to_node(self, vm): ...\n def _to_nodes(self, vms): ...\n def _to_volume(self, disk): ...\n def _to_volumes(self, disks): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def deploy_node(self, **kwargs): ...\n def create_node(self, **kwargs): ...\n def _to_image(self, img): ...\n def list_images(self, location=None): ...\n def _to_size(self, id, size): ...\n def _instance_type_to_size(self, instance): ...\n def list_instance_type(self, location=None): ...\n def list_sizes(self, location=None): ...\n def _to_loc(self, loc): ...\n def list_locations(self): ...\n def list_volumes(self): ...\n def create_volume(self, size, name, location=None, snapshot=None): ...\n def attach_volume(self, node, volume, device=None): ...\n def detach_volume(self, node, volume): ...\n def destroy_volume(self, volume): ...\n def _to_iface(self, iface): ...\n def _to_ifaces(self, ifaces): ...\n def ex_list_interfaces(self): ...\n def _to_disk(self, element): ...\n def _to_disks(self, elements): ...\n def ex_list_disks(self): ...\n def ex_node_attach_disk(self, node, disk): ...\n def ex_node_detach_disk(self, node, disk): ...\n def ex_node_attach_interface(self, node, iface): ...\n def ex_node_detach_interface(self, node, iface): ...\n def ex_snapshot_disk(self, disk, name=None): ...\n def ex_update_disk(self, disk, new_size=None, new_name=None): ...\n\n api_name = 'gandi'\n friendly_name = 'Gandi.net'\n website = 'http://www.gandi.net/'\n country = 'FR'\n type = Provider.GANDI\n features = {}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_nodes", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000622.py"} {"focal_file": "libcloud/compute/drivers/gandi.py", "focal_class": null, "focal_method": "list_locations", "tests": "import unittest\n\nclass Test_list_locations(unittest.TestCase):\n def test_list_locations(self):\n loc = list(filter(lambda x: 'france' in x.country.lower(), self.driver.list_locations()))[0]\n self.assertEqual(loc.country, 'France')\n", "method_code": " def list_locations(self):\n res = self.connection.request('hosting.datacenter.list')\n return [self._to_loc(l) for l in res.object]\n ", "context": "class GandiNodeDriver(BaseGandiDriverNodeDriver):\n def list_locations(self): ...\n def __init__(self, *args, **kwargs): ...\n def _resource_info(self, type, id): ...\n def _node_info(self, id): ...\n def _volume_info(self, id): ...\n def _to_node(self, vm): ...\n def _to_nodes(self, vms): ...\n def _to_volume(self, disk): ...\n def _to_volumes(self, disks): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def deploy_node(self, **kwargs): ...\n def create_node(self, **kwargs): ...\n def _to_image(self, img): ...\n def list_images(self, location=None): ...\n def _to_size(self, id, size): ...\n def _instance_type_to_size(self, instance): ...\n def list_instance_type(self, location=None): ...\n def list_sizes(self, location=None): ...\n def _to_loc(self, loc): ...\n def list_volumes(self): ...\n def create_volume(self, size, name, location=None, snapshot=None): ...\n def attach_volume(self, node, volume, device=None): ...\n def detach_volume(self, node, volume): ...\n def destroy_volume(self, volume): ...\n def _to_iface(self, iface): ...\n def _to_ifaces(self, ifaces): ...\n def ex_list_interfaces(self): ...\n def _to_disk(self, element): ...\n def _to_disks(self, elements): ...\n def ex_list_disks(self): ...\n def ex_node_attach_disk(self, node, disk): ...\n def ex_node_detach_disk(self, node, disk): ...\n def ex_node_attach_interface(self, node, iface): ...\n def ex_node_detach_interface(self, node, iface): ...\n def ex_snapshot_disk(self, disk, name=None): ...\n def ex_update_disk(self, disk, new_size=None, new_name=None): ...\n\n api_name = 'gandi'\n friendly_name = 'Gandi.net'\n website = 'http://www.gandi.net/'\n country = 'FR'\n type = Provider.GANDI\n features = {}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_locations", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000623.py"} {"focal_file": "libcloud/compute/drivers/gandi.py", "focal_class": null, "focal_method": "list_images", "tests": "import unittest\n\nclass Test_list_images(unittest.TestCase):\n def test_list_images(self):\n loc = list(filter(lambda x: 'france' in x.country.lower(), self.driver.list_locations()))[0]\n images = self.driver.list_images(loc)\n self.assertTrue(len(images) > 2)\n", "method_code": " def list_images(self, location=None):\n try:\n if location:\n filtering = {'datacenter_id': int(location.id)}\n else:\n filtering = {}\n images = self.connection.request('hosting.image.list', filtering)\n return [self._to_image(i) for i in images.object]\n except Exception:\n e = sys.exc_info()[1]\n raise GandiException(1011, e)\n ", "context": "class GandiNodeDriver(BaseGandiDriverNodeDriver):\n def list_images(self, location=None): ...\n def __init__(self, *args, **kwargs): ...\n def _resource_info(self, type, id): ...\n def _node_info(self, id): ...\n def _volume_info(self, id): ...\n def _to_node(self, vm): ...\n def _to_nodes(self, vms): ...\n def _to_volume(self, disk): ...\n def _to_volumes(self, disks): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def deploy_node(self, **kwargs): ...\n def create_node(self, **kwargs): ...\n def _to_image(self, img): ...\n def _to_size(self, id, size): ...\n def _instance_type_to_size(self, instance): ...\n def list_instance_type(self, location=None): ...\n def list_sizes(self, location=None): ...\n def _to_loc(self, loc): ...\n def list_locations(self): ...\n def list_volumes(self): ...\n def create_volume(self, size, name, location=None, snapshot=None): ...\n def attach_volume(self, node, volume, device=None): ...\n def detach_volume(self, node, volume): ...\n def destroy_volume(self, volume): ...\n def _to_iface(self, iface): ...\n def _to_ifaces(self, ifaces): ...\n def ex_list_interfaces(self): ...\n def _to_disk(self, element): ...\n def _to_disks(self, elements): ...\n def ex_list_disks(self): ...\n def ex_node_attach_disk(self, node, disk): ...\n def ex_node_detach_disk(self, node, disk): ...\n def ex_node_attach_interface(self, node, iface): ...\n def ex_node_detach_interface(self, node, iface): ...\n def ex_snapshot_disk(self, disk, name=None): ...\n def ex_update_disk(self, disk, new_size=None, new_name=None): ...\n\n api_name = 'gandi'\n friendly_name = 'Gandi.net'\n website = 'http://www.gandi.net/'\n country = 'FR'\n type = Provider.GANDI\n features = {}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_images", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000624.py"} {"focal_file": "libcloud/compute/drivers/gandi.py", "focal_class": null, "focal_method": "list_sizes", "tests": "import unittest\n\nclass Test_list_sizes(unittest.TestCase):\n def test_list_sizes(self):\n sizes = self.driver.list_sizes()\n self.assertEqual(len(sizes), 4)\n", "method_code": " def list_sizes(self, location=None):\n account = self.connection.request('hosting.account.info').object\n if account.get('rating_enabled'):\n return self.list_instance_type(location)\n available_res = account['resources']['available']\n if available_res['shares'] == 0:\n return None\n else:\n share_def = account['share_definition']\n available_cores = available_res['cores']\n max_core = int(available_cores + 0.75)\n shares = []\n if available_res['servers'] < 1:\n return shares\n for i in range(1, max_core + 1):\n share = {id: i}\n share_is_available = True\n for k in ['memory', 'disk', 'bandwidth']:\n if share_def[k] * i > available_res[k]:\n share_is_available = False\n else:\n share[k] = share_def[k] * i\n if share_is_available:\n nb_core = i\n shares.append(self._to_size(nb_core, share))\n return shares\n ", "context": "class GandiNodeDriver(BaseGandiDriverNodeDriver):\n def list_sizes(self, location=None): ...\n def __init__(self, *args, **kwargs): ...\n def _resource_info(self, type, id): ...\n def _node_info(self, id): ...\n def _volume_info(self, id): ...\n def _to_node(self, vm): ...\n def _to_nodes(self, vms): ...\n def _to_volume(self, disk): ...\n def _to_volumes(self, disks): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def deploy_node(self, **kwargs): ...\n def create_node(self, **kwargs): ...\n def _to_image(self, img): ...\n def list_images(self, location=None): ...\n def _to_size(self, id, size): ...\n def _instance_type_to_size(self, instance): ...\n def list_instance_type(self, location=None): ...\n def _to_loc(self, loc): ...\n def list_locations(self): ...\n def list_volumes(self): ...\n def create_volume(self, size, name, location=None, snapshot=None): ...\n def attach_volume(self, node, volume, device=None): ...\n def detach_volume(self, node, volume): ...\n def destroy_volume(self, volume): ...\n def _to_iface(self, iface): ...\n def _to_ifaces(self, ifaces): ...\n def ex_list_interfaces(self): ...\n def _to_disk(self, element): ...\n def _to_disks(self, elements): ...\n def ex_list_disks(self): ...\n def ex_node_attach_disk(self, node, disk): ...\n def ex_node_detach_disk(self, node, disk): ...\n def ex_node_attach_interface(self, node, iface): ...\n def ex_node_detach_interface(self, node, iface): ...\n def ex_snapshot_disk(self, disk, name=None): ...\n def ex_update_disk(self, disk, new_size=None, new_name=None): ...\n\n api_name = 'gandi'\n friendly_name = 'Gandi.net'\n website = 'http://www.gandi.net/'\n country = 'FR'\n type = Provider.GANDI\n features = {}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_sizes", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000625.py"} {"focal_file": "libcloud/compute/drivers/gandi.py", "focal_class": null, "focal_method": "destroy_node", "tests": "import unittest\n\nclass Test_destroy_node(unittest.TestCase):\n def test_destroy_node_running(self):\n nodes = self.driver.list_nodes()\n test_node = list(filter(lambda x: x.state == NodeState.RUNNING, nodes))[0]\n self.assertTrue(self.driver.destroy_node(test_node))\n\n def test_destroy_node_halted(self):\n nodes = self.driver.list_nodes()\n test_node = list(filter(lambda x: x.state == NodeState.TERMINATED, nodes))[0]\n self.assertTrue(self.driver.destroy_node(test_node))\n", "method_code": " def destroy_node(self, node):\n vm = self._node_info(node.id)\n if vm['state'] == 'running':\n op_stop = self.connection.request('hosting.vm.stop', int(node.id))\n if not self._wait_operation(op_stop.object['id']):\n raise GandiException(1010, 'vm.stop failed')\n op = self.connection.request('hosting.vm.delete', int(node.id))\n if self._wait_operation(op.object['id']):\n return True\n return False\n ", "context": "class GandiNodeDriver(BaseGandiDriverNodeDriver):\n def destroy_node(self, node): ...\n def __init__(self, *args, **kwargs): ...\n def _resource_info(self, type, id): ...\n def _node_info(self, id): ...\n def _volume_info(self, id): ...\n def _to_node(self, vm): ...\n def _to_nodes(self, vms): ...\n def _to_volume(self, disk): ...\n def _to_volumes(self, disks): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def deploy_node(self, **kwargs): ...\n def create_node(self, **kwargs): ...\n def _to_image(self, img): ...\n def list_images(self, location=None): ...\n def _to_size(self, id, size): ...\n def _instance_type_to_size(self, instance): ...\n def list_instance_type(self, location=None): ...\n def list_sizes(self, location=None): ...\n def _to_loc(self, loc): ...\n def list_locations(self): ...\n def list_volumes(self): ...\n def create_volume(self, size, name, location=None, snapshot=None): ...\n def attach_volume(self, node, volume, device=None): ...\n def detach_volume(self, node, volume): ...\n def destroy_volume(self, volume): ...\n def _to_iface(self, iface): ...\n def _to_ifaces(self, ifaces): ...\n def ex_list_interfaces(self): ...\n def _to_disk(self, element): ...\n def _to_disks(self, elements): ...\n def ex_list_disks(self): ...\n def ex_node_attach_disk(self, node, disk): ...\n def ex_node_detach_disk(self, node, disk): ...\n def ex_node_attach_interface(self, node, iface): ...\n def ex_node_detach_interface(self, node, iface): ...\n def ex_snapshot_disk(self, disk, name=None): ...\n def ex_update_disk(self, disk, new_size=None, new_name=None): ...\n\n api_name = 'gandi'\n friendly_name = 'Gandi.net'\n website = 'http://www.gandi.net/'\n country = 'FR'\n type = Provider.GANDI\n features = {}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_destroy_node_running", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000626.py"} {"focal_file": "libcloud/compute/drivers/gandi.py", "focal_class": null, "focal_method": "reboot_node", "tests": "import unittest\n\nclass Test_reboot_node(unittest.TestCase):\n def test_reboot_node(self):\n nodes = self.driver.list_nodes()\n test_node = list(filter(lambda x: x.state == NodeState.RUNNING, nodes))[0]\n self.assertTrue(self.driver.reboot_node(test_node))\n", "method_code": " def reboot_node(self, node):\n op = self.connection.request('hosting.vm.reboot', int(node.id))\n self._wait_operation(op.object['id'])\n vm = self._node_info(int(node.id))\n if vm['state'] == 'running':\n return True\n return False\n ", "context": "class GandiNodeDriver(BaseGandiDriverNodeDriver):\n def reboot_node(self, node): ...\n def __init__(self, *args, **kwargs): ...\n def _resource_info(self, type, id): ...\n def _node_info(self, id): ...\n def _volume_info(self, id): ...\n def _to_node(self, vm): ...\n def _to_nodes(self, vms): ...\n def _to_volume(self, disk): ...\n def _to_volumes(self, disks): ...\n def list_nodes(self): ...\n def destroy_node(self, node): ...\n def deploy_node(self, **kwargs): ...\n def create_node(self, **kwargs): ...\n def _to_image(self, img): ...\n def list_images(self, location=None): ...\n def _to_size(self, id, size): ...\n def _instance_type_to_size(self, instance): ...\n def list_instance_type(self, location=None): ...\n def list_sizes(self, location=None): ...\n def _to_loc(self, loc): ...\n def list_locations(self): ...\n def list_volumes(self): ...\n def create_volume(self, size, name, location=None, snapshot=None): ...\n def attach_volume(self, node, volume, device=None): ...\n def detach_volume(self, node, volume): ...\n def destroy_volume(self, volume): ...\n def _to_iface(self, iface): ...\n def _to_ifaces(self, ifaces): ...\n def ex_list_interfaces(self): ...\n def _to_disk(self, element): ...\n def _to_disks(self, elements): ...\n def ex_list_disks(self): ...\n def ex_node_attach_disk(self, node, disk): ...\n def ex_node_detach_disk(self, node, disk): ...\n def ex_node_attach_interface(self, node, iface): ...\n def ex_node_detach_interface(self, node, iface): ...\n def ex_snapshot_disk(self, disk, name=None): ...\n def ex_update_disk(self, disk, new_size=None, new_name=None): ...\n\n api_name = 'gandi'\n friendly_name = 'Gandi.net'\n website = 'http://www.gandi.net/'\n country = 'FR'\n type = Provider.GANDI\n features = {}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_reboot_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000627.py"} {"focal_file": "libcloud/compute/drivers/gandi.py", "focal_class": null, "focal_method": "create_node", "tests": "import unittest\n\nclass Test_create_node(unittest.TestCase):\n def test_create_node(self):\n login = 'libcloud'\n passwd = ''.join((random.choice(string.ascii_letters) for i in range(10)))\n loc = list(filter(lambda x: 'france' in x.country.lower(), self.driver.list_locations()))[0]\n images = self.driver.list_images(loc)\n images = [x for x in images if x.name.lower().startswith('debian')]\n img = list(filter(lambda x: '5' in x.name, images))[0]\n size = self.driver.list_sizes()[0]\n node = self.driver.create_node(name=self.node_name, login=login, password=passwd, image=img, location=loc, size=size)\n self.assertEqual(node.name, self.node_name)\n", "method_code": " def create_node(self, **kwargs):\n \"\"\"\n Create a new Gandi node\n \n @keyword name: String with a name for this new node (required)\n @type name: C{str}\n \n @keyword image: OS Image to boot on node. (required)\n @type image: L{NodeImage}\n \n @keyword location: Which data center to create a node in. If empty,\n undefined behavior will be selected. (optional)\n @type location: L{NodeLocation}\n \n @keyword size: The size of resources allocated to this node.\n (required)\n @type size: L{NodeSize}\n \n @keyword login: user name to create for login on machine (required)\n @type login: C{str}\n \n @keyword password: password for user that'll be created (required)\n @type password: C{str}\n \n @keyword inet_family: version of ip to use, default 4 (optional)\n @type inet_family: C{int}\n \n @rtype: L{Node}\n \"\"\"\n if kwargs.get('login') is None or kwargs.get('password') is None:\n raise GandiException(1020, 'login and password must be defined for node creation')\n location = kwargs.get('location')\n if location and isinstance(location, NodeLocation):\n dc_id = int(location.id)\n else:\n raise GandiException(1021, 'location must be a subclass of NodeLocation')\n size = kwargs.get('size')\n if not size and (not isinstance(size, NodeSize)):\n raise GandiException(1022, 'size must be a subclass of NodeSize')\n instance = INSTANCE_TYPES.get(size.id)\n cores = instance['cpu'] if instance else int(size.id)\n src_disk_id = int(kwargs['image'].id)\n disk_spec = {'datacenter_id': dc_id, 'name': 'disk_%s' % kwargs['name']}\n vm_spec = {'datacenter_id': dc_id, 'hostname': kwargs['name'], 'login': kwargs['login'], 'password': kwargs['password'], 'memory': int(size.ram), 'cores': cores, 'bandwidth': int(size.bandwidth), 'ip_version': kwargs.get('inet_family', 4)}\n op_disk, op_iface, op_vm = self.connection.request('hosting.vm.create_from', vm_spec, disk_spec, src_disk_id).object\n if self._wait_operation(op_vm['id']):\n node = self._node_info(op_vm['vm_id'])\n ifaces = node.get('ifaces')\n if len(ifaces) > 0:\n ips = ifaces[0].get('ips')\n if len(ips) > 0:\n node['ip'] = ips[0]['ip']\n return self._to_node(node)\n return None\n ", "context": "class GandiNodeDriver(BaseGandiDriverNodeDriver):\n def create_node(self, **kwargs): ...\n def __init__(self, *args, **kwargs): ...\n def _resource_info(self, type, id): ...\n def _node_info(self, id): ...\n def _volume_info(self, id): ...\n def _to_node(self, vm): ...\n def _to_nodes(self, vms): ...\n def _to_volume(self, disk): ...\n def _to_volumes(self, disks): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def deploy_node(self, **kwargs): ...\n def _to_image(self, img): ...\n def list_images(self, location=None): ...\n def _to_size(self, id, size): ...\n def _instance_type_to_size(self, instance): ...\n def list_instance_type(self, location=None): ...\n def list_sizes(self, location=None): ...\n def _to_loc(self, loc): ...\n def list_locations(self): ...\n def list_volumes(self): ...\n def create_volume(self, size, name, location=None, snapshot=None): ...\n def attach_volume(self, node, volume, device=None): ...\n def detach_volume(self, node, volume): ...\n def destroy_volume(self, volume): ...\n def _to_iface(self, iface): ...\n def _to_ifaces(self, ifaces): ...\n def ex_list_interfaces(self): ...\n def _to_disk(self, element): ...\n def _to_disks(self, elements): ...\n def ex_list_disks(self): ...\n def ex_node_attach_disk(self, node, disk): ...\n def ex_node_detach_disk(self, node, disk): ...\n def ex_node_attach_interface(self, node, iface): ...\n def ex_node_detach_interface(self, node, iface): ...\n def ex_snapshot_disk(self, disk, name=None): ...\n def ex_update_disk(self, disk, new_size=None, new_name=None): ...\n\n api_name = 'gandi'\n friendly_name = 'Gandi.net'\n website = 'http://www.gandi.net/'\n country = 'FR'\n type = Provider.GANDI\n features = {}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000628.py"} {"focal_file": "libcloud/compute/drivers/gandi.py", "focal_class": null, "focal_method": "create_volume", "tests": "import unittest\n\nclass Test_create_volume(unittest.TestCase):\n def test_create_volume(self):\n loc = list(filter(lambda x: 'france' in x.country.lower(), self.driver.list_locations()))[0]\n volume = self.driver.create_volume(size=1024, name='libcloud', location=loc)\n self.assertEqual(volume.name, 'libcloud')\n self.assertEqual(volume.size, 1024)\n", "method_code": " def create_volume(self, size, name, location=None, snapshot=None):\n disk_param = {'name': name, 'size': int(size), 'datacenter_id': int(location.id)}\n if snapshot:\n op = self.connection.request('hosting.disk.create_from', disk_param, int(snapshot.id))\n else:\n op = self.connection.request('hosting.disk.create', disk_param)\n if self._wait_operation(op.object['id']):\n disk = self._volume_info(op.object['disk_id'])\n return self._to_volume(disk)\n return None\n ", "context": "class GandiNodeDriver(BaseGandiDriverNodeDriver):\n def create_volume(self, size, name, location=None, snapshot=None): ...\n def __init__(self, *args, **kwargs): ...\n def _resource_info(self, type, id): ...\n def _node_info(self, id): ...\n def _volume_info(self, id): ...\n def _to_node(self, vm): ...\n def _to_nodes(self, vms): ...\n def _to_volume(self, disk): ...\n def _to_volumes(self, disks): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def deploy_node(self, **kwargs): ...\n def create_node(self, **kwargs): ...\n def _to_image(self, img): ...\n def list_images(self, location=None): ...\n def _to_size(self, id, size): ...\n def _instance_type_to_size(self, instance): ...\n def list_instance_type(self, location=None): ...\n def list_sizes(self, location=None): ...\n def _to_loc(self, loc): ...\n def list_locations(self): ...\n def list_volumes(self): ...\n def attach_volume(self, node, volume, device=None): ...\n def detach_volume(self, node, volume): ...\n def destroy_volume(self, volume): ...\n def _to_iface(self, iface): ...\n def _to_ifaces(self, ifaces): ...\n def ex_list_interfaces(self): ...\n def _to_disk(self, element): ...\n def _to_disks(self, elements): ...\n def ex_list_disks(self): ...\n def ex_node_attach_disk(self, node, disk): ...\n def ex_node_detach_disk(self, node, disk): ...\n def ex_node_attach_interface(self, node, iface): ...\n def ex_node_detach_interface(self, node, iface): ...\n def ex_snapshot_disk(self, disk, name=None): ...\n def ex_update_disk(self, disk, new_size=None, new_name=None): ...\n\n api_name = 'gandi'\n friendly_name = 'Gandi.net'\n website = 'http://www.gandi.net/'\n country = 'FR'\n type = Provider.GANDI\n features = {}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_volume", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000629.py"} {"focal_file": "libcloud/compute/drivers/gandi.py", "focal_class": null, "focal_method": "list_volumes", "tests": "import unittest\n\nclass Test_list_volumes(unittest.TestCase):\n def test_list_volumes(self):\n disks = self.driver.list_volumes()\n self.assertTrue(len(disks) > 0)\n", "method_code": " def list_volumes(self):\n \"\"\"\n \n @rtype: C{list} of L{StorageVolume}\n \"\"\"\n res = self.connection.request('hosting.disk.list', {})\n return self._to_volumes(res.object)\n ", "context": "class GandiNodeDriver(BaseGandiDriverNodeDriver):\n def list_volumes(self): ...\n def __init__(self, *args, **kwargs): ...\n def _resource_info(self, type, id): ...\n def _node_info(self, id): ...\n def _volume_info(self, id): ...\n def _to_node(self, vm): ...\n def _to_nodes(self, vms): ...\n def _to_volume(self, disk): ...\n def _to_volumes(self, disks): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def deploy_node(self, **kwargs): ...\n def create_node(self, **kwargs): ...\n def _to_image(self, img): ...\n def list_images(self, location=None): ...\n def _to_size(self, id, size): ...\n def _instance_type_to_size(self, instance): ...\n def list_instance_type(self, location=None): ...\n def list_sizes(self, location=None): ...\n def _to_loc(self, loc): ...\n def list_locations(self): ...\n def create_volume(self, size, name, location=None, snapshot=None): ...\n def attach_volume(self, node, volume, device=None): ...\n def detach_volume(self, node, volume): ...\n def destroy_volume(self, volume): ...\n def _to_iface(self, iface): ...\n def _to_ifaces(self, ifaces): ...\n def ex_list_interfaces(self): ...\n def _to_disk(self, element): ...\n def _to_disks(self, elements): ...\n def ex_list_disks(self): ...\n def ex_node_attach_disk(self, node, disk): ...\n def ex_node_detach_disk(self, node, disk): ...\n def ex_node_attach_interface(self, node, iface): ...\n def ex_node_detach_interface(self, node, iface): ...\n def ex_snapshot_disk(self, disk, name=None): ...\n def ex_update_disk(self, disk, new_size=None, new_name=None): ...\n\n api_name = 'gandi'\n friendly_name = 'Gandi.net'\n website = 'http://www.gandi.net/'\n country = 'FR'\n type = Provider.GANDI\n features = {}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_volumes", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000630.py"} {"focal_file": "libcloud/compute/drivers/gandi.py", "focal_class": null, "focal_method": "destroy_volume", "tests": "import unittest\n\nclass Test_destroy_volume(unittest.TestCase):\n def test_destroy_volume(self):\n volumes = self.driver.list_volumes()\n test_vol = list(filter(lambda x: x.name == 'test_disk', volumes))[0]\n self.assertTrue(self.driver.destroy_volume(test_vol))\n", "method_code": " def destroy_volume(self, volume):\n op = self.connection.request('hosting.disk.delete', int(volume.id))\n if self._wait_operation(op.object['id']):\n return True\n return False\n ", "context": "class GandiNodeDriver(BaseGandiDriverNodeDriver):\n def destroy_volume(self, volume): ...\n def __init__(self, *args, **kwargs): ...\n def _resource_info(self, type, id): ...\n def _node_info(self, id): ...\n def _volume_info(self, id): ...\n def _to_node(self, vm): ...\n def _to_nodes(self, vms): ...\n def _to_volume(self, disk): ...\n def _to_volumes(self, disks): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def deploy_node(self, **kwargs): ...\n def create_node(self, **kwargs): ...\n def _to_image(self, img): ...\n def list_images(self, location=None): ...\n def _to_size(self, id, size): ...\n def _instance_type_to_size(self, instance): ...\n def list_instance_type(self, location=None): ...\n def list_sizes(self, location=None): ...\n def _to_loc(self, loc): ...\n def list_locations(self): ...\n def list_volumes(self): ...\n def create_volume(self, size, name, location=None, snapshot=None): ...\n def attach_volume(self, node, volume, device=None): ...\n def detach_volume(self, node, volume): ...\n def _to_iface(self, iface): ...\n def _to_ifaces(self, ifaces): ...\n def ex_list_interfaces(self): ...\n def _to_disk(self, element): ...\n def _to_disks(self, elements): ...\n def ex_list_disks(self): ...\n def ex_node_attach_disk(self, node, disk): ...\n def ex_node_detach_disk(self, node, disk): ...\n def ex_node_attach_interface(self, node, iface): ...\n def ex_node_detach_interface(self, node, iface): ...\n def ex_snapshot_disk(self, disk, name=None): ...\n def ex_update_disk(self, disk, new_size=None, new_name=None): ...\n\n api_name = 'gandi'\n friendly_name = 'Gandi.net'\n website = 'http://www.gandi.net/'\n country = 'FR'\n type = Provider.GANDI\n features = {}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_destroy_volume", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000631.py"} {"focal_file": "libcloud/compute/drivers/gandi.py", "focal_class": null, "focal_method": "attach_volume", "tests": "import unittest\n\nclass Test_attach_volume(unittest.TestCase):\n def test_attach_volume(self):\n disks = self.driver.list_volumes()\n nodes = self.driver.list_nodes()\n res = self.driver.attach_volume(nodes[0], disks[0])\n self.assertTrue(res)\n", "method_code": " def attach_volume(self, node, volume, device=None):\n op = self.connection.request('hosting.vm.disk_attach', int(node.id), int(volume.id))\n if self._wait_operation(op.object['id']):\n return True\n return False\n ", "context": "class GandiNodeDriver(BaseGandiDriverNodeDriver):\n def attach_volume(self, node, volume, device=None): ...\n def __init__(self, *args, **kwargs): ...\n def _resource_info(self, type, id): ...\n def _node_info(self, id): ...\n def _volume_info(self, id): ...\n def _to_node(self, vm): ...\n def _to_nodes(self, vms): ...\n def _to_volume(self, disk): ...\n def _to_volumes(self, disks): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def deploy_node(self, **kwargs): ...\n def create_node(self, **kwargs): ...\n def _to_image(self, img): ...\n def list_images(self, location=None): ...\n def _to_size(self, id, size): ...\n def _instance_type_to_size(self, instance): ...\n def list_instance_type(self, location=None): ...\n def list_sizes(self, location=None): ...\n def _to_loc(self, loc): ...\n def list_locations(self): ...\n def list_volumes(self): ...\n def create_volume(self, size, name, location=None, snapshot=None): ...\n def detach_volume(self, node, volume): ...\n def destroy_volume(self, volume): ...\n def _to_iface(self, iface): ...\n def _to_ifaces(self, ifaces): ...\n def ex_list_interfaces(self): ...\n def _to_disk(self, element): ...\n def _to_disks(self, elements): ...\n def ex_list_disks(self): ...\n def ex_node_attach_disk(self, node, disk): ...\n def ex_node_detach_disk(self, node, disk): ...\n def ex_node_attach_interface(self, node, iface): ...\n def ex_node_detach_interface(self, node, iface): ...\n def ex_snapshot_disk(self, disk, name=None): ...\n def ex_update_disk(self, disk, new_size=None, new_name=None): ...\n\n api_name = 'gandi'\n friendly_name = 'Gandi.net'\n website = 'http://www.gandi.net/'\n country = 'FR'\n type = Provider.GANDI\n features = {}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_attach_volume", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000632.py"} {"focal_file": "libcloud/compute/drivers/gandi.py", "focal_class": null, "focal_method": "detach_volume", "tests": "import unittest\n\nclass Test_detach_volume(unittest.TestCase):\n def test_detach_volume(self):\n disks = self.driver.list_volumes()\n nodes = self.driver.list_nodes()\n res = self.driver.detach_volume(nodes[0], disks[0])\n self.assertTrue(res)\n", "method_code": " def detach_volume(self, node, volume):\n \"\"\"\n Detaches a volume from a node.\n \n @param node: Node which should be used\n @type node: L{Node}\n \n @param volume: Volume to be detached\n @type volume: L{StorageVolume}\n \n @rtype: C{bool}\n \"\"\"\n op = self.connection.request('hosting.vm.disk_detach', int(node.id), int(volume.id))\n if self._wait_operation(op.object['id']):\n return True\n return False\n ", "context": "class GandiNodeDriver(BaseGandiDriverNodeDriver):\n def detach_volume(self, node, volume): ...\n def __init__(self, *args, **kwargs): ...\n def _resource_info(self, type, id): ...\n def _node_info(self, id): ...\n def _volume_info(self, id): ...\n def _to_node(self, vm): ...\n def _to_nodes(self, vms): ...\n def _to_volume(self, disk): ...\n def _to_volumes(self, disks): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def deploy_node(self, **kwargs): ...\n def create_node(self, **kwargs): ...\n def _to_image(self, img): ...\n def list_images(self, location=None): ...\n def _to_size(self, id, size): ...\n def _instance_type_to_size(self, instance): ...\n def list_instance_type(self, location=None): ...\n def list_sizes(self, location=None): ...\n def _to_loc(self, loc): ...\n def list_locations(self): ...\n def list_volumes(self): ...\n def create_volume(self, size, name, location=None, snapshot=None): ...\n def attach_volume(self, node, volume, device=None): ...\n def destroy_volume(self, volume): ...\n def _to_iface(self, iface): ...\n def _to_ifaces(self, ifaces): ...\n def ex_list_interfaces(self): ...\n def _to_disk(self, element): ...\n def _to_disks(self, elements): ...\n def ex_list_disks(self): ...\n def ex_node_attach_disk(self, node, disk): ...\n def ex_node_detach_disk(self, node, disk): ...\n def ex_node_attach_interface(self, node, iface): ...\n def ex_node_detach_interface(self, node, iface): ...\n def ex_snapshot_disk(self, disk, name=None): ...\n def ex_update_disk(self, disk, new_size=None, new_name=None): ...\n\n api_name = 'gandi'\n friendly_name = 'Gandi.net'\n website = 'http://www.gandi.net/'\n country = 'FR'\n type = Provider.GANDI\n features = {}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_detach_volume", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000633.py"} {"focal_file": "libcloud/compute/drivers/gandi.py", "focal_class": null, "focal_method": "ex_list_interfaces", "tests": "import unittest\n\nclass Test_ex_list_interfaces(unittest.TestCase):\n def test_ex_list_interfaces(self):\n ifaces = self.driver.ex_list_interfaces()\n self.assertTrue(len(ifaces) > 0)\n", "method_code": " def ex_list_interfaces(self):\n \"\"\"\n Specific method to list network interfaces\n \n @rtype: C{list} of L{GandiNetworkInterface}\n \"\"\"\n ifaces = self.connection.request('hosting.iface.list').object\n ips = self.connection.request('hosting.ip.list').object\n for iface in ifaces:\n iface['ips'] = list(filter(lambda i: i['iface_id'] == iface['id'], ips))\n return self._to_ifaces(ifaces)\n ", "context": "class GandiNodeDriver(BaseGandiDriverNodeDriver):\n def ex_list_interfaces(self): ...\n def __init__(self, *args, **kwargs): ...\n def _resource_info(self, type, id): ...\n def _node_info(self, id): ...\n def _volume_info(self, id): ...\n def _to_node(self, vm): ...\n def _to_nodes(self, vms): ...\n def _to_volume(self, disk): ...\n def _to_volumes(self, disks): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def deploy_node(self, **kwargs): ...\n def create_node(self, **kwargs): ...\n def _to_image(self, img): ...\n def list_images(self, location=None): ...\n def _to_size(self, id, size): ...\n def _instance_type_to_size(self, instance): ...\n def list_instance_type(self, location=None): ...\n def list_sizes(self, location=None): ...\n def _to_loc(self, loc): ...\n def list_locations(self): ...\n def list_volumes(self): ...\n def create_volume(self, size, name, location=None, snapshot=None): ...\n def attach_volume(self, node, volume, device=None): ...\n def detach_volume(self, node, volume): ...\n def destroy_volume(self, volume): ...\n def _to_iface(self, iface): ...\n def _to_ifaces(self, ifaces): ...\n def _to_disk(self, element): ...\n def _to_disks(self, elements): ...\n def ex_list_disks(self): ...\n def ex_node_attach_disk(self, node, disk): ...\n def ex_node_detach_disk(self, node, disk): ...\n def ex_node_attach_interface(self, node, iface): ...\n def ex_node_detach_interface(self, node, iface): ...\n def ex_snapshot_disk(self, disk, name=None): ...\n def ex_update_disk(self, disk, new_size=None, new_name=None): ...\n\n api_name = 'gandi'\n friendly_name = 'Gandi.net'\n website = 'http://www.gandi.net/'\n country = 'FR'\n type = Provider.GANDI\n features = {}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_list_interfaces", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000634.py"} {"focal_file": "libcloud/compute/drivers/gandi.py", "focal_class": null, "focal_method": "ex_node_attach_interface", "tests": "import unittest\n\nclass Test_ex_node_attach_interface(unittest.TestCase):\n def test_ex_attach_interface(self):\n ifaces = self.driver.ex_list_interfaces()\n nodes = self.driver.list_nodes()\n res = self.driver.ex_node_attach_interface(nodes[0], ifaces[0])\n self.assertTrue(res)\n", "method_code": " def ex_node_attach_interface(self, node, iface):\n \"\"\"\n Specific method to attach an interface to a node\n \n @param node: Node which should be used\n @type node: L{Node}\n \n \n @param iface: Network interface which should be used\n @type iface: L{GandiNetworkInterface}\n \n @rtype: C{bool}\n \"\"\"\n op = self.connection.request('hosting.vm.iface_attach', int(node.id), int(iface.id))\n if self._wait_operation(op.object['id']):\n return True\n return False\n ", "context": "class GandiNodeDriver(BaseGandiDriverNodeDriver):\n def ex_node_attach_interface(self, node, iface): ...\n def __init__(self, *args, **kwargs): ...\n def _resource_info(self, type, id): ...\n def _node_info(self, id): ...\n def _volume_info(self, id): ...\n def _to_node(self, vm): ...\n def _to_nodes(self, vms): ...\n def _to_volume(self, disk): ...\n def _to_volumes(self, disks): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def deploy_node(self, **kwargs): ...\n def create_node(self, **kwargs): ...\n def _to_image(self, img): ...\n def list_images(self, location=None): ...\n def _to_size(self, id, size): ...\n def _instance_type_to_size(self, instance): ...\n def list_instance_type(self, location=None): ...\n def list_sizes(self, location=None): ...\n def _to_loc(self, loc): ...\n def list_locations(self): ...\n def list_volumes(self): ...\n def create_volume(self, size, name, location=None, snapshot=None): ...\n def attach_volume(self, node, volume, device=None): ...\n def detach_volume(self, node, volume): ...\n def destroy_volume(self, volume): ...\n def _to_iface(self, iface): ...\n def _to_ifaces(self, ifaces): ...\n def ex_list_interfaces(self): ...\n def _to_disk(self, element): ...\n def _to_disks(self, elements): ...\n def ex_list_disks(self): ...\n def ex_node_attach_disk(self, node, disk): ...\n def ex_node_detach_disk(self, node, disk): ...\n def ex_node_detach_interface(self, node, iface): ...\n def ex_snapshot_disk(self, disk, name=None): ...\n def ex_update_disk(self, disk, new_size=None, new_name=None): ...\n\n api_name = 'gandi'\n friendly_name = 'Gandi.net'\n website = 'http://www.gandi.net/'\n country = 'FR'\n type = Provider.GANDI\n features = {}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_attach_interface", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000635.py"} {"focal_file": "libcloud/compute/drivers/gandi.py", "focal_class": null, "focal_method": "ex_node_detach_interface", "tests": "import unittest\n\nclass Test_ex_node_detach_interface(unittest.TestCase):\n def test_ex_detach_interface(self):\n ifaces = self.driver.ex_list_interfaces()\n nodes = self.driver.list_nodes()\n res = self.driver.ex_node_detach_interface(nodes[0], ifaces[0])\n self.assertTrue(res)\n", "method_code": " def ex_node_detach_interface(self, node, iface):\n \"\"\"\n Specific method to detach an interface from a node\n \n @param node: Node which should be used\n @type node: L{Node}\n \n \n @param iface: Network interface which should be used\n @type iface: L{GandiNetworkInterface}\n \n @rtype: C{bool}\n \"\"\"\n op = self.connection.request('hosting.vm.iface_detach', int(node.id), int(iface.id))\n if self._wait_operation(op.object['id']):\n return True\n return False\n ", "context": "class GandiNodeDriver(BaseGandiDriverNodeDriver):\n def ex_node_detach_interface(self, node, iface): ...\n def __init__(self, *args, **kwargs): ...\n def _resource_info(self, type, id): ...\n def _node_info(self, id): ...\n def _volume_info(self, id): ...\n def _to_node(self, vm): ...\n def _to_nodes(self, vms): ...\n def _to_volume(self, disk): ...\n def _to_volumes(self, disks): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def deploy_node(self, **kwargs): ...\n def create_node(self, **kwargs): ...\n def _to_image(self, img): ...\n def list_images(self, location=None): ...\n def _to_size(self, id, size): ...\n def _instance_type_to_size(self, instance): ...\n def list_instance_type(self, location=None): ...\n def list_sizes(self, location=None): ...\n def _to_loc(self, loc): ...\n def list_locations(self): ...\n def list_volumes(self): ...\n def create_volume(self, size, name, location=None, snapshot=None): ...\n def attach_volume(self, node, volume, device=None): ...\n def detach_volume(self, node, volume): ...\n def destroy_volume(self, volume): ...\n def _to_iface(self, iface): ...\n def _to_ifaces(self, ifaces): ...\n def ex_list_interfaces(self): ...\n def _to_disk(self, element): ...\n def _to_disks(self, elements): ...\n def ex_list_disks(self): ...\n def ex_node_attach_disk(self, node, disk): ...\n def ex_node_detach_disk(self, node, disk): ...\n def ex_node_attach_interface(self, node, iface): ...\n def ex_snapshot_disk(self, disk, name=None): ...\n def ex_update_disk(self, disk, new_size=None, new_name=None): ...\n\n api_name = 'gandi'\n friendly_name = 'Gandi.net'\n website = 'http://www.gandi.net/'\n country = 'FR'\n type = Provider.GANDI\n features = {}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_detach_interface", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 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": "libcloud/compute/drivers/gandi.py", "focal_class": null, "focal_method": "ex_snapshot_disk", "tests": "import unittest\n\nclass Test_ex_snapshot_disk(unittest.TestCase):\n def test_ex_snapshot_disk(self):\n disks = self.driver.list_volumes()\n self.assertTrue(self.driver.ex_snapshot_disk(disks[2]))\n self.assertRaises(GandiException, self.driver.ex_snapshot_disk, disks[0])\n", "method_code": " def ex_snapshot_disk(self, disk, name=None):\n \"\"\"\n Specific method to make a snapshot of a disk\n \n @param disk: Disk which should be used\n @type disk: L{GandiDisk}\n \n @param name: Name which should be used\n @type name: C{str}\n \n @rtype: C{bool}\n \"\"\"\n if not disk.extra.get('can_snapshot'):\n raise GandiException(1021, \"Disk %s can't snapshot\" % disk.id)\n if not name:\n suffix = datetime.today().strftime('%Y%m%d')\n name = 'snap_%s' % suffix\n op = self.connection.request('hosting.disk.create_from', {'name': name, 'type': 'snapshot'}, int(disk.id))\n if self._wait_operation(op.object['id']):\n return True\n return False\n ", "context": "class GandiNodeDriver(BaseGandiDriverNodeDriver):\n def ex_snapshot_disk(self, disk, name=None): ...\n def __init__(self, *args, **kwargs): ...\n def _resource_info(self, type, id): ...\n def _node_info(self, id): ...\n def _volume_info(self, id): ...\n def _to_node(self, vm): ...\n def _to_nodes(self, vms): ...\n def _to_volume(self, disk): ...\n def _to_volumes(self, disks): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def deploy_node(self, **kwargs): ...\n def create_node(self, **kwargs): ...\n def _to_image(self, img): ...\n def list_images(self, location=None): ...\n def _to_size(self, id, size): ...\n def _instance_type_to_size(self, instance): ...\n def list_instance_type(self, location=None): ...\n def list_sizes(self, location=None): ...\n def _to_loc(self, loc): ...\n def list_locations(self): ...\n def list_volumes(self): ...\n def create_volume(self, size, name, location=None, snapshot=None): ...\n def attach_volume(self, node, volume, device=None): ...\n def detach_volume(self, node, volume): ...\n def destroy_volume(self, volume): ...\n def _to_iface(self, iface): ...\n def _to_ifaces(self, ifaces): ...\n def ex_list_interfaces(self): ...\n def _to_disk(self, element): ...\n def _to_disks(self, elements): ...\n def ex_list_disks(self): ...\n def ex_node_attach_disk(self, node, disk): ...\n def ex_node_detach_disk(self, node, disk): ...\n def ex_node_attach_interface(self, node, iface): ...\n def ex_node_detach_interface(self, node, iface): ...\n def ex_update_disk(self, disk, new_size=None, new_name=None): ...\n\n api_name = 'gandi'\n friendly_name = 'Gandi.net'\n website = 'http://www.gandi.net/'\n country = 'FR'\n type = Provider.GANDI\n features = {}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_snapshot_disk", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000637.py"} {"focal_file": "libcloud/compute/drivers/gandi.py", "focal_class": null, "focal_method": "ex_update_disk", "tests": "import unittest\n\nclass Test_ex_update_disk(unittest.TestCase):\n def test_ex_update_disk(self):\n disks = self.driver.list_volumes()\n self.assertTrue(self.driver.ex_update_disk(disks[0], new_size=4096))\n", "method_code": " def ex_update_disk(self, disk, new_size=None, new_name=None):\n \"\"\"Specific method to update size or name of a disk\n WARNING: if a server is attached it'll be rebooted\n \n @param disk: Disk which should be used\n @type disk: L{GandiDisk}\n \n @param new_size: New size\n @type new_size: C{int}\n \n @param new_name: New name\n @type new_name: C{str}\n \n @rtype: C{bool}\n \"\"\"\n params = {}\n if new_size:\n params.update({'size': new_size})\n if new_name:\n params.update({'name': new_name})\n op = self.connection.request('hosting.disk.update', int(disk.id), params)\n if self._wait_operation(op.object['id']):\n return True\n return False\n ", "context": "class GandiNodeDriver(BaseGandiDriverNodeDriver):\n def ex_update_disk(self, disk, new_size=None, new_name=None): ...\n def __init__(self, *args, **kwargs): ...\n def _resource_info(self, type, id): ...\n def _node_info(self, id): ...\n def _volume_info(self, id): ...\n def _to_node(self, vm): ...\n def _to_nodes(self, vms): ...\n def _to_volume(self, disk): ...\n def _to_volumes(self, disks): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def deploy_node(self, **kwargs): ...\n def create_node(self, **kwargs): ...\n def _to_image(self, img): ...\n def list_images(self, location=None): ...\n def _to_size(self, id, size): ...\n def _instance_type_to_size(self, instance): ...\n def list_instance_type(self, location=None): ...\n def list_sizes(self, location=None): ...\n def _to_loc(self, loc): ...\n def list_locations(self): ...\n def list_volumes(self): ...\n def create_volume(self, size, name, location=None, snapshot=None): ...\n def attach_volume(self, node, volume, device=None): ...\n def detach_volume(self, node, volume): ...\n def destroy_volume(self, volume): ...\n def _to_iface(self, iface): ...\n def _to_ifaces(self, ifaces): ...\n def ex_list_interfaces(self): ...\n def _to_disk(self, element): ...\n def _to_disks(self, elements): ...\n def ex_list_disks(self): ...\n def ex_node_attach_disk(self, node, disk): ...\n def ex_node_detach_disk(self, node, disk): ...\n def ex_node_attach_interface(self, node, iface): ...\n def ex_node_detach_interface(self, node, iface): ...\n def ex_snapshot_disk(self, disk, name=None): ...\n\n api_name = 'gandi'\n friendly_name = 'Gandi.net'\n website = 'http://www.gandi.net/'\n country = 'FR'\n type = Provider.GANDI\n features = {}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_update_disk", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/compute/drivers/gogrid.py", "focal_class": null, "focal_method": "create_node", "tests": "import unittest\n\nclass Test_create_node(unittest.TestCase):\n def test_create_node(self):\n image = NodeImage(1531, None, self.driver)\n node = self.driver.create_node(name='test1', image=image, size=self._get_test_512Mb_node_size())\n self.assertEqual(node.name, 'test1')\n self.assertTrue(node.id is not None)\n self.assertEqual(node.extra['password'], 'bebebe')\n", "method_code": " def create_node(self, **kwargs):\n \"\"\"Create a new GoGird node\n \n @inherits: L{NodeDriver.create_node}\n \n @keyword ex_description: Description of a Node\n @type ex_description: C{str}\n \n @keyword ex_ip: Public IP address to use for a Node. If not\n specified, first available IP address will be picked\n @type ex_ip: C{str}\n \n @rtype: L{GoGridNode}\n \"\"\"\n node = self.ex_create_node_nowait(**kwargs)\n timeout = 60 * 20\n waittime = 0\n interval = 2 * 60\n while node.id is None and waittime < timeout:\n nodes = self.list_nodes()\n for i in nodes:\n if i.public_ips[0] == node.public_ips[0] and i.id is not None:\n return i\n waittime += interval\n time.sleep(interval)\n if id is None:\n raise Exception(\"Wasn't able to wait for id allocation for the node %s\" % str(node))\n return node\n ", "context": "class GoGridNodeDriver(BaseGoGridDriverNodeDriver):\n def create_node(self, **kwargs): ...\n def __init__(self, *args, **kwargs): ...\n def _get_state(self, element): ...\n def _get_ip(self, element): ...\n def _get_id(self, element): ...\n def _to_node(self, element, password=None): ...\n def _to_image(self, element): ...\n def _to_images(self, object): ...\n def _to_location(self, element): ...\n def _to_locations(self, object): ...\n def list_images(self, location=None): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def _server_list(self): ...\n def _password_list(self): ...\n def _server_power(self, id, power): ...\n def _server_delete(self, id): ...\n def _get_first_ip(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def ex_create_node_nowait(self, **kwargs): ...\n def ex_save_image(self, node, name): ...\n def ex_edit_node(self, **kwargs): ...\n def ex_edit_image(self, **kwargs): ...\n def ex_list_ips(self, **kwargs): ...\n\n connectionCls = GoGridConnection\n type = Provider.GOGRID\n api_name = 'gogrid'\n name = 'GoGrid'\n website = 'http://www.gogrid.com/'\n features = {'create_node': ['generates_password']}\n _instance_types = GOGRID_INSTANCE_TYPES\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000639.py"} {"focal_file": "libcloud/compute/drivers/gogrid.py", "focal_class": null, "focal_method": "list_nodes", "tests": "import unittest\n\nclass Test_list_nodes(unittest.TestCase):\n def test_list_nodes(self):\n node = self.driver.list_nodes()[0]\n self.assertEqual(node.id, '90967')\n self.assertEqual(node.extra['password'], 'bebebe')\n self.assertEqual(node.extra['description'], 'test server')\n", "method_code": " def list_nodes(self):\n \"\"\"\n @inherits: L{NodeDriver.list_nodes}\n @rtype: C{list} of L{GoGridNode}\n \"\"\"\n passwords_map = {}\n res = self._server_list()\n try:\n for password in self._password_list()['list']:\n try:\n passwords_map[password['server']['id']] = password['password']\n except KeyError:\n pass\n except InvalidCredsError:\n pass\n return [self._to_node(el, passwords_map.get(el.get('id'))) for el in res['list']]\n ", "context": "class GoGridNodeDriver(BaseGoGridDriverNodeDriver):\n def list_nodes(self): ...\n def __init__(self, *args, **kwargs): ...\n def _get_state(self, element): ...\n def _get_ip(self, element): ...\n def _get_id(self, element): ...\n def _to_node(self, element, password=None): ...\n def _to_image(self, element): ...\n def _to_images(self, object): ...\n def _to_location(self, element): ...\n def _to_locations(self, object): ...\n def list_images(self, location=None): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def _server_list(self): ...\n def _password_list(self): ...\n def _server_power(self, id, power): ...\n def _server_delete(self, id): ...\n def _get_first_ip(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def ex_create_node_nowait(self, **kwargs): ...\n def create_node(self, **kwargs): ...\n def ex_save_image(self, node, name): ...\n def ex_edit_node(self, **kwargs): ...\n def ex_edit_image(self, **kwargs): ...\n def ex_list_ips(self, **kwargs): ...\n\n connectionCls = GoGridConnection\n type = Provider.GOGRID\n api_name = 'gogrid'\n name = 'GoGrid'\n website = 'http://www.gogrid.com/'\n features = {'create_node': ['generates_password']}\n _instance_types = GOGRID_INSTANCE_TYPES\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_nodes", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000640.py"} {"focal_file": "libcloud/compute/drivers/gogrid.py", "focal_class": null, "focal_method": "reboot_node", "tests": "import unittest\n\nclass Test_reboot_node(unittest.TestCase):\n def test_reboot_node(self):\n node = Node(90967, None, None, None, None, self.driver)\n ret = self.driver.reboot_node(node)\n self.assertTrue(ret)\n", "method_code": " def reboot_node(self, node):\n \"\"\"\n @inherits: L{NodeDriver.reboot_node}\n @type node: L{GoGridNode}\n \"\"\"\n id = node.id\n power = 'restart'\n res = self._server_power(id, power)\n if not res.success():\n raise Exception(res.parse_error())\n return True\n ", "context": "class GoGridNodeDriver(BaseGoGridDriverNodeDriver):\n def reboot_node(self, node): ...\n def __init__(self, *args, **kwargs): ...\n def _get_state(self, element): ...\n def _get_ip(self, element): ...\n def _get_id(self, element): ...\n def _to_node(self, element, password=None): ...\n def _to_image(self, element): ...\n def _to_images(self, object): ...\n def _to_location(self, element): ...\n def _to_locations(self, object): ...\n def list_images(self, location=None): ...\n def list_nodes(self): ...\n def destroy_node(self, node): ...\n def _server_list(self): ...\n def _password_list(self): ...\n def _server_power(self, id, power): ...\n def _server_delete(self, id): ...\n def _get_first_ip(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def ex_create_node_nowait(self, **kwargs): ...\n def create_node(self, **kwargs): ...\n def ex_save_image(self, node, name): ...\n def ex_edit_node(self, **kwargs): ...\n def ex_edit_image(self, **kwargs): ...\n def ex_list_ips(self, **kwargs): ...\n\n connectionCls = GoGridConnection\n type = Provider.GOGRID\n api_name = 'gogrid'\n name = 'GoGrid'\n website = 'http://www.gogrid.com/'\n features = {'create_node': ['generates_password']}\n _instance_types = GOGRID_INSTANCE_TYPES\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_reboot_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/compute/drivers/gogrid.py", "focal_class": null, "focal_method": "destroy_node", "tests": "import unittest\n\nclass Test_destroy_node(unittest.TestCase):\n def test_destroy_node(self):\n node = Node(90967, None, None, None, None, self.driver)\n ret = self.driver.destroy_node(node)\n self.assertTrue(ret)\n", "method_code": " def destroy_node(self, node):\n \"\"\"\n @inherits: L{NodeDriver.reboot_node}\n @type node: L{GoGridNode}\n \"\"\"\n id = node.id\n res = self._server_delete(id)\n if not res.success():\n raise Exception(res.parse_error())\n return True\n ", "context": "class GoGridNodeDriver(BaseGoGridDriverNodeDriver):\n def destroy_node(self, node): ...\n def __init__(self, *args, **kwargs): ...\n def _get_state(self, element): ...\n def _get_ip(self, element): ...\n def _get_id(self, element): ...\n def _to_node(self, element, password=None): ...\n def _to_image(self, element): ...\n def _to_images(self, object): ...\n def _to_location(self, element): ...\n def _to_locations(self, object): ...\n def list_images(self, location=None): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def _server_list(self): ...\n def _password_list(self): ...\n def _server_power(self, id, power): ...\n def _server_delete(self, id): ...\n def _get_first_ip(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def ex_create_node_nowait(self, **kwargs): ...\n def create_node(self, **kwargs): ...\n def ex_save_image(self, node, name): ...\n def ex_edit_node(self, **kwargs): ...\n def ex_edit_image(self, **kwargs): ...\n def ex_list_ips(self, **kwargs): ...\n\n connectionCls = GoGridConnection\n type = Provider.GOGRID\n api_name = 'gogrid'\n name = 'GoGrid'\n website = 'http://www.gogrid.com/'\n features = {'create_node': ['generates_password']}\n _instance_types = GOGRID_INSTANCE_TYPES\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_destroy_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/compute/drivers/gogrid.py", "focal_class": null, "focal_method": "list_images", "tests": "import unittest\n\nclass Test_list_images(unittest.TestCase):\n def test_list_images(self):\n images = self.driver.list_images()\n image = images[0]\n self.assertEqual(len(images), 4)\n self.assertEqual(image.name, 'CentOS 5.3 (32-bit) w/ None')\n self.assertEqual(image.id, '1531')\n location = NodeLocation(id='gogrid/GSI-939ef909-84b8-4a2f-ad56-02ccd7da05ff.img', name='test location', country='Slovenia', driver=self.driver)\n images = self.driver.list_images(location=location)\n image = images[0]\n self.assertEqual(len(images), 4)\n self.assertEqual(image.name, 'CentOS 5.3 (32-bit) w/ None')\n self.assertEqual(image.id, '1531')\n", "method_code": " def list_images(self, location=None):\n params = {}\n if location is not None:\n params['datacenter'] = location.id\n images = self._to_images(self.connection.request('/api/grid/image/list', params).object)\n return images\n ", "context": "class GoGridNodeDriver(BaseGoGridDriverNodeDriver):\n def list_images(self, location=None): ...\n def __init__(self, *args, **kwargs): ...\n def _get_state(self, element): ...\n def _get_ip(self, element): ...\n def _get_id(self, element): ...\n def _to_node(self, element, password=None): ...\n def _to_image(self, element): ...\n def _to_images(self, object): ...\n def _to_location(self, element): ...\n def _to_locations(self, object): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def _server_list(self): ...\n def _password_list(self): ...\n def _server_power(self, id, power): ...\n def _server_delete(self, id): ...\n def _get_first_ip(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def ex_create_node_nowait(self, **kwargs): ...\n def create_node(self, **kwargs): ...\n def ex_save_image(self, node, name): ...\n def ex_edit_node(self, **kwargs): ...\n def ex_edit_image(self, **kwargs): ...\n def ex_list_ips(self, **kwargs): ...\n\n connectionCls = GoGridConnection\n type = Provider.GOGRID\n api_name = 'gogrid'\n name = 'GoGrid'\n website = 'http://www.gogrid.com/'\n features = {'create_node': ['generates_password']}\n _instance_types = GOGRID_INSTANCE_TYPES\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_images", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000643.py"} {"focal_file": "libcloud/compute/drivers/gogrid.py", "focal_class": null, "focal_method": "list_locations", "tests": "import unittest\n\nclass Test_list_locations(unittest.TestCase):\n def test_list_locations(self):\n locations = self.driver.list_locations()\n location_names = [location.name for location in locations]\n self.assertEqual(len(locations), 2)\n for i in (0, 1):\n self.assertTrue(isinstance(locations[i], NodeLocation))\n self.assertTrue('US-West-1' in location_names)\n self.assertTrue('US-East-1' in location_names)\n", "method_code": " def list_locations(self):\n locations = self._to_locations(self.connection.request('/api/common/lookup/list', params={'lookup': 'ip.datacenter'}).object)\n return locations\n ", "context": "class GoGridNodeDriver(BaseGoGridDriverNodeDriver):\n def list_locations(self): ...\n def __init__(self, *args, **kwargs): ...\n def _get_state(self, element): ...\n def _get_ip(self, element): ...\n def _get_id(self, element): ...\n def _to_node(self, element, password=None): ...\n def _to_image(self, element): ...\n def _to_images(self, object): ...\n def _to_location(self, element): ...\n def _to_locations(self, object): ...\n def list_images(self, location=None): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def _server_list(self): ...\n def _password_list(self): ...\n def _server_power(self, id, power): ...\n def _server_delete(self, id): ...\n def _get_first_ip(self, location=None): ...\n def list_sizes(self, location=None): ...\n def ex_create_node_nowait(self, **kwargs): ...\n def create_node(self, **kwargs): ...\n def ex_save_image(self, node, name): ...\n def ex_edit_node(self, **kwargs): ...\n def ex_edit_image(self, **kwargs): ...\n def ex_list_ips(self, **kwargs): ...\n\n connectionCls = GoGridConnection\n type = Provider.GOGRID\n api_name = 'gogrid'\n name = 'GoGrid'\n website = 'http://www.gogrid.com/'\n features = {'create_node': ['generates_password']}\n _instance_types = GOGRID_INSTANCE_TYPES\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_locations", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000644.py"} {"focal_file": "libcloud/compute/drivers/gogrid.py", "focal_class": null, "focal_method": "ex_save_image", "tests": "import unittest\n\nclass Test_ex_save_image(unittest.TestCase):\n def test_ex_save_image(self):\n node = self.driver.list_nodes()[0]\n image = self.driver.ex_save_image(node, 'testimage')\n self.assertEqual(image.name, 'testimage')\n", "method_code": " def ex_save_image(self, node, name):\n \"\"\"Create an image for node.\n \n Please refer to GoGrid documentation to get info\n how prepare a node for image creation:\n \n http://wiki.gogrid.com/wiki/index.php/MyGSI\n \n @keyword node: node to use as a base for image\n @type node: L{GoGridNode}\n \n @keyword name: name for new image\n @type name: C{str}\n \n @rtype: L{NodeImage}\n \"\"\"\n params = {'server': node.id, 'friendlyName': name}\n object = self.connection.request('/api/grid/image/save', params=params, method='POST').object\n return self._to_images(object)[0]\n ", "context": "class GoGridNodeDriver(BaseGoGridDriverNodeDriver):\n def ex_save_image(self, node, name): ...\n def __init__(self, *args, **kwargs): ...\n def _get_state(self, element): ...\n def _get_ip(self, element): ...\n def _get_id(self, element): ...\n def _to_node(self, element, password=None): ...\n def _to_image(self, element): ...\n def _to_images(self, object): ...\n def _to_location(self, element): ...\n def _to_locations(self, object): ...\n def list_images(self, location=None): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def _server_list(self): ...\n def _password_list(self): ...\n def _server_power(self, id, power): ...\n def _server_delete(self, id): ...\n def _get_first_ip(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def ex_create_node_nowait(self, **kwargs): ...\n def create_node(self, **kwargs): ...\n def ex_edit_node(self, **kwargs): ...\n def ex_edit_image(self, **kwargs): ...\n def ex_list_ips(self, **kwargs): ...\n\n connectionCls = GoGridConnection\n type = Provider.GOGRID\n api_name = 'gogrid'\n name = 'GoGrid'\n website = 'http://www.gogrid.com/'\n features = {'create_node': ['generates_password']}\n _instance_types = GOGRID_INSTANCE_TYPES\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_save_image", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 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": "libcloud/compute/drivers/gogrid.py", "focal_class": null, "focal_method": "ex_edit_image", "tests": "import unittest\n\nclass Test_ex_edit_image(unittest.TestCase):\n def test_ex_edit_image(self):\n image = self.driver.list_images()[0]\n ret = self.driver.ex_edit_image(image=image, public=False, ex_description='test', name='testname')\n self.assertTrue(isinstance(ret, NodeImage))\n", "method_code": " def ex_edit_image(self, **kwargs):\n \"\"\"Edit metadata of a server image.\n \n @keyword image: image to be edited (required)\n @type image: L{NodeImage}\n \n @keyword public: should be the image public (required)\n @type public: C{bool}\n \n @keyword ex_description: description of the image (optional)\n @type ex_description: C{str}\n \n @keyword name: name of the image\n @type name C{str}\n \n @rtype: L{NodeImage}\n \"\"\"\n image = kwargs['image']\n public = kwargs['public']\n params = {'id': image.id, 'isPublic': str(public).lower()}\n if 'ex_description' in kwargs:\n params['description'] = kwargs['ex_description']\n if 'name' in kwargs:\n params['friendlyName'] = kwargs['name']\n object = self.connection.request('/api/grid/image/edit', params=params).object\n return self._to_image(object['list'][0])\n ", "context": "class GoGridNodeDriver(BaseGoGridDriverNodeDriver):\n def ex_edit_image(self, **kwargs): ...\n def __init__(self, *args, **kwargs): ...\n def _get_state(self, element): ...\n def _get_ip(self, element): ...\n def _get_id(self, element): ...\n def _to_node(self, element, password=None): ...\n def _to_image(self, element): ...\n def _to_images(self, object): ...\n def _to_location(self, element): ...\n def _to_locations(self, object): ...\n def list_images(self, location=None): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def _server_list(self): ...\n def _password_list(self): ...\n def _server_power(self, id, power): ...\n def _server_delete(self, id): ...\n def _get_first_ip(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def ex_create_node_nowait(self, **kwargs): ...\n def create_node(self, **kwargs): ...\n def ex_save_image(self, node, name): ...\n def ex_edit_node(self, **kwargs): ...\n def ex_list_ips(self, **kwargs): ...\n\n connectionCls = GoGridConnection\n type = Provider.GOGRID\n api_name = 'gogrid'\n name = 'GoGrid'\n website = 'http://www.gogrid.com/'\n features = {'create_node': ['generates_password']}\n _instance_types = GOGRID_INSTANCE_TYPES\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_edit_image", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 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": "libcloud/compute/drivers/gogrid.py", "focal_class": null, "focal_method": "ex_edit_node", "tests": "import unittest\n\nclass Test_ex_edit_node(unittest.TestCase):\n def test_ex_edit_node(self):\n node = Node(id=90967, name=None, state=None, public_ips=None, private_ips=None, driver=self.driver)\n ret = self.driver.ex_edit_node(node=node, size=self._get_test_512Mb_node_size())\n self.assertTrue(isinstance(ret, Node))\n", "method_code": " def ex_edit_node(self, **kwargs):\n \"\"\"Change attributes of a node.\n \n @keyword node: node to be edited (required)\n @type node: L{GoGridNode}\n \n @keyword size: new size of a node (required)\n @type size: L{NodeSize}\n \n @keyword ex_description: new description of a node\n @type ex_description: C{str}\n \n @rtype: L{Node}\n \"\"\"\n node = kwargs['node']\n size = kwargs['size']\n params = {'id': node.id, 'server.ram': size.id}\n if 'ex_description' in kwargs:\n params['description'] = kwargs['ex_description']\n object = self.connection.request('/api/grid/server/edit', params=params).object\n return self._to_node(object['list'][0])\n ", "context": "class GoGridNodeDriver(BaseGoGridDriverNodeDriver):\n def ex_edit_node(self, **kwargs): ...\n def __init__(self, *args, **kwargs): ...\n def _get_state(self, element): ...\n def _get_ip(self, element): ...\n def _get_id(self, element): ...\n def _to_node(self, element, password=None): ...\n def _to_image(self, element): ...\n def _to_images(self, object): ...\n def _to_location(self, element): ...\n def _to_locations(self, object): ...\n def list_images(self, location=None): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def _server_list(self): ...\n def _password_list(self): ...\n def _server_power(self, id, power): ...\n def _server_delete(self, id): ...\n def _get_first_ip(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def ex_create_node_nowait(self, **kwargs): ...\n def create_node(self, **kwargs): ...\n def ex_save_image(self, node, name): ...\n def ex_edit_image(self, **kwargs): ...\n def ex_list_ips(self, **kwargs): ...\n\n connectionCls = GoGridConnection\n type = Provider.GOGRID\n api_name = 'gogrid'\n name = 'GoGrid'\n website = 'http://www.gogrid.com/'\n features = {'create_node': ['generates_password']}\n _instance_types = GOGRID_INSTANCE_TYPES\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_edit_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/compute/drivers/gogrid.py", "focal_class": null, "focal_method": "ex_list_ips", "tests": "import unittest\n\nclass Test_ex_list_ips(unittest.TestCase):\n def test_ex_list_ips(self):\n ips = self.driver.ex_list_ips()\n expected_ips = {'192.168.75.66': GoGridIpAddress(id='5348099', ip='192.168.75.66', public=True, state='Unassigned', subnet='192.168.75.64/255.255.255.240'), '192.168.75.67': GoGridIpAddress(id='5348100', ip='192.168.75.67', public=True, state='Assigned', subnet='192.168.75.64/255.255.255.240'), '192.168.75.68': GoGridIpAddress(id='5348101', ip='192.168.75.68', public=False, state='Unassigned', subnet='192.168.75.64/255.255.255.240')}\n self.assertEqual(len(expected_ips), 3)\n for ip in ips:\n self.assertTrue(ip.ip in expected_ips)\n self.assertEqual(ip.public, expected_ips[ip.ip].public)\n self.assertEqual(ip.state, expected_ips[ip.ip].state)\n self.assertEqual(ip.subnet, expected_ips[ip.ip].subnet)\n del expected_ips[ip.ip]\n self.assertEqual(len(expected_ips), 0)\n", "method_code": " def ex_list_ips(self, **kwargs):\n \"\"\"Return list of IP addresses assigned to\n the account.\n \n @keyword public: set to True to list only\n public IPs or False to list only\n private IPs. Set to None or not specify\n at all not to filter by type\n @type public: C{bool}\n \n @keyword assigned: set to True to list only addresses\n assigned to servers, False to list unassigned\n addresses and set to None or don't set at all\n not no filter by state\n @type assigned: C{bool}\n \n @keyword location: filter IP addresses by location\n @type location: L{NodeLocation}\n \n @rtype: C{list} of L{GoGridIpAddress}\n \"\"\"\n params = {}\n if 'public' in kwargs and kwargs['public'] is not None:\n params['ip.type'] = {True: 'Public', False: 'Private'}[kwargs['public']]\n if 'assigned' in kwargs and kwargs['assigned'] is not None:\n params['ip.state'] = {True: 'Assigned', False: 'Unassigned'}[kwargs['assigned']]\n if 'location' in kwargs and kwargs['location'] is not None:\n params['datacenter'] = kwargs['location'].id\n ips = self._to_ips(self.connection.request('/api/grid/ip/list', params=params).object)\n return ips\n ", "context": "class GoGridNodeDriver(BaseGoGridDriverNodeDriver):\n def ex_list_ips(self, **kwargs): ...\n def __init__(self, *args, **kwargs): ...\n def _get_state(self, element): ...\n def _get_ip(self, element): ...\n def _get_id(self, element): ...\n def _to_node(self, element, password=None): ...\n def _to_image(self, element): ...\n def _to_images(self, object): ...\n def _to_location(self, element): ...\n def _to_locations(self, object): ...\n def list_images(self, location=None): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def _server_list(self): ...\n def _password_list(self): ...\n def _server_power(self, id, power): ...\n def _server_delete(self, id): ...\n def _get_first_ip(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def ex_create_node_nowait(self, **kwargs): ...\n def create_node(self, **kwargs): ...\n def ex_save_image(self, node, name): ...\n def ex_edit_node(self, **kwargs): ...\n def ex_edit_image(self, **kwargs): ...\n\n connectionCls = GoGridConnection\n type = Provider.GOGRID\n api_name = 'gogrid'\n name = 'GoGrid'\n website = 'http://www.gogrid.com/'\n features = {'create_node': ['generates_password']}\n _instance_types = GOGRID_INSTANCE_TYPES\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_list_ips", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000648.py"} {"focal_file": "libcloud/compute/drivers/gridspot.py", "focal_class": null, "focal_method": "list_nodes", "tests": "import unittest\n\nclass Test_list_nodes(unittest.TestCase):\n def test_list_nodes(self):\n nodes = self.driver.list_nodes()\n self.assertEqual(len(nodes), 2)\n running_node = nodes[0]\n starting_node = nodes[1]\n self.assertEqual(running_node.id, 'inst_CP2WrQi2WIS4iheyAVkQYw')\n self.assertEqual(running_node.state, NodeState.RUNNING)\n self.assertTrue('69.4.239.74' in running_node.public_ips)\n self.assertEqual(running_node.extra['port'], 62394)\n self.assertEqual(running_node.extra['vm_ram'], 1429436743)\n self.assertEqual(running_node.extra['start_state_time'], 1342108905)\n self.assertEqual(running_node.extra['vm_num_logical_cores'], 8)\n self.assertEqual(running_node.extra['vm_num_physical_cores'], 4)\n self.assertEqual(running_node.extra['winning_bid_id'], 'bid_X5xhotGYiGUk7_RmIqVafA')\n self.assertFalse('ended_state_time' in running_node.extra)\n self.assertEqual(running_node.extra['running_state_time'], 1342108989)\n self.assertEqual(starting_node.id, 'inst_CP2WrQi2WIS4iheyAVkQYw2')\n self.assertEqual(starting_node.state, NodeState.PENDING)\n self.assertTrue('69.4.239.74' in starting_node.public_ips)\n self.assertEqual(starting_node.extra['port'], 62395)\n self.assertEqual(starting_node.extra['vm_ram'], 1429436744)\n self.assertEqual(starting_node.extra['start_state_time'], 1342108906)\n self.assertEqual(starting_node.extra['vm_num_logical_cores'], 7)\n self.assertEqual(starting_node.extra['vm_num_physical_cores'], 5)\n self.assertEqual(starting_node.extra['winning_bid_id'], 'bid_X5xhotGYiGUk7_RmIqVafA1')\n self.assertFalse('ended_state_time' in starting_node.extra)\n self.assertEqual(starting_node.extra['running_state_time'], 1342108990)\n", "method_code": " def list_nodes(self):\n data = self.connection.request('/compute_api/v1/list_instances').object\n return [self._to_node(n) for n in data['instances']]\n ", "context": "class GridspotNodeDriver(NodeDriver):\n def list_nodes(self): ...\n def destroy_node(self, node): ...\n def _get_node_state(self, state): ...\n def _add_int_param(self, params, data, field): ...\n def _to_node(self, data): ...\n\n type = Provider.GRIDSPOT\n name = 'Gridspot'\n website = 'http://www.gridspot.com/'\n connectionCls = GridspotConnection\n NODE_STATE_MAP = {'Running': NodeState.RUNNING, 'Starting': NodeState.PENDING}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_nodes", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000649.py"} {"focal_file": "libcloud/compute/drivers/gridspot.py", "focal_class": null, "focal_method": "destroy_node", "tests": "import unittest\n\nclass Test_destroy_node(unittest.TestCase):\n def test_destroy_node(self):\n \"\"\"\n Test destroy_node for Gridspot driver\n \"\"\"\n node = self.driver.list_nodes()[0]\n self.assertTrue(self.driver.destroy_node(node))\n", "method_code": " def destroy_node(self, node):\n data = {'instance_id': node.id}\n self.connection.request('/compute_api/v1/stop_instance', data).object\n return True\n ", "context": "class GridspotNodeDriver(NodeDriver):\n def destroy_node(self, node): ...\n def list_nodes(self): ...\n def _get_node_state(self, state): ...\n def _add_int_param(self, params, data, field): ...\n def _to_node(self, data): ...\n\n type = Provider.GRIDSPOT\n name = 'Gridspot'\n website = 'http://www.gridspot.com/'\n connectionCls = GridspotConnection\n NODE_STATE_MAP = {'Running': NodeState.RUNNING, 'Starting': NodeState.PENDING}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_destroy_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/compute/drivers/hostvirtual.py", "focal_class": null, "focal_method": "list_nodes", "tests": "import unittest\n\nclass Test_list_nodes(unittest.TestCase):\n def test_list_nodes(self):\n nodes = self.driver.list_nodes()\n self.assertEqual(len(nodes), 4)\n self.assertEqual(len(nodes[0].public_ips), 1)\n self.assertEqual(len(nodes[1].public_ips), 1)\n self.assertEqual(len(nodes[0].private_ips), 0)\n self.assertEqual(len(nodes[1].private_ips), 0)\n self.assertTrue('208.111.39.118' in nodes[1].public_ips)\n self.assertTrue('208.111.45.250' in nodes[0].public_ips)\n self.assertEqual(nodes[3].state, NodeState.RUNNING)\n self.assertEqual(nodes[1].state, NodeState.TERMINATED)\n", "method_code": " def list_nodes(self):\n result = self.connection.request(API_ROOT + '/cloud/servers/').object\n nodes = []\n for value in result:\n node = self._to_node(value)\n nodes.append(node)\n return nodes\n ", "context": "class HostVirtualNodeDriver(NodeDriver):\n def list_nodes(self): ...\n def __init__(self, key): ...\n def _to_node(self, data): ...\n def list_locations(self): ...\n def list_sizes(self, location=None): ...\n def list_images(self): ...\n def _wait_for_node(self, node_id, timeout=30, interval=5.0): ...\n def create_node(self, **kwargs): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def ex_get_node(self, node_id): ...\n def ex_stop_node(self, node): ...\n def ex_start_node(self, node): ...\n def ex_provision_node(self, **kwargs): ...\n def ex_delete_node(self, node): ...\n\n self.location = None\n\n type = Provider.HOSTVIRTUAL\n name = 'HostVirtual'\n website = 'http://www.vr.org'\n connectionCls = HostVirtualComputeConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_nodes", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000651.py"} {"focal_file": "libcloud/compute/drivers/hostvirtual.py", "focal_class": null, "focal_method": "list_sizes", "tests": "import unittest\n\nclass Test_list_sizes(unittest.TestCase):\n def test_list_sizes(self):\n sizes = self.driver.list_sizes()\n self.assertEqual(len(sizes), 14)\n self.assertEqual(sizes[0].id, '31')\n self.assertEqual(sizes[4].id, '71')\n self.assertEqual(sizes[2].ram, '512MB')\n self.assertEqual(sizes[2].disk, '20GB')\n self.assertEqual(sizes[3].bandwidth, '600GB')\n self.assertEqual(sizes[1].price, '15.00')\n", "method_code": " def list_sizes(self, location=None):\n params = {}\n if location:\n params = {'location': location.id}\n result = self.connection.request(API_ROOT + '/cloud/sizes/', data=json.dumps(params)).object\n sizes = []\n for size in result:\n n = NodeSize(id=size['plan_id'], name=size['plan'], ram=size['ram'], disk=size['disk'], bandwidth=size['transfer'], price=size['price'], driver=self.connection.driver)\n sizes.append(n)\n return sizes\n ", "context": "class HostVirtualNodeDriver(NodeDriver):\n def list_sizes(self, location=None): ...\n def __init__(self, key): ...\n def _to_node(self, data): ...\n def list_locations(self): ...\n def list_images(self): ...\n def list_nodes(self): ...\n def _wait_for_node(self, node_id, timeout=30, interval=5.0): ...\n def create_node(self, **kwargs): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def ex_get_node(self, node_id): ...\n def ex_stop_node(self, node): ...\n def ex_start_node(self, node): ...\n def ex_provision_node(self, **kwargs): ...\n def ex_delete_node(self, node): ...\n\n self.location = None\n\n type = Provider.HOSTVIRTUAL\n name = 'HostVirtual'\n website = 'http://www.vr.org'\n connectionCls = HostVirtualComputeConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_sizes", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000652.py"} {"focal_file": "libcloud/compute/drivers/hostvirtual.py", "focal_class": null, "focal_method": "list_images", "tests": "import unittest\n\nclass Test_list_images(unittest.TestCase):\n def test_list_images(self):\n images = self.driver.list_images()\n self.assertEqual(len(images), 8)\n self.assertEqual(images[0].id, '1739')\n self.assertEqual(images[0].name, 'Gentoo 2012 (0619) i386')\n", "method_code": " def list_images(self):\n result = self.connection.request(API_ROOT + '/cloud/images/').object\n images = []\n for image in result:\n i = NodeImage(id=image['id'], name=image['os'], driver=self.connection.driver, extra=image)\n del i.extra['id']\n del i.extra['os']\n images.append(i)\n return images\n ", "context": "class HostVirtualNodeDriver(NodeDriver):\n def list_images(self): ...\n def __init__(self, key): ...\n def _to_node(self, data): ...\n def list_locations(self): ...\n def list_sizes(self, location=None): ...\n def list_nodes(self): ...\n def _wait_for_node(self, node_id, timeout=30, interval=5.0): ...\n def create_node(self, **kwargs): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def ex_get_node(self, node_id): ...\n def ex_stop_node(self, node): ...\n def ex_start_node(self, node): ...\n def ex_provision_node(self, **kwargs): ...\n def ex_delete_node(self, node): ...\n\n self.location = None\n\n type = Provider.HOSTVIRTUAL\n name = 'HostVirtual'\n website = 'http://www.vr.org'\n connectionCls = HostVirtualComputeConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_images", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000653.py"} {"focal_file": "libcloud/compute/drivers/hostvirtual.py", "focal_class": null, "focal_method": "list_locations", "tests": "import unittest\n\nclass Test_list_locations(unittest.TestCase):\n def test_list_locations(self):\n locations = self.driver.list_locations()\n self.assertEqual(locations[0].id, '3')\n self.assertEqual(locations[0].name, 'SJC - San Jose, CA')\n self.assertEqual(locations[1].id, '13')\n self.assertEqual(locations[1].name, 'IAD2- Reston, VA')\n\n def test_create_node_in_location(self):\n auth = NodeAuthPassword('vr!@#hosted#@!')\n size = self.driver.list_sizes()[0]\n image = self.driver.list_images()[0]\n location = self.driver.list_locations()[1]\n node = self.driver.create_node(name='test.com', image=image, size=size, auth=auth, location=location)\n self.assertEqual('62291', node.id)\n self.assertEqual('server1.vr-cluster.org', node.name)\n", "method_code": " def list_locations(self):\n result = self.connection.request(API_ROOT + '/cloud/locations/').object\n locations = []\n for dc in result:\n locations.append(NodeLocation(dc['id'], dc['name'], dc['name'].split(',')[1].replace(' ', ''), self))\n return locations\n ", "context": "class HostVirtualNodeDriver(NodeDriver):\n def list_locations(self): ...\n def __init__(self, key): ...\n def _to_node(self, data): ...\n def list_sizes(self, location=None): ...\n def list_images(self): ...\n def list_nodes(self): ...\n def _wait_for_node(self, node_id, timeout=30, interval=5.0): ...\n def create_node(self, **kwargs): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def ex_get_node(self, node_id): ...\n def ex_stop_node(self, node): ...\n def ex_start_node(self, node): ...\n def ex_provision_node(self, **kwargs): ...\n def ex_delete_node(self, node): ...\n\n self.location = None\n\n type = Provider.HOSTVIRTUAL\n name = 'HostVirtual'\n website = 'http://www.vr.org'\n connectionCls = HostVirtualComputeConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_locations", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000654.py"} {"focal_file": "libcloud/compute/drivers/hostvirtual.py", "focal_class": null, "focal_method": "reboot_node", "tests": "import unittest\n\nclass Test_reboot_node(unittest.TestCase):\n def test_reboot_node(self):\n node = self.driver.list_nodes()[0]\n self.assertTrue(self.driver.reboot_node(node))\n", "method_code": " def reboot_node(self, node):\n params = {'force': 0, 'mbpkgid': node.id}\n result = self.connection.request(API_ROOT + '/cloud/server/reboot', data=json.dumps(params), method='POST').object\n return bool(result)\n ", "context": "class HostVirtualNodeDriver(NodeDriver):\n def reboot_node(self, node): ...\n def __init__(self, key): ...\n def _to_node(self, data): ...\n def list_locations(self): ...\n def list_sizes(self, location=None): ...\n def list_images(self): ...\n def list_nodes(self): ...\n def _wait_for_node(self, node_id, timeout=30, interval=5.0): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def ex_get_node(self, node_id): ...\n def ex_stop_node(self, node): ...\n def ex_start_node(self, node): ...\n def ex_provision_node(self, **kwargs): ...\n def ex_delete_node(self, node): ...\n\n self.location = None\n\n type = Provider.HOSTVIRTUAL\n name = 'HostVirtual'\n website = 'http://www.vr.org'\n connectionCls = HostVirtualComputeConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_reboot_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000655.py"} {"focal_file": "libcloud/compute/drivers/hostvirtual.py", "focal_class": null, "focal_method": "ex_get_node", "tests": "import unittest\n\nclass Test_ex_get_node(unittest.TestCase):\n def test_ex_get_node(self):\n node = self.driver.ex_get_node(node_id='62291')\n self.assertEqual(node.id, '62291')\n self.assertEqual(node.name, 'server1.vr-cluster.org')\n self.assertEqual(node.state, NodeState.TERMINATED)\n self.assertTrue('208.111.45.250' in node.public_ips)\n", "method_code": " def ex_get_node(self, node_id):\n \"\"\"\n Get a single node.\n \n @param node_id: id of the node that we need the node object for\n @type node_id: C{str}\n \n @rtype: L{Node}\n \"\"\"\n params = {'mbpkgid': node_id}\n result = self.connection.request(API_ROOT + '/cloud/server', params=params).object\n node = self._to_node(result)\n return node\n ", "context": "class HostVirtualNodeDriver(NodeDriver):\n def ex_get_node(self, node_id): ...\n def __init__(self, key): ...\n def _to_node(self, data): ...\n def list_locations(self): ...\n def list_sizes(self, location=None): ...\n def list_images(self): ...\n def list_nodes(self): ...\n def _wait_for_node(self, node_id, timeout=30, interval=5.0): ...\n def create_node(self, **kwargs): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def ex_stop_node(self, node): ...\n def ex_start_node(self, node): ...\n def ex_provision_node(self, **kwargs): ...\n def ex_delete_node(self, node): ...\n\n self.location = None\n\n type = Provider.HOSTVIRTUAL\n name = 'HostVirtual'\n website = 'http://www.vr.org'\n connectionCls = HostVirtualComputeConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_get_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000656.py"} {"focal_file": "libcloud/compute/drivers/hostvirtual.py", "focal_class": null, "focal_method": "ex_stop_node", "tests": "import unittest\n\nclass Test_ex_stop_node(unittest.TestCase):\n def test_ex_stop_node(self):\n node = self.driver.list_nodes()[0]\n self.assertTrue(self.driver.ex_stop_node(node))\n", "method_code": " def ex_stop_node(self, node):\n \"\"\"\n Stop a node.\n \n @param node: Node which should be used\n @type node: L{Node}\n \n @rtype: C{bool}\n \"\"\"\n params = {'force': 0, 'mbpkgid': node.id}\n result = self.connection.request(API_ROOT + '/cloud/server/shutdown', data=json.dumps(params), method='POST').object\n return bool(result)\n ", "context": "class HostVirtualNodeDriver(NodeDriver):\n def ex_stop_node(self, node): ...\n def __init__(self, key): ...\n def _to_node(self, data): ...\n def list_locations(self): ...\n def list_sizes(self, location=None): ...\n def list_images(self): ...\n def list_nodes(self): ...\n def _wait_for_node(self, node_id, timeout=30, interval=5.0): ...\n def create_node(self, **kwargs): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def ex_get_node(self, node_id): ...\n def ex_start_node(self, node): ...\n def ex_provision_node(self, **kwargs): ...\n def ex_delete_node(self, node): ...\n\n self.location = None\n\n type = Provider.HOSTVIRTUAL\n name = 'HostVirtual'\n website = 'http://www.vr.org'\n connectionCls = HostVirtualComputeConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_stop_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 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": "libcloud/compute/drivers/hostvirtual.py", "focal_class": null, "focal_method": "ex_start_node", "tests": "import unittest\n\nclass Test_ex_start_node(unittest.TestCase):\n def test_ex_start_node(self):\n node = self.driver.list_nodes()[0]\n self.assertTrue(self.driver.ex_start_node(node))\n", "method_code": " def ex_start_node(self, node):\n \"\"\"\n Start a node.\n \n @param node: Node which should be used\n @type node: L{Node}\n \n @rtype: C{bool}\n \"\"\"\n params = {'mbpkgid': node.id}\n result = self.connection.request(API_ROOT + '/cloud/server/start', data=json.dumps(params), method='POST').object\n return bool(result)\n ", "context": "class HostVirtualNodeDriver(NodeDriver):\n def ex_start_node(self, node): ...\n def __init__(self, key): ...\n def _to_node(self, data): ...\n def list_locations(self): ...\n def list_sizes(self, location=None): ...\n def list_images(self): ...\n def list_nodes(self): ...\n def _wait_for_node(self, node_id, timeout=30, interval=5.0): ...\n def create_node(self, **kwargs): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def ex_get_node(self, node_id): ...\n def ex_stop_node(self, node): ...\n def ex_provision_node(self, **kwargs): ...\n def ex_delete_node(self, node): ...\n\n self.location = None\n\n type = Provider.HOSTVIRTUAL\n name = 'HostVirtual'\n website = 'http://www.vr.org'\n connectionCls = HostVirtualComputeConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_start_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000658.py"} {"focal_file": "libcloud/compute/drivers/hostvirtual.py", "focal_class": null, "focal_method": "destroy_node", "tests": "import unittest\n\nclass Test_destroy_node(unittest.TestCase):\n def test_destroy_node(self):\n node = self.driver.list_nodes()[0]\n self.assertTrue(self.driver.destroy_node(node))\n", "method_code": " def destroy_node(self, node):\n params = {'mbpkgid': node.id}\n result = self.connection.request(API_ROOT + '/cloud/cancel', data=json.dumps(params), method='POST').object\n return bool(result)\n ", "context": "class HostVirtualNodeDriver(NodeDriver):\n def destroy_node(self, node): ...\n def __init__(self, key): ...\n def _to_node(self, data): ...\n def list_locations(self): ...\n def list_sizes(self, location=None): ...\n def list_images(self): ...\n def list_nodes(self): ...\n def _wait_for_node(self, node_id, timeout=30, interval=5.0): ...\n def create_node(self, **kwargs): ...\n def reboot_node(self, node): ...\n def ex_get_node(self, node_id): ...\n def ex_stop_node(self, node): ...\n def ex_start_node(self, node): ...\n def ex_provision_node(self, **kwargs): ...\n def ex_delete_node(self, node): ...\n\n self.location = None\n\n type = Provider.HOSTVIRTUAL\n name = 'HostVirtual'\n website = 'http://www.vr.org'\n connectionCls = HostVirtualComputeConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_destroy_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000659.py"} {"focal_file": "libcloud/compute/drivers/hostvirtual.py", "focal_class": null, "focal_method": "ex_delete_node", "tests": "import unittest\n\nclass Test_ex_delete_node(unittest.TestCase):\n def test_ex_delete_node(self):\n node = self.driver.list_nodes()[0]\n self.assertTrue(self.driver.ex_delete_node(node))\n", "method_code": " def ex_delete_node(self, node):\n \"\"\"\n Delete a node.\n \n @param node: Node which should be used\n @type node: L{Node}\n \n @rtype: C{bool}\n \"\"\"\n params = {'mbpkgid': node.id}\n result = self.connection.request(API_ROOT + '/cloud/server/delete', data=json.dumps(params), method='POST').object\n return bool(result)\n ", "context": "class HostVirtualNodeDriver(NodeDriver):\n def ex_delete_node(self, node): ...\n def __init__(self, key): ...\n def _to_node(self, data): ...\n def list_locations(self): ...\n def list_sizes(self, location=None): ...\n def list_images(self): ...\n def list_nodes(self): ...\n def _wait_for_node(self, node_id, timeout=30, interval=5.0): ...\n def create_node(self, **kwargs): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def ex_get_node(self, node_id): ...\n def ex_stop_node(self, node): ...\n def ex_start_node(self, node): ...\n def ex_provision_node(self, **kwargs): ...\n\n self.location = None\n\n type = Provider.HOSTVIRTUAL\n name = 'HostVirtual'\n website = 'http://www.vr.org'\n connectionCls = HostVirtualComputeConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_delete_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000660.py"} {"focal_file": "libcloud/compute/drivers/hostvirtual.py", "focal_class": null, "focal_method": "create_node", "tests": "import unittest\n\nclass Test_create_node(unittest.TestCase):\n def test_create_node(self):\n auth = NodeAuthPassword('vr!@#hosted#@!')\n size = self.driver.list_sizes()[0]\n image = self.driver.list_images()[0]\n node = self.driver.create_node(name='test.com', image=image, size=size, auth=auth)\n self.assertEqual('62291', node.id)\n self.assertEqual('server1.vr-cluster.org', node.name)\n", "method_code": " def create_node(self, **kwargs):\n dc = None\n size = kwargs['size']\n image = kwargs['image']\n params = {'plan': size.name}\n dc = DEFAULT_NODE_LOCATION_ID\n if 'location' in kwargs:\n dc = kwargs['location'].id\n result = self.connection.request(API_ROOT + '/cloud/buy/', data=json.dumps(params), method='POST').object\n stub_node = self._to_node({'mbpkgid': result['id'], 'status': 'PENDING', 'fqdn': kwargs['name'], 'plan_id': size.id, 'os_id': image.id, 'location_id': dc})\n self.ex_provision_node(node=stub_node, auth=kwargs['auth'])\n node = self._wait_for_node(stub_node.id)\n return node\n ", "context": "class HostVirtualNodeDriver(NodeDriver):\n def create_node(self, **kwargs): ...\n def __init__(self, key): ...\n def _to_node(self, data): ...\n def list_locations(self): ...\n def list_sizes(self, location=None): ...\n def list_images(self): ...\n def list_nodes(self): ...\n def _wait_for_node(self, node_id, timeout=30, interval=5.0): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def ex_get_node(self, node_id): ...\n def ex_stop_node(self, node): ...\n def ex_start_node(self, node): ...\n def ex_provision_node(self, **kwargs): ...\n def ex_delete_node(self, node): ...\n\n self.location = None\n\n type = Provider.HOSTVIRTUAL\n name = 'HostVirtual'\n website = 'http://www.vr.org'\n connectionCls = HostVirtualComputeConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000661.py"} {"focal_file": "libcloud/compute/drivers/hostvirtual.py", "focal_class": null, "focal_method": "ex_provision_node", "tests": "import unittest\n\nclass Test_ex_provision_node(unittest.TestCase):\n def test_ex_provision_node(self):\n node = self.driver.list_nodes()[0]\n auth = NodeAuthPassword('vr!@#hosted#@!')\n self.assertTrue(self.driver.ex_provision_node(node=node, auth=auth))\n", "method_code": " def ex_provision_node(self, **kwargs):\n \"\"\"\n Provision a server on a VR package and get it booted\n \n @keyword node: node which should be used\n @type node: L{Node}\n \n @keyword image: The distribution to deploy on your server (mandatory)\n @type image: L{NodeImage}\n \n @keyword auth: an SSH key or root password (mandatory)\n @type auth: L{NodeAuthSSHKey} or L{NodeAuthPassword}\n \n @keyword location: which datacenter to create the server in\n @type location: L{NodeLocation}\n \n @return: Node representing the newly built server\n @rtype: L{Node}\n \"\"\"\n node = kwargs['node']\n if 'image' in kwargs:\n image = kwargs['image']\n else:\n image = node.extra['image']\n params = {'mbpkgid': node.id, 'image': image, 'fqdn': node.name, 'location': node.extra['location']}\n auth = kwargs['auth']\n ssh_key = None\n password = None\n if isinstance(auth, NodeAuthSSHKey):\n ssh_key = auth.pubkey\n params['ssh_key'] = ssh_key\n elif isinstance(auth, NodeAuthPassword):\n password = auth.password\n params['password'] = password\n if not ssh_key and (not password):\n raise HostVirtualException(500, 'Need SSH key or Root password')\n result = self.connection.request(API_ROOT + '/cloud/server/build', data=json.dumps(params), method='POST').object\n return bool(result)\n ", "context": "class HostVirtualNodeDriver(NodeDriver):\n def ex_provision_node(self, **kwargs): ...\n def __init__(self, key): ...\n def _to_node(self, data): ...\n def list_locations(self): ...\n def list_sizes(self, location=None): ...\n def list_images(self): ...\n def list_nodes(self): ...\n def _wait_for_node(self, node_id, timeout=30, interval=5.0): ...\n def create_node(self, **kwargs): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def ex_get_node(self, node_id): ...\n def ex_stop_node(self, node): ...\n def ex_start_node(self, node): ...\n def ex_delete_node(self, node): ...\n\n self.location = None\n\n type = Provider.HOSTVIRTUAL\n name = 'HostVirtual'\n website = 'http://www.vr.org'\n connectionCls = HostVirtualComputeConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_provision_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000662.py"} {"focal_file": "libcloud/compute/drivers/ibm_sce.py", "focal_class": null, "focal_method": "list_nodes", "tests": "import unittest\n\nclass Test_list_nodes(unittest.TestCase):\n def test_list_nodes(self):\n ret = self.driver.list_nodes()\n self.assertEquals(len(ret), 3)\n self.assertEquals(ret[0].id, '26557')\n self.assertEquals(ret[0].name, 'Insight Instance')\n self.assertEquals(ret[0].public_ips, ['129.33.196.128'])\n self.assertEquals(ret[0].private_ips, [])\n self.assertEquals(ret[1].public_ips, [])\n self.assertEquals(ret[1].private_ips, [])\n self.assertEquals(ret[1].id, '28193')\n", "method_code": " def list_nodes(self):\n return self._to_nodes(self.connection.request(REST_BASE + '/instances').object)\n ", "context": "class IBMNodeDriver(NodeDriver):\n def list_nodes(self): ...\n def create_node(self, **kwargs): ...\n def create_volume(self, size, name, location, **kwargs): ...\n def create_image(self, name, description=None, **kwargs): ...\n def destroy_node(self, node): ...\n def destroy_volume(self, volume): ...\n def ex_destroy_image(self, image): ...\n def attach_volume(self, node, volume): ...\n def detach_volume(self, node, volume): ...\n def reboot_node(self, node): ...\n def list_images(self, location=None): ...\n def list_volumes(self): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def ex_list_storage_offerings(self): ...\n def ex_allocate_address(self, location_id, offering_id, vlan_id=None): ...\n def ex_list_addresses(self, resource_id=None): ...\n def ex_copy_to(self, image, volume): ...\n def ex_delete_address(self, resource_id): ...\n def ex_wait_storage_state(self, volume, state=VolumeState.DETACHED, wait_period=60, timeout=1200): ...\n def _to_nodes(self, object): ...\n def _to_node(self, instance): ...\n def _to_images(self, object): ...\n def _to_image(self, image): ...\n def _to_locations(self, object): ...\n def _to_location(self, location): ...\n def _to_node_sizes(self, object): ...\n def _to_node_size(self, object): ...\n def _to_volumes(self, object): ...\n def _to_volume(self, object): ...\n def _to_volume_offerings(self, object): ...\n def _to_volume_offering(self, object): ...\n def _to_addresses(self, object): ...\n def _to_address(self, object): ...\n\n connectionCls = IBMConnection\n type = Provider.IBM\n name = 'IBM SmartCloud Enterprise'\n website = 'http://ibm.com/services/us/en/cloud-enterprise/'\n NODE_STATE_MAP = {0: NodeState.PENDING, 1: NodeState.PENDING, 2: NodeState.TERMINATED, 3: NodeState.TERMINATED, 4: NodeState.TERMINATED, 5: NodeState.RUNNING, 6: NodeState.UNKNOWN, 7: NodeState.PENDING, 8: NodeState.REBOOTING, 9: NodeState.PENDING, 10: NodeState.PENDING, 11: NodeState.TERMINATED, 12: NodeState.PENDING, 13: NodeState.PENDING, 14: NodeState.PENDING, 15: NodeState.PENDING}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_nodes", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000663.py"} {"focal_file": "libcloud/compute/drivers/ibm_sce.py", "focal_class": null, "focal_method": "list_sizes", "tests": "import unittest\n\nclass Test_list_sizes(unittest.TestCase):\n def test_list_sizes(self):\n ret = self.driver.list_sizes()\n self.assertEquals(len(ret), 9)\n self.assertEquals(ret[0].id, 'BRZ32.1/2048/60*175')\n self.assertEquals(ret[1].id, 'BRZ64.2/4096/60*500*350')\n self.assertEquals(ret[2].id, 'COP32.1/2048/60')\n self.assertEquals(ret[0].name, 'Bronze 32 bit')\n self.assertEquals(ret[0].disk, None)\n", "method_code": " def list_sizes(self, location=None):\n \"\"\"\n Returns a generic list of sizes. See list_images() for a list of\n supported sizes for specific images. In particular, you need to have\n a size that matches the architecture (32-bit vs 64-bit) of the virtual\n machine image operating system.\n \n @inherits: L{NodeDriver.list_sizes}\n \"\"\"\n return [NodeSize('BRZ32.1/2048/60*175', 'Bronze 32 bit', None, None, None, None, self.connection.driver), NodeSize('BRZ64.2/4096/60*500*350', 'Bronze 64 bit', None, None, None, None, self.connection.driver), NodeSize('COP32.1/2048/60', 'Copper 32 bit', None, None, None, None, self.connection.driver), NodeSize('COP64.2/4096/60', 'Copper 64 bit', None, None, None, None, self.connection.driver), NodeSize('SLV32.2/4096/60*350', 'Silver 32 bit', None, None, None, None, self.connection.driver), NodeSize('SLV64.4/8192/60*500*500', 'Silver 64 bit', None, None, None, None, self.connection.driver), NodeSize('GLD32.4/4096/60*350', 'Gold 32 bit', None, None, None, None, self.connection.driver), NodeSize('GLD64.8/16384/60*500*500', 'Gold 64 bit', None, None, None, None, self.connection.driver), NodeSize('PLT64.16/16384/60*500*500*500*500', 'Platinum 64 bit', None, None, None, None, self.connection.driver)]\n ", "context": "class IBMNodeDriver(NodeDriver):\n def list_sizes(self, location=None): ...\n def create_node(self, **kwargs): ...\n def create_volume(self, size, name, location, **kwargs): ...\n def create_image(self, name, description=None, **kwargs): ...\n def destroy_node(self, node): ...\n def destroy_volume(self, volume): ...\n def ex_destroy_image(self, image): ...\n def attach_volume(self, node, volume): ...\n def detach_volume(self, node, volume): ...\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def list_volumes(self): ...\n def list_locations(self): ...\n def ex_list_storage_offerings(self): ...\n def ex_allocate_address(self, location_id, offering_id, vlan_id=None): ...\n def ex_list_addresses(self, resource_id=None): ...\n def ex_copy_to(self, image, volume): ...\n def ex_delete_address(self, resource_id): ...\n def ex_wait_storage_state(self, volume, state=VolumeState.DETACHED, wait_period=60, timeout=1200): ...\n def _to_nodes(self, object): ...\n def _to_node(self, instance): ...\n def _to_images(self, object): ...\n def _to_image(self, image): ...\n def _to_locations(self, object): ...\n def _to_location(self, location): ...\n def _to_node_sizes(self, object): ...\n def _to_node_size(self, object): ...\n def _to_volumes(self, object): ...\n def _to_volume(self, object): ...\n def _to_volume_offerings(self, object): ...\n def _to_volume_offering(self, object): ...\n def _to_addresses(self, object): ...\n def _to_address(self, object): ...\n\n connectionCls = IBMConnection\n type = Provider.IBM\n name = 'IBM SmartCloud Enterprise'\n website = 'http://ibm.com/services/us/en/cloud-enterprise/'\n NODE_STATE_MAP = {0: NodeState.PENDING, 1: NodeState.PENDING, 2: NodeState.TERMINATED, 3: NodeState.TERMINATED, 4: NodeState.TERMINATED, 5: NodeState.RUNNING, 6: NodeState.UNKNOWN, 7: NodeState.PENDING, 8: NodeState.REBOOTING, 9: NodeState.PENDING, 10: NodeState.PENDING, 11: NodeState.TERMINATED, 12: NodeState.PENDING, 13: NodeState.PENDING, 14: NodeState.PENDING, 15: NodeState.PENDING}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_sizes", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000664.py"} {"focal_file": "libcloud/compute/drivers/ibm_sce.py", "focal_class": null, "focal_method": "list_images", "tests": "import unittest\n\nclass Test_list_images(unittest.TestCase):\n def test_list_images(self):\n ret = self.driver.list_images()\n self.assertEqual(len(ret), 21)\n self.assertEqual(ret[10].name, 'Rational Asset Manager 7.2.0.1')\n self.assertEqual(ret[9].id, '10002573')\n", "method_code": " def list_images(self, location=None):\n return self._to_images(self.connection.request(REST_BASE + '/offerings/image').object)\n ", "context": "class IBMNodeDriver(NodeDriver):\n def list_images(self, location=None): ...\n def create_node(self, **kwargs): ...\n def create_volume(self, size, name, location, **kwargs): ...\n def create_image(self, name, description=None, **kwargs): ...\n def destroy_node(self, node): ...\n def destroy_volume(self, volume): ...\n def ex_destroy_image(self, image): ...\n def attach_volume(self, node, volume): ...\n def detach_volume(self, node, volume): ...\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def list_volumes(self): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def ex_list_storage_offerings(self): ...\n def ex_allocate_address(self, location_id, offering_id, vlan_id=None): ...\n def ex_list_addresses(self, resource_id=None): ...\n def ex_copy_to(self, image, volume): ...\n def ex_delete_address(self, resource_id): ...\n def ex_wait_storage_state(self, volume, state=VolumeState.DETACHED, wait_period=60, timeout=1200): ...\n def _to_nodes(self, object): ...\n def _to_node(self, instance): ...\n def _to_images(self, object): ...\n def _to_image(self, image): ...\n def _to_locations(self, object): ...\n def _to_location(self, location): ...\n def _to_node_sizes(self, object): ...\n def _to_node_size(self, object): ...\n def _to_volumes(self, object): ...\n def _to_volume(self, object): ...\n def _to_volume_offerings(self, object): ...\n def _to_volume_offering(self, object): ...\n def _to_addresses(self, object): ...\n def _to_address(self, object): ...\n\n connectionCls = IBMConnection\n type = Provider.IBM\n name = 'IBM SmartCloud Enterprise'\n website = 'http://ibm.com/services/us/en/cloud-enterprise/'\n NODE_STATE_MAP = {0: NodeState.PENDING, 1: NodeState.PENDING, 2: NodeState.TERMINATED, 3: NodeState.TERMINATED, 4: NodeState.TERMINATED, 5: NodeState.RUNNING, 6: NodeState.UNKNOWN, 7: NodeState.PENDING, 8: NodeState.REBOOTING, 9: NodeState.PENDING, 10: NodeState.PENDING, 11: NodeState.TERMINATED, 12: NodeState.PENDING, 13: NodeState.PENDING, 14: NodeState.PENDING, 15: NodeState.PENDING}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_images", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000665.py"} {"focal_file": "libcloud/compute/drivers/ibm_sce.py", "focal_class": null, "focal_method": "list_locations", "tests": "import unittest\n\nclass Test_list_locations(unittest.TestCase):\n def test_list_locations(self):\n ret = self.driver.list_locations()\n self.assertEquals(len(ret), 6)\n self.assertEquals(ret[0].id, '41')\n self.assertEquals(ret[0].name, 'Raleigh')\n self.assertEquals(ret[0].country, 'U.S.A')\n", "method_code": " def list_locations(self):\n return self._to_locations(self.connection.request(REST_BASE + '/locations').object)\n ", "context": "class IBMNodeDriver(NodeDriver):\n def list_locations(self): ...\n def create_node(self, **kwargs): ...\n def create_volume(self, size, name, location, **kwargs): ...\n def create_image(self, name, description=None, **kwargs): ...\n def destroy_node(self, node): ...\n def destroy_volume(self, volume): ...\n def ex_destroy_image(self, image): ...\n def attach_volume(self, node, volume): ...\n def detach_volume(self, node, volume): ...\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def list_volumes(self): ...\n def list_sizes(self, location=None): ...\n def ex_list_storage_offerings(self): ...\n def ex_allocate_address(self, location_id, offering_id, vlan_id=None): ...\n def ex_list_addresses(self, resource_id=None): ...\n def ex_copy_to(self, image, volume): ...\n def ex_delete_address(self, resource_id): ...\n def ex_wait_storage_state(self, volume, state=VolumeState.DETACHED, wait_period=60, timeout=1200): ...\n def _to_nodes(self, object): ...\n def _to_node(self, instance): ...\n def _to_images(self, object): ...\n def _to_image(self, image): ...\n def _to_locations(self, object): ...\n def _to_location(self, location): ...\n def _to_node_sizes(self, object): ...\n def _to_node_size(self, object): ...\n def _to_volumes(self, object): ...\n def _to_volume(self, object): ...\n def _to_volume_offerings(self, object): ...\n def _to_volume_offering(self, object): ...\n def _to_addresses(self, object): ...\n def _to_address(self, object): ...\n\n connectionCls = IBMConnection\n type = Provider.IBM\n name = 'IBM SmartCloud Enterprise'\n website = 'http://ibm.com/services/us/en/cloud-enterprise/'\n NODE_STATE_MAP = {0: NodeState.PENDING, 1: NodeState.PENDING, 2: NodeState.TERMINATED, 3: NodeState.TERMINATED, 4: NodeState.TERMINATED, 5: NodeState.RUNNING, 6: NodeState.UNKNOWN, 7: NodeState.PENDING, 8: NodeState.REBOOTING, 9: NodeState.PENDING, 10: NodeState.PENDING, 11: NodeState.TERMINATED, 12: NodeState.PENDING, 13: NodeState.PENDING, 14: NodeState.PENDING, 15: NodeState.PENDING}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_locations", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000666.py"} {"focal_file": "libcloud/compute/drivers/ibm_sce.py", "focal_class": null, "focal_method": "create_node", "tests": "import unittest\n\nclass Test_create_node(unittest.TestCase):\n def test_create_node(self):\n IBMMockHttp.type = 'CREATE'\n image = NodeImage(id=11, name='Rational Insight', driver=self.driver)\n size = NodeSize('LARGE', 'LARGE', None, None, None, None, self.driver)\n location = NodeLocation('1', 'POK', 'US', driver=self.driver)\n ret = self.driver.create_node(name='RationalInsight4', image=image, size=size, location=location, publicKey='MyPublicKey', configurationData={'insight_admin_password': 'myPassword1', 'db2_admin_password': 'myPassword2', 'report_user_password': 'myPassword3'})\n self.assertTrue(isinstance(ret, Node))\n self.assertEquals(ret.name, 'RationalInsight4')\n IBMMockHttp.type = 'CREATE_INVALID'\n location = NodeLocation('3', 'DOESNOTEXIST', 'US', driver=self.driver)\n try:\n ret = self.driver.create_node(name='RationalInsight5', image=image, size=size, location=location, publicKey='MyPublicKey', configurationData={'insight_admin_password': 'myPassword1', 'db2_admin_password': 'myPassword2', 'report_user_password': 'myPassword3'})\n except Exception:\n e = sys.exc_info()[1]\n self.assertEquals(e.args[0], 'Error 412: No DataCenter with id: 3')\n else:\n self.fail('test should have thrown')\n", "method_code": " def create_node(self, **kwargs):\n \"\"\"\n Creates a node in the IBM SmartCloud Enterprise.\n \n See L{NodeDriver.create_node} for more keyword args.\n \n @inherits: L{NodeDriver.create_node}\n \n @keyword auth: Name of the pubkey to use. When constructing\n C{NodeAuthSSHKey} instance, 'pubkey' argument must be the name of\n the public key to use. You chose this name when creating\n a new public key on the IBM server.\n @type auth: L{NodeAuthSSHKey}\n \n @keyword ex_configurationData: Image-specific configuration\n parameters. Configuration parameters are defined in the parameters\n .xml file. The URL to this file is defined in the NodeImage at\n extra[parametersURL].\n Note: This argument must be specified when launching a Windows\n instance. It must contain 'UserName' and 'Password' keys.\n @type ex_configurationData: C{dict}\n \"\"\"\n data = {}\n data.update({'name': kwargs['name']})\n data.update({'imageID': kwargs['image'].id})\n data.update({'instanceType': kwargs['size'].id})\n if 'location' in kwargs:\n data.update({'location': kwargs['location'].id})\n else:\n data.update({'location': '1'})\n if 'auth' in kwargs and isinstance(kwargs['auth'], NodeAuthSSHKey):\n data.update({'publicKey': kwargs['auth'].pubkey})\n if 'ex_configurationData' in kwargs:\n configurationData = kwargs['ex_configurationData']\n if configurationData:\n for key in configurationData.keys():\n data.update({key: configurationData.get(key)})\n resp = self.connection.request(action=REST_BASE + '/instances', headers={'Content-Type': 'application/x-www-form-urlencoded'}, method='POST', data=data).object\n return self._to_nodes(resp)[0]\n ", "context": "class IBMNodeDriver(NodeDriver):\n def create_node(self, **kwargs): ...\n def create_volume(self, size, name, location, **kwargs): ...\n def create_image(self, name, description=None, **kwargs): ...\n def destroy_node(self, node): ...\n def destroy_volume(self, volume): ...\n def ex_destroy_image(self, image): ...\n def attach_volume(self, node, volume): ...\n def detach_volume(self, node, volume): ...\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def list_volumes(self): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def ex_list_storage_offerings(self): ...\n def ex_allocate_address(self, location_id, offering_id, vlan_id=None): ...\n def ex_list_addresses(self, resource_id=None): ...\n def ex_copy_to(self, image, volume): ...\n def ex_delete_address(self, resource_id): ...\n def ex_wait_storage_state(self, volume, state=VolumeState.DETACHED, wait_period=60, timeout=1200): ...\n def _to_nodes(self, object): ...\n def _to_node(self, instance): ...\n def _to_images(self, object): ...\n def _to_image(self, image): ...\n def _to_locations(self, object): ...\n def _to_location(self, location): ...\n def _to_node_sizes(self, object): ...\n def _to_node_size(self, object): ...\n def _to_volumes(self, object): ...\n def _to_volume(self, object): ...\n def _to_volume_offerings(self, object): ...\n def _to_volume_offering(self, object): ...\n def _to_addresses(self, object): ...\n def _to_address(self, object): ...\n\n connectionCls = IBMConnection\n type = Provider.IBM\n name = 'IBM SmartCloud Enterprise'\n website = 'http://ibm.com/services/us/en/cloud-enterprise/'\n NODE_STATE_MAP = {0: NodeState.PENDING, 1: NodeState.PENDING, 2: NodeState.TERMINATED, 3: NodeState.TERMINATED, 4: NodeState.TERMINATED, 5: NodeState.RUNNING, 6: NodeState.UNKNOWN, 7: NodeState.PENDING, 8: NodeState.REBOOTING, 9: NodeState.PENDING, 10: NodeState.PENDING, 11: NodeState.TERMINATED, 12: NodeState.PENDING, 13: NodeState.PENDING, 14: NodeState.PENDING, 15: NodeState.PENDING}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000667.py"} {"focal_file": "libcloud/compute/drivers/ibm_sce.py", "focal_class": null, "focal_method": "destroy_node", "tests": "import unittest\n\nclass Test_destroy_node(unittest.TestCase):\n def test_destroy_node(self):\n nodes = self.driver.list_nodes()\n self.assertEquals(len(nodes), 3)\n IBMMockHttp.type = 'DELETE'\n toDelete = nodes[1]\n ret = self.driver.destroy_node(toDelete)\n self.assertTrue(ret)\n IBMMockHttp.type = 'DELETED'\n nodes = self.driver.list_nodes()\n self.assertEquals(len(nodes), 2)\n try:\n self.driver.destroy_node(toDelete)\n except Exception:\n e = sys.exc_info()[1]\n self.assertEquals(e.args[0], 'Error 404: Invalid Instance ID 28193')\n else:\n self.fail('test should have thrown')\n", "method_code": " def destroy_node(self, node):\n url = REST_BASE + '/instances/%s' % node.id\n status = int(self.connection.request(action=url, method='DELETE').status)\n return status == httplib.OK\n ", "context": "class IBMNodeDriver(NodeDriver):\n def destroy_node(self, node): ...\n def create_node(self, **kwargs): ...\n def create_volume(self, size, name, location, **kwargs): ...\n def create_image(self, name, description=None, **kwargs): ...\n def destroy_volume(self, volume): ...\n def ex_destroy_image(self, image): ...\n def attach_volume(self, node, volume): ...\n def detach_volume(self, node, volume): ...\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def list_volumes(self): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def ex_list_storage_offerings(self): ...\n def ex_allocate_address(self, location_id, offering_id, vlan_id=None): ...\n def ex_list_addresses(self, resource_id=None): ...\n def ex_copy_to(self, image, volume): ...\n def ex_delete_address(self, resource_id): ...\n def ex_wait_storage_state(self, volume, state=VolumeState.DETACHED, wait_period=60, timeout=1200): ...\n def _to_nodes(self, object): ...\n def _to_node(self, instance): ...\n def _to_images(self, object): ...\n def _to_image(self, image): ...\n def _to_locations(self, object): ...\n def _to_location(self, location): ...\n def _to_node_sizes(self, object): ...\n def _to_node_size(self, object): ...\n def _to_volumes(self, object): ...\n def _to_volume(self, object): ...\n def _to_volume_offerings(self, object): ...\n def _to_volume_offering(self, object): ...\n def _to_addresses(self, object): ...\n def _to_address(self, object): ...\n\n connectionCls = IBMConnection\n type = Provider.IBM\n name = 'IBM SmartCloud Enterprise'\n website = 'http://ibm.com/services/us/en/cloud-enterprise/'\n NODE_STATE_MAP = {0: NodeState.PENDING, 1: NodeState.PENDING, 2: NodeState.TERMINATED, 3: NodeState.TERMINATED, 4: NodeState.TERMINATED, 5: NodeState.RUNNING, 6: NodeState.UNKNOWN, 7: NodeState.PENDING, 8: NodeState.REBOOTING, 9: NodeState.PENDING, 10: NodeState.PENDING, 11: NodeState.TERMINATED, 12: NodeState.PENDING, 13: NodeState.PENDING, 14: NodeState.PENDING, 15: NodeState.PENDING}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_destroy_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000668.py"} {"focal_file": "libcloud/compute/drivers/ibm_sce.py", "focal_class": null, "focal_method": "reboot_node", "tests": "import unittest\n\nclass Test_reboot_node(unittest.TestCase):\n def test_reboot_node(self):\n nodes = self.driver.list_nodes()\n IBMMockHttp.type = 'REBOOT'\n self.assertEquals(len(nodes), 3)\n ret = self.driver.reboot_node(nodes[0])\n self.assertTrue(ret)\n try:\n ret = self.driver.reboot_node(nodes[1])\n except Exception:\n e = sys.exc_info()[1]\n self.assertEquals(e.args[0], 'Error 412: Instance must be in the Active state')\n else:\n self.fail('test should have thrown')\n", "method_code": " def reboot_node(self, node):\n url = REST_BASE + '/instances/%s' % node.id\n headers = {'Content-Type': 'application/x-www-form-urlencoded'}\n data = {'state': 'restart'}\n resp = self.connection.request(action=url, method='PUT', headers=headers, data=data)\n return int(resp.status) == 200\n ", "context": "class IBMNodeDriver(NodeDriver):\n def reboot_node(self, node): ...\n def create_node(self, **kwargs): ...\n def create_volume(self, size, name, location, **kwargs): ...\n def create_image(self, name, description=None, **kwargs): ...\n def destroy_node(self, node): ...\n def destroy_volume(self, volume): ...\n def ex_destroy_image(self, image): ...\n def attach_volume(self, node, volume): ...\n def detach_volume(self, node, volume): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def list_volumes(self): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def ex_list_storage_offerings(self): ...\n def ex_allocate_address(self, location_id, offering_id, vlan_id=None): ...\n def ex_list_addresses(self, resource_id=None): ...\n def ex_copy_to(self, image, volume): ...\n def ex_delete_address(self, resource_id): ...\n def ex_wait_storage_state(self, volume, state=VolumeState.DETACHED, wait_period=60, timeout=1200): ...\n def _to_nodes(self, object): ...\n def _to_node(self, instance): ...\n def _to_images(self, object): ...\n def _to_image(self, image): ...\n def _to_locations(self, object): ...\n def _to_location(self, location): ...\n def _to_node_sizes(self, object): ...\n def _to_node_size(self, object): ...\n def _to_volumes(self, object): ...\n def _to_volume(self, object): ...\n def _to_volume_offerings(self, object): ...\n def _to_volume_offering(self, object): ...\n def _to_addresses(self, object): ...\n def _to_address(self, object): ...\n\n connectionCls = IBMConnection\n type = Provider.IBM\n name = 'IBM SmartCloud Enterprise'\n website = 'http://ibm.com/services/us/en/cloud-enterprise/'\n NODE_STATE_MAP = {0: NodeState.PENDING, 1: NodeState.PENDING, 2: NodeState.TERMINATED, 3: NodeState.TERMINATED, 4: NodeState.TERMINATED, 5: NodeState.RUNNING, 6: NodeState.UNKNOWN, 7: NodeState.PENDING, 8: NodeState.REBOOTING, 9: NodeState.PENDING, 10: NodeState.PENDING, 11: NodeState.TERMINATED, 12: NodeState.PENDING, 13: NodeState.PENDING, 14: NodeState.PENDING, 15: NodeState.PENDING}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_reboot_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000669.py"} {"focal_file": "libcloud/compute/drivers/ibm_sce.py", "focal_class": null, "focal_method": "list_volumes", "tests": "import unittest\n\nclass Test_list_volumes(unittest.TestCase):\n def test_list_volumes(self):\n ret = self.driver.list_volumes()\n self.assertEqual(len(ret), 1)\n self.assertEqual(ret[0].name, 'libcloudvol')\n self.assertEqual(ret[0].extra['location'], '141')\n self.assertEqual(ret[0].size, '2048')\n self.assertEqual(ret[0].id, '39281')\n", "method_code": " def list_volumes(self):\n \"\"\"\n List storage volumes.\n \n @rtype: C{list} of L{StorageVolume}\n \"\"\"\n return self._to_volumes(self.connection.request(REST_BASE + '/storage').object)\n ", "context": "class IBMNodeDriver(NodeDriver):\n def list_volumes(self): ...\n def create_node(self, **kwargs): ...\n def create_volume(self, size, name, location, **kwargs): ...\n def create_image(self, name, description=None, **kwargs): ...\n def destroy_node(self, node): ...\n def destroy_volume(self, volume): ...\n def ex_destroy_image(self, image): ...\n def attach_volume(self, node, volume): ...\n def detach_volume(self, node, volume): ...\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def ex_list_storage_offerings(self): ...\n def ex_allocate_address(self, location_id, offering_id, vlan_id=None): ...\n def ex_list_addresses(self, resource_id=None): ...\n def ex_copy_to(self, image, volume): ...\n def ex_delete_address(self, resource_id): ...\n def ex_wait_storage_state(self, volume, state=VolumeState.DETACHED, wait_period=60, timeout=1200): ...\n def _to_nodes(self, object): ...\n def _to_node(self, instance): ...\n def _to_images(self, object): ...\n def _to_image(self, image): ...\n def _to_locations(self, object): ...\n def _to_location(self, location): ...\n def _to_node_sizes(self, object): ...\n def _to_node_size(self, object): ...\n def _to_volumes(self, object): ...\n def _to_volume(self, object): ...\n def _to_volume_offerings(self, object): ...\n def _to_volume_offering(self, object): ...\n def _to_addresses(self, object): ...\n def _to_address(self, object): ...\n\n connectionCls = IBMConnection\n type = Provider.IBM\n name = 'IBM SmartCloud Enterprise'\n website = 'http://ibm.com/services/us/en/cloud-enterprise/'\n NODE_STATE_MAP = {0: NodeState.PENDING, 1: NodeState.PENDING, 2: NodeState.TERMINATED, 3: NodeState.TERMINATED, 4: NodeState.TERMINATED, 5: NodeState.RUNNING, 6: NodeState.UNKNOWN, 7: NodeState.PENDING, 8: NodeState.REBOOTING, 9: NodeState.PENDING, 10: NodeState.PENDING, 11: NodeState.TERMINATED, 12: NodeState.PENDING, 13: NodeState.PENDING, 14: NodeState.PENDING, 15: NodeState.PENDING}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_volumes", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000670.py"} {"focal_file": "libcloud/compute/drivers/ibm_sce.py", "focal_class": null, "focal_method": "attach_volume", "tests": "import unittest\n\nclass Test_attach_volume(unittest.TestCase):\n def test_attach_volume(self):\n vols = self.driver.list_volumes()\n nodes = self.driver.list_nodes()\n IBMMockHttp.type = 'ATTACH'\n ret = self.driver.attach_volume(nodes[0], vols[0])\n self.assertTrue(ret)\n", "method_code": " def attach_volume(self, node, volume):\n \"\"\"\n Attaches volume to node.\n \n @param node: Node to attach volume to\n @type node: L{Node}\n \n @param volume: Volume to attach\n @type volume: L{StorageVolume}\n \n @rtype: C{bool}\n \"\"\"\n url = REST_BASE + '/instances/%s' % node.id\n headers = {'Content-Type': 'application/x-www-form-urlencoded'}\n data = {'storageID': volume.id, 'type': 'attach'}\n resp = self.connection.request(action=url, method='PUT', headers=headers, data=data)\n return int(resp.status) == 200\n ", "context": "class IBMNodeDriver(NodeDriver):\n def attach_volume(self, node, volume): ...\n def create_node(self, **kwargs): ...\n def create_volume(self, size, name, location, **kwargs): ...\n def create_image(self, name, description=None, **kwargs): ...\n def destroy_node(self, node): ...\n def destroy_volume(self, volume): ...\n def ex_destroy_image(self, image): ...\n def detach_volume(self, node, volume): ...\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def list_volumes(self): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def ex_list_storage_offerings(self): ...\n def ex_allocate_address(self, location_id, offering_id, vlan_id=None): ...\n def ex_list_addresses(self, resource_id=None): ...\n def ex_copy_to(self, image, volume): ...\n def ex_delete_address(self, resource_id): ...\n def ex_wait_storage_state(self, volume, state=VolumeState.DETACHED, wait_period=60, timeout=1200): ...\n def _to_nodes(self, object): ...\n def _to_node(self, instance): ...\n def _to_images(self, object): ...\n def _to_image(self, image): ...\n def _to_locations(self, object): ...\n def _to_location(self, location): ...\n def _to_node_sizes(self, object): ...\n def _to_node_size(self, object): ...\n def _to_volumes(self, object): ...\n def _to_volume(self, object): ...\n def _to_volume_offerings(self, object): ...\n def _to_volume_offering(self, object): ...\n def _to_addresses(self, object): ...\n def _to_address(self, object): ...\n\n connectionCls = IBMConnection\n type = Provider.IBM\n name = 'IBM SmartCloud Enterprise'\n website = 'http://ibm.com/services/us/en/cloud-enterprise/'\n NODE_STATE_MAP = {0: NodeState.PENDING, 1: NodeState.PENDING, 2: NodeState.TERMINATED, 3: NodeState.TERMINATED, 4: NodeState.TERMINATED, 5: NodeState.RUNNING, 6: NodeState.UNKNOWN, 7: NodeState.PENDING, 8: NodeState.REBOOTING, 9: NodeState.PENDING, 10: NodeState.PENDING, 11: NodeState.TERMINATED, 12: NodeState.PENDING, 13: NodeState.PENDING, 14: NodeState.PENDING, 15: NodeState.PENDING}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_attach_volume", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 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": "libcloud/compute/drivers/ibm_sce.py", "focal_class": null, "focal_method": "create_volume", "tests": "import unittest\n\nclass Test_create_volume(unittest.TestCase):\n def test_create_volume(self):\n IBMMockHttp.type = 'CREATE'\n ret = self.driver.create_volume('256', 'test-volume', location='141', format='RAW', offering_id='20001208')\n self.assertEqual(ret.id, '39293')\n self.assertEqual(ret.size, '256')\n self.assertEqual(ret.name, 'test-volume')\n self.assertEqual(ret.extra['location'], '141')\n", "method_code": " def create_volume(self, size, name, location, **kwargs):\n \"\"\"\n Create a new block storage volume (virtual disk)\n \n @param size: Size of volume in gigabytes (required).\n Find out the possible sizes from the\n offerings/storage REST interface\n @type size: C{int}\n \n @keyword name: Name of the volume to be created (required)\n @type name: C{str}\n \n @keyword location: Which data center to create a volume in. If\n empty, it will fail for IBM SmartCloud Enterprise\n (required)\n @type location: L{NodeLocation}\n \n @keyword snapshot: Not supported for IBM SmartCloud Enterprise\n @type snapshot: C{str}\n \n @keyword kwargs.format: Either RAW or EXT3 for IBM SmartCloud\n Enterprise (optional)\n @type kwargs.format: C{str}\n \n @keyword kwargs.offering_id: The storage offering ID for IBM\n SmartCloud Enterprise\n Find this from the REST interface\n storage/offerings. (optional)\n @type kwargs.offering_id: C{str}\n \n @keyword kwargs.source_disk_id: If cloning a volume, the storage\n disk to make a copy from (optional)\n @type kwargs.source_disk_id: C{str}\n \n @keyword kwargs.storage_area_id: The id of the storage availability\n area to create the volume in\n (optional)\n @type kwargs.storage_area_id: C{str}\n \n @keyword kwargs.target_location_id: If cloning a volume, the\n storage disk to make a copy\n from (optional)\n @type kwargs.target_location_id: C{str}\n \n @return: The newly created L{StorageVolume}.\n @rtype: L{StorageVolume}\n \"\"\"\n data = {}\n data.update({'name': name})\n data.update({'size': size})\n data.update({'location': location})\n if 'format' in kwargs and kwargs['format'] is not None:\n data.update({'format': kwargs['format']})\n if 'offering_id' in kwargs and kwargs['offering_id'] is not None:\n data.update({'offeringID': kwargs['offering_id']})\n if 'storage_area_id' in kwargs and kwargs['storage_area_id'] is not None:\n data.update({'storageAreaID': kwargs['storage_area_id']})\n if 'source_disk_id' in kwargs:\n data.update({'sourceDiskID': kwargs['source_disk_id']})\n data.update({'type': 'clone'})\n if 'target_location_id' in kwargs:\n data.update({'targetLocationID': kwargs['target_location_id']})\n resp = self.connection.request(action=REST_BASE + '/storage', headers={'Content-Type': 'application/x-www-form-urlencoded'}, method='POST', data=data).object\n return self._to_volumes(resp)[0]\n ", "context": "class IBMNodeDriver(NodeDriver):\n def create_volume(self, size, name, location, **kwargs): ...\n def create_node(self, **kwargs): ...\n def create_image(self, name, description=None, **kwargs): ...\n def destroy_node(self, node): ...\n def destroy_volume(self, volume): ...\n def ex_destroy_image(self, image): ...\n def attach_volume(self, node, volume): ...\n def detach_volume(self, node, volume): ...\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def list_volumes(self): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def ex_list_storage_offerings(self): ...\n def ex_allocate_address(self, location_id, offering_id, vlan_id=None): ...\n def ex_list_addresses(self, resource_id=None): ...\n def ex_copy_to(self, image, volume): ...\n def ex_delete_address(self, resource_id): ...\n def ex_wait_storage_state(self, volume, state=VolumeState.DETACHED, wait_period=60, timeout=1200): ...\n def _to_nodes(self, object): ...\n def _to_node(self, instance): ...\n def _to_images(self, object): ...\n def _to_image(self, image): ...\n def _to_locations(self, object): ...\n def _to_location(self, location): ...\n def _to_node_sizes(self, object): ...\n def _to_node_size(self, object): ...\n def _to_volumes(self, object): ...\n def _to_volume(self, object): ...\n def _to_volume_offerings(self, object): ...\n def _to_volume_offering(self, object): ...\n def _to_addresses(self, object): ...\n def _to_address(self, object): ...\n\n connectionCls = IBMConnection\n type = Provider.IBM\n name = 'IBM SmartCloud Enterprise'\n website = 'http://ibm.com/services/us/en/cloud-enterprise/'\n NODE_STATE_MAP = {0: NodeState.PENDING, 1: NodeState.PENDING, 2: NodeState.TERMINATED, 3: NodeState.TERMINATED, 4: NodeState.TERMINATED, 5: NodeState.RUNNING, 6: NodeState.UNKNOWN, 7: NodeState.PENDING, 8: NodeState.REBOOTING, 9: NodeState.PENDING, 10: NodeState.PENDING, 11: NodeState.TERMINATED, 12: NodeState.PENDING, 13: NodeState.PENDING, 14: NodeState.PENDING, 15: NodeState.PENDING}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_volume", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000672.py"} {"focal_file": "libcloud/compute/drivers/ibm_sce.py", "focal_class": null, "focal_method": "destroy_volume", "tests": "import unittest\n\nclass Test_destroy_volume(unittest.TestCase):\n def test_destroy_volume(self):\n vols = self.driver.list_volumes()\n IBMMockHttp.type = 'DESTROY'\n ret = self.driver.destroy_volume(vols[0])\n self.assertTrue(ret)\n", "method_code": " def destroy_volume(self, volume):\n \"\"\"\n Destroys a storage volume.\n \n @param volume: Volume to be destroyed\n @type volume: L{StorageVolume}\n \n @rtype: C{bool}\n \"\"\"\n url = REST_BASE + '/storage/%s' % volume.id\n status = int(self.connection.request(action=url, method='DELETE').status)\n return status == httplib.OK\n ", "context": "class IBMNodeDriver(NodeDriver):\n def destroy_volume(self, volume): ...\n def create_node(self, **kwargs): ...\n def create_volume(self, size, name, location, **kwargs): ...\n def create_image(self, name, description=None, **kwargs): ...\n def destroy_node(self, node): ...\n def ex_destroy_image(self, image): ...\n def attach_volume(self, node, volume): ...\n def detach_volume(self, node, volume): ...\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def list_volumes(self): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def ex_list_storage_offerings(self): ...\n def ex_allocate_address(self, location_id, offering_id, vlan_id=None): ...\n def ex_list_addresses(self, resource_id=None): ...\n def ex_copy_to(self, image, volume): ...\n def ex_delete_address(self, resource_id): ...\n def ex_wait_storage_state(self, volume, state=VolumeState.DETACHED, wait_period=60, timeout=1200): ...\n def _to_nodes(self, object): ...\n def _to_node(self, instance): ...\n def _to_images(self, object): ...\n def _to_image(self, image): ...\n def _to_locations(self, object): ...\n def _to_location(self, location): ...\n def _to_node_sizes(self, object): ...\n def _to_node_size(self, object): ...\n def _to_volumes(self, object): ...\n def _to_volume(self, object): ...\n def _to_volume_offerings(self, object): ...\n def _to_volume_offering(self, object): ...\n def _to_addresses(self, object): ...\n def _to_address(self, object): ...\n\n connectionCls = IBMConnection\n type = Provider.IBM\n name = 'IBM SmartCloud Enterprise'\n website = 'http://ibm.com/services/us/en/cloud-enterprise/'\n NODE_STATE_MAP = {0: NodeState.PENDING, 1: NodeState.PENDING, 2: NodeState.TERMINATED, 3: NodeState.TERMINATED, 4: NodeState.TERMINATED, 5: NodeState.RUNNING, 6: NodeState.UNKNOWN, 7: NodeState.PENDING, 8: NodeState.REBOOTING, 9: NodeState.PENDING, 10: NodeState.PENDING, 11: NodeState.TERMINATED, 12: NodeState.PENDING, 13: NodeState.PENDING, 14: NodeState.PENDING, 15: NodeState.PENDING}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_destroy_volume", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 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": "libcloud/compute/drivers/ibm_sce.py", "focal_class": null, "focal_method": "ex_destroy_image", "tests": "import unittest\n\nclass Test_ex_destroy_image(unittest.TestCase):\n def test_ex_destroy_image(self):\n image = self.driver.list_images()\n IBMMockHttp.type = 'DESTROY'\n ret = self.driver.ex_destroy_image(image[0])\n self.assertTrue(ret)\n", "method_code": " def ex_destroy_image(self, image):\n \"\"\"\n Destroys an image.\n \n @param image: Image to be destroyed\n @type image: L{NodeImage}\n \n @return: C{bool}\n \"\"\"\n url = REST_BASE + '/offerings/image/%s' % image.id\n status = int(self.connection.request(action=url, method='DELETE').status)\n return status == 200\n ", "context": "class IBMNodeDriver(NodeDriver):\n def ex_destroy_image(self, image): ...\n def create_node(self, **kwargs): ...\n def create_volume(self, size, name, location, **kwargs): ...\n def create_image(self, name, description=None, **kwargs): ...\n def destroy_node(self, node): ...\n def destroy_volume(self, volume): ...\n def attach_volume(self, node, volume): ...\n def detach_volume(self, node, volume): ...\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def list_volumes(self): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def ex_list_storage_offerings(self): ...\n def ex_allocate_address(self, location_id, offering_id, vlan_id=None): ...\n def ex_list_addresses(self, resource_id=None): ...\n def ex_copy_to(self, image, volume): ...\n def ex_delete_address(self, resource_id): ...\n def ex_wait_storage_state(self, volume, state=VolumeState.DETACHED, wait_period=60, timeout=1200): ...\n def _to_nodes(self, object): ...\n def _to_node(self, instance): ...\n def _to_images(self, object): ...\n def _to_image(self, image): ...\n def _to_locations(self, object): ...\n def _to_location(self, location): ...\n def _to_node_sizes(self, object): ...\n def _to_node_size(self, object): ...\n def _to_volumes(self, object): ...\n def _to_volume(self, object): ...\n def _to_volume_offerings(self, object): ...\n def _to_volume_offering(self, object): ...\n def _to_addresses(self, object): ...\n def _to_address(self, object): ...\n\n connectionCls = IBMConnection\n type = Provider.IBM\n name = 'IBM SmartCloud Enterprise'\n website = 'http://ibm.com/services/us/en/cloud-enterprise/'\n NODE_STATE_MAP = {0: NodeState.PENDING, 1: NodeState.PENDING, 2: NodeState.TERMINATED, 3: NodeState.TERMINATED, 4: NodeState.TERMINATED, 5: NodeState.RUNNING, 6: NodeState.UNKNOWN, 7: NodeState.PENDING, 8: NodeState.REBOOTING, 9: NodeState.PENDING, 10: NodeState.PENDING, 11: NodeState.TERMINATED, 12: NodeState.PENDING, 13: NodeState.PENDING, 14: NodeState.PENDING, 15: NodeState.PENDING}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_destroy_image", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000674.py"} {"focal_file": "libcloud/compute/drivers/ibm_sce.py", "focal_class": null, "focal_method": "detach_volume", "tests": "import unittest\n\nclass Test_detach_volume(unittest.TestCase):\n def test_detach_volume(self):\n nodes = self.driver.list_nodes()\n vols = self.driver.list_volumes()\n IBMMockHttp.type = 'DETACH'\n ret = self.driver.detach_volume(nodes[0], vols[0])\n self.assertTrue(ret)\n", "method_code": " def detach_volume(self, node, volume):\n \"\"\"\n Detaches a volume from a node.\n \n @param node: Node which should be used\n @type node: L{Node}\n \n @param volume: Volume to be detached\n @type volume: L{StorageVolume}\n \n @rtype: C{bool}\n \"\"\"\n url = REST_BASE + '/instances/%s' % node.id\n headers = {'Content-Type': 'application/x-www-form-urlencoded'}\n data = {'storageID': volume.id, 'type': 'detach'}\n resp = self.connection.request(action=url, method='PUT', headers=headers, data=data)\n return int(resp.status) == 200\n ", "context": "class IBMNodeDriver(NodeDriver):\n def detach_volume(self, node, volume): ...\n def create_node(self, **kwargs): ...\n def create_volume(self, size, name, location, **kwargs): ...\n def create_image(self, name, description=None, **kwargs): ...\n def destroy_node(self, node): ...\n def destroy_volume(self, volume): ...\n def ex_destroy_image(self, image): ...\n def attach_volume(self, node, volume): ...\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def list_volumes(self): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def ex_list_storage_offerings(self): ...\n def ex_allocate_address(self, location_id, offering_id, vlan_id=None): ...\n def ex_list_addresses(self, resource_id=None): ...\n def ex_copy_to(self, image, volume): ...\n def ex_delete_address(self, resource_id): ...\n def ex_wait_storage_state(self, volume, state=VolumeState.DETACHED, wait_period=60, timeout=1200): ...\n def _to_nodes(self, object): ...\n def _to_node(self, instance): ...\n def _to_images(self, object): ...\n def _to_image(self, image): ...\n def _to_locations(self, object): ...\n def _to_location(self, location): ...\n def _to_node_sizes(self, object): ...\n def _to_node_size(self, object): ...\n def _to_volumes(self, object): ...\n def _to_volume(self, object): ...\n def _to_volume_offerings(self, object): ...\n def _to_volume_offering(self, object): ...\n def _to_addresses(self, object): ...\n def _to_address(self, object): ...\n\n connectionCls = IBMConnection\n type = Provider.IBM\n name = 'IBM SmartCloud Enterprise'\n website = 'http://ibm.com/services/us/en/cloud-enterprise/'\n NODE_STATE_MAP = {0: NodeState.PENDING, 1: NodeState.PENDING, 2: NodeState.TERMINATED, 3: NodeState.TERMINATED, 4: NodeState.TERMINATED, 5: NodeState.RUNNING, 6: NodeState.UNKNOWN, 7: NodeState.PENDING, 8: NodeState.REBOOTING, 9: NodeState.PENDING, 10: NodeState.PENDING, 11: NodeState.TERMINATED, 12: NodeState.PENDING, 13: NodeState.PENDING, 14: NodeState.PENDING, 15: NodeState.PENDING}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_detach_volume", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 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": "libcloud/compute/drivers/ibm_sce.py", "focal_class": null, "focal_method": "ex_allocate_address", "tests": "import unittest\n\nclass Test_ex_allocate_address(unittest.TestCase):\n def test_ex_allocate_address(self):\n IBMMockHttp.type = 'ALLOCATE'\n ret = self.driver.ex_allocate_address('141', '20001223')\n self.assertEqual(ret.id, '292795')\n self.assertEqual(ret.state, '0')\n self.assertEqual(ret.options['location'], '141')\n", "method_code": " def ex_allocate_address(self, location_id, offering_id, vlan_id=None):\n \"\"\"\n Allocate a new reserved IP address\n \n @param location_id: Target data center\n @type location_id: C{str}\n \n @param offering_id: Offering ID for address to create\n @type offering_id: C{str}\n \n @param vlan_id: ID of target VLAN\n @type vlan_id: C{str}\n \n @return: L{Address} object\n @rtype: L{Address}\n \"\"\"\n url = REST_BASE + '/addresses'\n headers = {'Content-Type': 'application/x-www-form-urlencoded'}\n data = {'location': location_id, 'offeringID': offering_id}\n if vlan_id is not None:\n data.update({'vlanID': vlan_id})\n resp = self.connection.request(action=url, method='POST', headers=headers, data=data).object\n return self._to_addresses(resp)[0]\n ", "context": "class IBMNodeDriver(NodeDriver):\n def ex_allocate_address(self, location_id, offering_id, vlan_id=None): ...\n def create_node(self, **kwargs): ...\n def create_volume(self, size, name, location, **kwargs): ...\n def create_image(self, name, description=None, **kwargs): ...\n def destroy_node(self, node): ...\n def destroy_volume(self, volume): ...\n def ex_destroy_image(self, image): ...\n def attach_volume(self, node, volume): ...\n def detach_volume(self, node, volume): ...\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def list_volumes(self): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def ex_list_storage_offerings(self): ...\n def ex_list_addresses(self, resource_id=None): ...\n def ex_copy_to(self, image, volume): ...\n def ex_delete_address(self, resource_id): ...\n def ex_wait_storage_state(self, volume, state=VolumeState.DETACHED, wait_period=60, timeout=1200): ...\n def _to_nodes(self, object): ...\n def _to_node(self, instance): ...\n def _to_images(self, object): ...\n def _to_image(self, image): ...\n def _to_locations(self, object): ...\n def _to_location(self, location): ...\n def _to_node_sizes(self, object): ...\n def _to_node_size(self, object): ...\n def _to_volumes(self, object): ...\n def _to_volume(self, object): ...\n def _to_volume_offerings(self, object): ...\n def _to_volume_offering(self, object): ...\n def _to_addresses(self, object): ...\n def _to_address(self, object): ...\n\n connectionCls = IBMConnection\n type = Provider.IBM\n name = 'IBM SmartCloud Enterprise'\n website = 'http://ibm.com/services/us/en/cloud-enterprise/'\n NODE_STATE_MAP = {0: NodeState.PENDING, 1: NodeState.PENDING, 2: NodeState.TERMINATED, 3: NodeState.TERMINATED, 4: NodeState.TERMINATED, 5: NodeState.RUNNING, 6: NodeState.UNKNOWN, 7: NodeState.PENDING, 8: NodeState.REBOOTING, 9: NodeState.PENDING, 10: NodeState.PENDING, 11: NodeState.TERMINATED, 12: NodeState.PENDING, 13: NodeState.PENDING, 14: NodeState.PENDING, 15: NodeState.PENDING}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_allocate_address", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000676.py"} {"focal_file": "libcloud/compute/drivers/ibm_sce.py", "focal_class": null, "focal_method": "ex_delete_address", "tests": "import unittest\n\nclass Test_ex_delete_address(unittest.TestCase):\n def test_ex_delete_address(self):\n IBMMockHttp.type = 'DELETE'\n ret = self.driver.ex_delete_address('292795')\n self.assertTrue(ret)\n", "method_code": " def ex_delete_address(self, resource_id):\n \"\"\"\n Delete a reserved IP address\n \n @param resource_id: The address to delete (required)\n @type resource_id: C{str}\n \n @rtype: C{bool}\n \"\"\"\n url = REST_BASE + '/addresses/' + resource_id\n status = int(self.connection.request(action=url, method='DELETE').status)\n return status == 200\n ", "context": "class IBMNodeDriver(NodeDriver):\n def ex_delete_address(self, resource_id): ...\n def create_node(self, **kwargs): ...\n def create_volume(self, size, name, location, **kwargs): ...\n def create_image(self, name, description=None, **kwargs): ...\n def destroy_node(self, node): ...\n def destroy_volume(self, volume): ...\n def ex_destroy_image(self, image): ...\n def attach_volume(self, node, volume): ...\n def detach_volume(self, node, volume): ...\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def list_volumes(self): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def ex_list_storage_offerings(self): ...\n def ex_allocate_address(self, location_id, offering_id, vlan_id=None): ...\n def ex_list_addresses(self, resource_id=None): ...\n def ex_copy_to(self, image, volume): ...\n def ex_wait_storage_state(self, volume, state=VolumeState.DETACHED, wait_period=60, timeout=1200): ...\n def _to_nodes(self, object): ...\n def _to_node(self, instance): ...\n def _to_images(self, object): ...\n def _to_image(self, image): ...\n def _to_locations(self, object): ...\n def _to_location(self, location): ...\n def _to_node_sizes(self, object): ...\n def _to_node_size(self, object): ...\n def _to_volumes(self, object): ...\n def _to_volume(self, object): ...\n def _to_volume_offerings(self, object): ...\n def _to_volume_offering(self, object): ...\n def _to_addresses(self, object): ...\n def _to_address(self, object): ...\n\n connectionCls = IBMConnection\n type = Provider.IBM\n name = 'IBM SmartCloud Enterprise'\n website = 'http://ibm.com/services/us/en/cloud-enterprise/'\n NODE_STATE_MAP = {0: NodeState.PENDING, 1: NodeState.PENDING, 2: NodeState.TERMINATED, 3: NodeState.TERMINATED, 4: NodeState.TERMINATED, 5: NodeState.RUNNING, 6: NodeState.UNKNOWN, 7: NodeState.PENDING, 8: NodeState.REBOOTING, 9: NodeState.PENDING, 10: NodeState.PENDING, 11: NodeState.TERMINATED, 12: NodeState.PENDING, 13: NodeState.PENDING, 14: NodeState.PENDING, 15: NodeState.PENDING}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_delete_address", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 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": "libcloud/compute/drivers/ibm_sce.py", "focal_class": null, "focal_method": "ex_list_addresses", "tests": "import unittest\n\nclass Test_ex_list_addresses(unittest.TestCase):\n def test_ex_list_addresses(self):\n ret = self.driver.ex_list_addresses()\n self.assertEqual(ret[0].ip, '170.225.160.218')\n self.assertEqual(ret[0].options['location'], '141')\n self.assertEqual(ret[0].id, '292795')\n self.assertEqual(ret[0].state, '2')\n", "method_code": " def ex_list_addresses(self, resource_id=None):\n \"\"\"\n List the reserved IP addresses\n \n @param resource_id: If this is supplied only a single address will\n be returned (optional)\n @type resource_id: C{str}\n \n @rtype: C{list} of L{Address}\n \"\"\"\n url = REST_BASE + '/addresses'\n if resource_id:\n url += '/' + resource_id\n return self._to_addresses(self.connection.request(url).object)\n ", "context": "class IBMNodeDriver(NodeDriver):\n def ex_list_addresses(self, resource_id=None): ...\n def create_node(self, **kwargs): ...\n def create_volume(self, size, name, location, **kwargs): ...\n def create_image(self, name, description=None, **kwargs): ...\n def destroy_node(self, node): ...\n def destroy_volume(self, volume): ...\n def ex_destroy_image(self, image): ...\n def attach_volume(self, node, volume): ...\n def detach_volume(self, node, volume): ...\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def list_volumes(self): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def ex_list_storage_offerings(self): ...\n def ex_allocate_address(self, location_id, offering_id, vlan_id=None): ...\n def ex_copy_to(self, image, volume): ...\n def ex_delete_address(self, resource_id): ...\n def ex_wait_storage_state(self, volume, state=VolumeState.DETACHED, wait_period=60, timeout=1200): ...\n def _to_nodes(self, object): ...\n def _to_node(self, instance): ...\n def _to_images(self, object): ...\n def _to_image(self, image): ...\n def _to_locations(self, object): ...\n def _to_location(self, location): ...\n def _to_node_sizes(self, object): ...\n def _to_node_size(self, object): ...\n def _to_volumes(self, object): ...\n def _to_volume(self, object): ...\n def _to_volume_offerings(self, object): ...\n def _to_volume_offering(self, object): ...\n def _to_addresses(self, object): ...\n def _to_address(self, object): ...\n\n connectionCls = IBMConnection\n type = Provider.IBM\n name = 'IBM SmartCloud Enterprise'\n website = 'http://ibm.com/services/us/en/cloud-enterprise/'\n NODE_STATE_MAP = {0: NodeState.PENDING, 1: NodeState.PENDING, 2: NodeState.TERMINATED, 3: NodeState.TERMINATED, 4: NodeState.TERMINATED, 5: NodeState.RUNNING, 6: NodeState.UNKNOWN, 7: NodeState.PENDING, 8: NodeState.REBOOTING, 9: NodeState.PENDING, 10: NodeState.PENDING, 11: NodeState.TERMINATED, 12: NodeState.PENDING, 13: NodeState.PENDING, 14: NodeState.PENDING, 15: NodeState.PENDING}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_list_addresses", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000678.py"} {"focal_file": "libcloud/compute/drivers/ibm_sce.py", "focal_class": null, "focal_method": "ex_list_storage_offerings", "tests": "import unittest\n\nclass Test_ex_list_storage_offerings(unittest.TestCase):\n def test_ex_list_storage_offerings(self):\n ret = self.driver.ex_list_storage_offerings()\n self.assertEqual(ret[0].name, 'Small')\n self.assertEqual(ret[0].location, '61')\n self.assertEqual(ret[0].id, '20001208')\n", "method_code": " def ex_list_storage_offerings(self):\n \"\"\"\n List the storage center offerings\n \n @rtype: C{list} of L{VolumeOffering}\n \"\"\"\n return self._to_volume_offerings(self.connection.request(REST_BASE + '/offerings/storage').object)\n ", "context": "class IBMNodeDriver(NodeDriver):\n def ex_list_storage_offerings(self): ...\n def create_node(self, **kwargs): ...\n def create_volume(self, size, name, location, **kwargs): ...\n def create_image(self, name, description=None, **kwargs): ...\n def destroy_node(self, node): ...\n def destroy_volume(self, volume): ...\n def ex_destroy_image(self, image): ...\n def attach_volume(self, node, volume): ...\n def detach_volume(self, node, volume): ...\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def list_volumes(self): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def ex_allocate_address(self, location_id, offering_id, vlan_id=None): ...\n def ex_list_addresses(self, resource_id=None): ...\n def ex_copy_to(self, image, volume): ...\n def ex_delete_address(self, resource_id): ...\n def ex_wait_storage_state(self, volume, state=VolumeState.DETACHED, wait_period=60, timeout=1200): ...\n def _to_nodes(self, object): ...\n def _to_node(self, instance): ...\n def _to_images(self, object): ...\n def _to_image(self, image): ...\n def _to_locations(self, object): ...\n def _to_location(self, location): ...\n def _to_node_sizes(self, object): ...\n def _to_node_size(self, object): ...\n def _to_volumes(self, object): ...\n def _to_volume(self, object): ...\n def _to_volume_offerings(self, object): ...\n def _to_volume_offering(self, object): ...\n def _to_addresses(self, object): ...\n def _to_address(self, object): ...\n\n connectionCls = IBMConnection\n type = Provider.IBM\n name = 'IBM SmartCloud Enterprise'\n website = 'http://ibm.com/services/us/en/cloud-enterprise/'\n NODE_STATE_MAP = {0: NodeState.PENDING, 1: NodeState.PENDING, 2: NodeState.TERMINATED, 3: NodeState.TERMINATED, 4: NodeState.TERMINATED, 5: NodeState.RUNNING, 6: NodeState.UNKNOWN, 7: NodeState.PENDING, 8: NodeState.REBOOTING, 9: NodeState.PENDING, 10: NodeState.PENDING, 11: NodeState.TERMINATED, 12: NodeState.PENDING, 13: NodeState.PENDING, 14: NodeState.PENDING, 15: NodeState.PENDING}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_list_storage_offerings", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000679.py"} {"focal_file": "libcloud/compute/drivers/joyent.py", "focal_class": null, "focal_method": "list_sizes", "tests": "import unittest\n\nclass Test_list_sizes(unittest.TestCase):\n def test_list_sizes(self):\n sizes = self.driver.list_sizes()\n self.assertEqual(sizes[0].ram, 16384)\n", "method_code": " def list_sizes(self):\n result = self.connection.request('/my/packages').object\n sizes = []\n for value in result:\n size = NodeSize(id=value['name'], name=value['name'], ram=value['memory'], disk=value['disk'], bandwidth=None, price=0.0, driver=self.connection.driver)\n sizes.append(size)\n return sizes\n ", "context": "class JoyentNodeDriver(NodeDriver):\n def list_sizes(self): ...\n def __init__(self, *args, **kwargs): ...\n def list_images(self): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def create_node(self, **kwargs): ...\n def ex_stop_node(self, node): ...\n def ex_start_node(self, node): ...\n def _to_node(self, data): ...\n\n self.connection.host = kwargs['location'] + API_HOST_SUFFIX\n\n type = Provider.JOYENT\n name = 'Joyent'\n website = 'http://www.joyentcloud.com'\n connectionCls = JoyentConnection\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_sizes", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 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": "libcloud/compute/drivers/joyent.py", "focal_class": null, "focal_method": "list_images", "tests": "import unittest\n\nclass Test_list_images(unittest.TestCase):\n def test_list_images(self):\n images = self.driver.list_images()\n self.assertEqual(images[0].name, 'nodejs')\n", "method_code": " def list_images(self):\n result = self.connection.request('/my/datasets').object\n images = []\n for value in result:\n extra = {'type': value['type'], 'urn': value['urn'], 'os': value['os'], 'default': value['default']}\n image = NodeImage(id=value['id'], name=value['name'], driver=self.connection.driver, extra=extra)\n images.append(image)\n return images\n ", "context": "class JoyentNodeDriver(NodeDriver):\n def list_images(self): ...\n def __init__(self, *args, **kwargs): ...\n def list_sizes(self): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def create_node(self, **kwargs): ...\n def ex_stop_node(self, node): ...\n def ex_start_node(self, node): ...\n def _to_node(self, data): ...\n\n self.connection.host = kwargs['location'] + API_HOST_SUFFIX\n\n type = Provider.JOYENT\n name = 'Joyent'\n website = 'http://www.joyentcloud.com'\n connectionCls = JoyentConnection\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_images", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000681.py"} {"focal_file": "libcloud/compute/drivers/joyent.py", "focal_class": null, "focal_method": "create_node", "tests": "import unittest\n\nclass Test_create_node(unittest.TestCase):\n def test_create_node(self):\n image = self.driver.list_images()[0]\n size = self.driver.list_sizes()[0]\n node = self.driver.create_node(image=image, size=size, name='testlc')\n self.assertEqual(node.name, 'testlc')\n", "method_code": " def create_node(self, **kwargs):\n name = kwargs['name']\n size = kwargs['size']\n image = kwargs['image']\n data = json.dumps({'name': name, 'package': size.id, 'dataset': image.id})\n result = self.connection.request('/my/machines', data=data, method='POST')\n return self._to_node(result.object)\n ", "context": "class JoyentNodeDriver(NodeDriver):\n def create_node(self, **kwargs): ...\n def __init__(self, *args, **kwargs): ...\n def list_images(self): ...\n def list_sizes(self): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def ex_stop_node(self, node): ...\n def ex_start_node(self, node): ...\n def _to_node(self, data): ...\n\n self.connection.host = kwargs['location'] + API_HOST_SUFFIX\n\n type = Provider.JOYENT\n name = 'Joyent'\n website = 'http://www.joyentcloud.com'\n connectionCls = JoyentConnection\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 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": "libcloud/compute/drivers/joyent.py", "focal_class": null, "focal_method": "ex_stop_node", "tests": "import unittest\n\nclass Test_ex_stop_node(unittest.TestCase):\n def test_ex_stop_node(self):\n node = self.driver.list_nodes()[0]\n self.assertTrue(self.driver.ex_stop_node(node))\n", "method_code": " def ex_stop_node(self, node):\n \"\"\"\n Stop node\n \n @param node: The node to be stopped\n @type node: L{Node}\n \n @rtype: C{bool}\n \"\"\"\n data = json.dumps({'action': 'stop'})\n result = self.connection.request('/my/machines/%s' % node.id, data=data, method='POST')\n return result.status == httplib.ACCEPTED\n ", "context": "class JoyentNodeDriver(NodeDriver):\n def ex_stop_node(self, node): ...\n def __init__(self, *args, **kwargs): ...\n def list_images(self): ...\n def list_sizes(self): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def create_node(self, **kwargs): ...\n def ex_start_node(self, node): ...\n def _to_node(self, data): ...\n\n self.connection.host = kwargs['location'] + API_HOST_SUFFIX\n\n type = Provider.JOYENT\n name = 'Joyent'\n website = 'http://www.joyentcloud.com'\n connectionCls = JoyentConnection\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_stop_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 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": "libcloud/compute/drivers/joyent.py", "focal_class": null, "focal_method": "ex_start_node", "tests": "import unittest\n\nclass Test_ex_start_node(unittest.TestCase):\n def test_ex_start_node(self):\n node = self.driver.list_nodes()[0]\n self.assertTrue(self.driver.ex_start_node(node))\n", "method_code": " def ex_start_node(self, node):\n \"\"\"\n Start node\n \n @param node: The node to be stopped\n @type node: L{Node}\n \n @rtype: C{bool}\n \"\"\"\n data = json.dumps({'action': 'start'})\n result = self.connection.request('/my/machines/%s' % node.id, data=data, method='POST')\n return result.status == httplib.ACCEPTED\n ", "context": "class JoyentNodeDriver(NodeDriver):\n def ex_start_node(self, node): ...\n def __init__(self, *args, **kwargs): ...\n def list_images(self): ...\n def list_sizes(self): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def create_node(self, **kwargs): ...\n def ex_stop_node(self, node): ...\n def _to_node(self, data): ...\n\n self.connection.host = kwargs['location'] + API_HOST_SUFFIX\n\n type = Provider.JOYENT\n name = 'Joyent'\n website = 'http://www.joyentcloud.com'\n connectionCls = JoyentConnection\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_start_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/compute/drivers/linode.py", "focal_class": null, "focal_method": "list_nodes", "tests": "import unittest\n\nclass Test_list_nodes(unittest.TestCase):\n def test_list_nodes(self):\n nodes = self.driver.list_nodes()\n self.assertEqual(len(nodes), 1)\n node = nodes[0]\n self.assertEqual(node.id, '8098')\n self.assertEqual(node.name, 'api-node3')\n self.assertEqual(node.extra['PLANID'], '1')\n self.assertTrue('75.127.96.245' in node.public_ips)\n self.assertEqual(node.private_ips, [])\n", "method_code": " def list_nodes(self):\n \"\"\"\n List all Linodes that the API key can access\n \n This call will return all Linodes that the API key in use has access\n to.\n If a node is in this list, rebooting will work; however, creation and\n destruction are a separate grant.\n \n @return: List of node objects that the API key can access\n @rtype: C{list} of L{Node}\n \"\"\"\n params = {'api_action': 'linode.list'}\n data = self.connection.request(API_ROOT, params=params).objects[0]\n return self._to_nodes(data)\n ", "context": "class LinodeNodeDriver(NodeDriver):\n def list_nodes(self): ...\n def __init__(self, key): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def create_node(self, **kwargs): ...\n def list_sizes(self, location=None): ...\n def list_images(self): ...\n def list_locations(self): ...\n def linode_set_datacenter(self, dc): ...\n def _to_nodes(self, objs): ...\n\n self.datacenter = None\n\n type = Provider.LINODE\n name = 'Linode'\n website = 'http://www.linode.com/'\n connectionCls = LinodeConnection\n _linode_plan_ids = LINODE_PLAN_IDS\n LINODE_STATES = {-2: NodeState.UNKNOWN, -1: NodeState.PENDING, 0: NodeState.PENDING, 1: NodeState.RUNNING, 2: NodeState.TERMINATED, 3: NodeState.REBOOTING, 4: NodeState.UNKNOWN}\n features = {'create_node': ['ssh_key', 'password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_nodes", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000685.py"} {"focal_file": "libcloud/compute/drivers/linode.py", "focal_class": null, "focal_method": "reboot_node", "tests": "import unittest\n\nclass Test_reboot_node(unittest.TestCase):\n def test_reboot_node(self):\n node = self.driver.list_nodes()[0]\n self.driver.reboot_node(node)\n", "method_code": " def reboot_node(self, node):\n \"\"\"\n Reboot the given Linode\n \n Will issue a shutdown job followed by a boot job, using the last booted\n configuration. In most cases, this will be the only configuration.\n \n @param node: the Linode to reboot\n @type node: L{Node}\n \n @rtype: C{bool}\n \"\"\"\n params = {'api_action': 'linode.reboot', 'LinodeID': node.id}\n self.connection.request(API_ROOT, params=params)\n return True\n ", "context": "class LinodeNodeDriver(NodeDriver):\n def reboot_node(self, node): ...\n def __init__(self, key): ...\n def list_nodes(self): ...\n def destroy_node(self, node): ...\n def create_node(self, **kwargs): ...\n def list_sizes(self, location=None): ...\n def list_images(self): ...\n def list_locations(self): ...\n def linode_set_datacenter(self, dc): ...\n def _to_nodes(self, objs): ...\n\n self.datacenter = None\n\n type = Provider.LINODE\n name = 'Linode'\n website = 'http://www.linode.com/'\n connectionCls = LinodeConnection\n _linode_plan_ids = LINODE_PLAN_IDS\n LINODE_STATES = {-2: NodeState.UNKNOWN, -1: NodeState.PENDING, 0: NodeState.PENDING, 1: NodeState.RUNNING, 2: NodeState.TERMINATED, 3: NodeState.REBOOTING, 4: NodeState.UNKNOWN}\n features = {'create_node': ['ssh_key', 'password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_reboot_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000686.py"} {"focal_file": "libcloud/compute/drivers/linode.py", "focal_class": null, "focal_method": "destroy_node", "tests": "import unittest\n\nclass Test_destroy_node(unittest.TestCase):\n def test_destroy_node(self):\n node = self.driver.list_nodes()[0]\n self.driver.destroy_node(node)\n", "method_code": " def destroy_node(self, node):\n \"\"\"Destroy the given Linode\n \n Will remove the Linode from the account and issue a prorated credit. A\n grant for removing Linodes from the account is required, otherwise this\n method will fail.\n \n In most cases, all disk images must be removed from a Linode before the\n Linode can be removed; however, this call explicitly skips those\n safeguards. There is no going back from this method.\n \n @param node: the Linode to destroy\n @type node: L{Node}\n \n @rtype: C{bool}\n \"\"\"\n params = {'api_action': 'linode.delete', 'LinodeID': node.id, 'skipChecks': True}\n self.connection.request(API_ROOT, params=params)\n return True\n ", "context": "class LinodeNodeDriver(NodeDriver):\n def destroy_node(self, node): ...\n def __init__(self, key): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def create_node(self, **kwargs): ...\n def list_sizes(self, location=None): ...\n def list_images(self): ...\n def list_locations(self): ...\n def linode_set_datacenter(self, dc): ...\n def _to_nodes(self, objs): ...\n\n self.datacenter = None\n\n type = Provider.LINODE\n name = 'Linode'\n website = 'http://www.linode.com/'\n connectionCls = LinodeConnection\n _linode_plan_ids = LINODE_PLAN_IDS\n LINODE_STATES = {-2: NodeState.UNKNOWN, -1: NodeState.PENDING, 0: NodeState.PENDING, 1: NodeState.RUNNING, 2: NodeState.TERMINATED, 3: NodeState.REBOOTING, 4: NodeState.UNKNOWN}\n features = {'create_node': ['ssh_key', 'password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_destroy_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000687.py"} {"focal_file": "libcloud/compute/drivers/linode.py", "focal_class": null, "focal_method": "list_sizes", "tests": "import unittest\n\nclass Test_list_sizes(unittest.TestCase):\n def test_list_sizes(self):\n sizes = self.driver.list_sizes()\n self.assertEqual(len(sizes), 10)\n for size in sizes:\n self.assertEqual(size.ram, int(size.name.split(' ')[1]))\n", "method_code": " def list_sizes(self, location=None):\n \"\"\"\n List available Linode plans\n \n Gets the sizes that can be used for creating a Linode. Since available\n Linode plans vary per-location, this method can also be passed a\n location to filter the availability.\n \n @keyword location: the facility to retrieve plans in\n @type location: L{NodeLocation}\n \n @rtype: C{list} of L{NodeSize}\n \"\"\"\n params = {'api_action': 'avail.linodeplans'}\n data = self.connection.request(API_ROOT, params=params).objects[0]\n sizes = []\n for obj in data:\n n = NodeSize(id=obj['PLANID'], name=obj['LABEL'], ram=obj['RAM'], disk=obj['DISK'] * 1024, bandwidth=obj['XFER'], price=obj['PRICE'], driver=self.connection.driver)\n sizes.append(n)\n return sizes\n ", "context": "class LinodeNodeDriver(NodeDriver):\n def list_sizes(self, location=None): ...\n def __init__(self, key): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def create_node(self, **kwargs): ...\n def list_images(self): ...\n def list_locations(self): ...\n def linode_set_datacenter(self, dc): ...\n def _to_nodes(self, objs): ...\n\n self.datacenter = None\n\n type = Provider.LINODE\n name = 'Linode'\n website = 'http://www.linode.com/'\n connectionCls = LinodeConnection\n _linode_plan_ids = LINODE_PLAN_IDS\n LINODE_STATES = {-2: NodeState.UNKNOWN, -1: NodeState.PENDING, 0: NodeState.PENDING, 1: NodeState.RUNNING, 2: NodeState.TERMINATED, 3: NodeState.REBOOTING, 4: NodeState.UNKNOWN}\n features = {'create_node': ['ssh_key', 'password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_sizes", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000688.py"} {"focal_file": "libcloud/compute/drivers/linode.py", "focal_class": null, "focal_method": "list_images", "tests": "import unittest\n\nclass Test_list_images(unittest.TestCase):\n def test_list_images(self):\n images = self.driver.list_images()\n self.assertEqual(len(images), 22)\n", "method_code": " def list_images(self):\n \"\"\"\n List available Linux distributions\n \n Retrieve all Linux distributions that can be deployed to a Linode.\n \n @rtype: C{list} of L{NodeImage}\n \"\"\"\n params = {'api_action': 'avail.distributions'}\n data = self.connection.request(API_ROOT, params=params).objects[0]\n distros = []\n for obj in data:\n i = NodeImage(id=obj['DISTRIBUTIONID'], name=obj['LABEL'], driver=self.connection.driver, extra={'pvops': obj['REQUIRESPVOPSKERNEL'], '64bit': obj['IS64BIT']})\n distros.append(i)\n return distros\n ", "context": "class LinodeNodeDriver(NodeDriver):\n def list_images(self): ...\n def __init__(self, key): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def create_node(self, **kwargs): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def linode_set_datacenter(self, dc): ...\n def _to_nodes(self, objs): ...\n\n self.datacenter = None\n\n type = Provider.LINODE\n name = 'Linode'\n website = 'http://www.linode.com/'\n connectionCls = LinodeConnection\n _linode_plan_ids = LINODE_PLAN_IDS\n LINODE_STATES = {-2: NodeState.UNKNOWN, -1: NodeState.PENDING, 0: NodeState.PENDING, 1: NodeState.RUNNING, 2: NodeState.TERMINATED, 3: NodeState.REBOOTING, 4: NodeState.UNKNOWN}\n features = {'create_node': ['ssh_key', 'password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_images", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000689.py"} {"focal_file": "libcloud/compute/drivers/opennebula.py", "focal_class": null, "focal_method": "create_node", "tests": "import unittest\n\nclass Test_create_node(unittest.TestCase):\n def test_create_node(self):\n \"\"\"\n Test create_node functionality.\n \"\"\"\n image = NodeImage(id=5, name='Ubuntu 9.04 LAMP', driver=self.driver)\n size = OpenNebulaNodeSize(id=1, name='small', ram=1024, cpu=1, disk=None, bandwidth=None, price=None, driver=self.driver)\n networks = list()\n networks.append(OpenNebulaNetwork(id=5, name='Network 5', address='192.168.0.0', size=256, driver=self.driver))\n networks.append(OpenNebulaNetwork(id=15, name='Network 15', address='192.168.1.0', size=256, driver=self.driver))\n context = {'hostname': 'compute-5'}\n node = self.driver.create_node(name='Compute 5', image=image, size=size, networks=networks, context=context)\n self.assertEqual(node.id, '5')\n self.assertEqual(node.name, 'Compute 5')\n self.assertEqual(node.state, OpenNebulaNodeDriver.NODE_STATE_MAP['ACTIVE'])\n self.assertEqual(node.public_ips[0].id, '5')\n self.assertEqual(node.public_ips[0].name, 'Network 5')\n self.assertEqual(node.public_ips[0].address, '192.168.0.1')\n self.assertEqual(node.public_ips[0].size, 1)\n self.assertEqual(node.public_ips[0].extra['mac'], '02:00:c0:a8:00:01')\n self.assertEqual(node.public_ips[1].id, '15')\n self.assertEqual(node.public_ips[1].name, 'Network 15')\n self.assertEqual(node.public_ips[1].address, '192.168.1.1')\n self.assertEqual(node.public_ips[1].size, 1)\n self.assertEqual(node.public_ips[1].extra['mac'], '02:00:c0:a8:01:01')\n self.assertEqual(node.private_ips, [])\n self.assertTrue(len([size for size in self.driver.list_sizes() if size.id == node.size.id]) == 1)\n self.assertEqual(node.image.id, '5')\n self.assertEqual(node.image.name, 'Ubuntu 9.04 LAMP')\n self.assertEqual(node.image.extra['type'], 'DISK')\n self.assertEqual(node.image.extra['target'], 'hda')\n context = node.extra['context']\n self.assertEqual(context['hostname'], 'compute-5')\n", "method_code": " def create_node(self, **kwargs):\n \"\"\"\n Create a new OpenNebula node.\n \n @inherits: L{NodeDriver.create_node}\n \n @keyword networks: List of virtual networks to which this node should\n connect. (optional)\n @type networks: L{OpenNebulaNetwork} or\n C{list} of L{OpenNebulaNetwork}\n \"\"\"\n compute = ET.Element('COMPUTE')\n name = ET.SubElement(compute, 'NAME')\n name.text = kwargs['name']\n instance_type = ET.SubElement(compute, 'INSTANCE_TYPE')\n instance_type.text = kwargs['size'].name\n storage = ET.SubElement(compute, 'STORAGE')\n ET.SubElement(storage, 'DISK', {'image': '%s' % str(kwargs['image'].id)})\n if 'networks' in kwargs:\n if not isinstance(kwargs['networks'], list):\n kwargs['networks'] = [kwargs['networks']]\n networkGroup = ET.SubElement(compute, 'NETWORK')\n for network in kwargs['networks']:\n if network.address:\n ET.SubElement(networkGroup, 'NIC', {'network': '%s' % str(network.id), 'ip': network.address})\n else:\n ET.SubElement(networkGroup, 'NIC', {'network': '%s' % str(network.id)})\n xml = ET.tostring(compute)\n node = self.connection.request('/compute', method='POST', data=xml).object\n return self._to_node(node)\n ", "context": "class OpenNebulaNodeDriver(NodeDriver):\n def create_node(self, **kwargs): ...\n def __new__(cls, key, secret=None, api_version=DEFAULT_API_VERSION, **kwargs): ...\n def destroy_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def ex_list_networks(self, location=None): ...\n def ex_node_action(self, node, action): ...\n def _to_images(self, object): ...\n def _to_image(self, image): ...\n def _to_networks(self, object): ...\n def _to_network(self, element): ...\n def _to_nodes(self, object): ...\n def _to_node(self, compute): ...\n def _extract_networks(self, compute): ...\n def _extract_images(self, compute): ...\n\n connectionCls = OpenNebulaConnection\n name = 'OpenNebula'\n website = 'http://opennebula.org/'\n type = Provider.OPENNEBULA\n NODE_STATE_MAP = {'INIT': NodeState.PENDING, 'PENDING': NodeState.PENDING, 'HOLD': NodeState.PENDING, 'ACTIVE': NodeState.RUNNING, 'STOPPED': NodeState.TERMINATED, 'SUSPENDED': NodeState.PENDING, 'DONE': NodeState.TERMINATED, 'FAILED': NodeState.TERMINATED}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000690.py"} {"focal_file": "libcloud/compute/drivers/opennebula.py", "focal_class": null, "focal_method": "destroy_node", "tests": "import unittest\n\nclass Test_destroy_node(unittest.TestCase):\n def test_destroy_node(self):\n \"\"\"\n Test destroy_node functionality.\n \"\"\"\n node = Node(5, None, None, None, None, self.driver)\n ret = self.driver.destroy_node(node)\n self.assertTrue(ret)\n", "method_code": " def destroy_node(self, node):\n url = '/compute/%s' % str(node.id)\n resp = self.connection.request(url, method='DELETE')\n return resp.status == httplib.OK\n ", "context": "class OpenNebulaNodeDriver(NodeDriver):\n def destroy_node(self, node): ...\n def __new__(cls, key, secret=None, api_version=DEFAULT_API_VERSION, **kwargs): ...\n def create_node(self, **kwargs): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def ex_list_networks(self, location=None): ...\n def ex_node_action(self, node, action): ...\n def _to_images(self, object): ...\n def _to_image(self, image): ...\n def _to_networks(self, object): ...\n def _to_network(self, element): ...\n def _to_nodes(self, object): ...\n def _to_node(self, compute): ...\n def _extract_networks(self, compute): ...\n def _extract_images(self, compute): ...\n\n connectionCls = OpenNebulaConnection\n name = 'OpenNebula'\n website = 'http://opennebula.org/'\n type = Provider.OPENNEBULA\n NODE_STATE_MAP = {'INIT': NodeState.PENDING, 'PENDING': NodeState.PENDING, 'HOLD': NodeState.PENDING, 'ACTIVE': NodeState.RUNNING, 'STOPPED': NodeState.TERMINATED, 'SUSPENDED': NodeState.PENDING, 'DONE': NodeState.TERMINATED, 'FAILED': NodeState.TERMINATED}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_destroy_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 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": "libcloud/compute/drivers/opennebula.py", "focal_class": null, "focal_method": "list_nodes", "tests": "import unittest\n\nclass Test_list_nodes(unittest.TestCase):\n def test_list_nodes(self):\n \"\"\"\n Test list_nodes functionality.\n \"\"\"\n nodes = self.driver.list_nodes()\n self.assertEqual(len(nodes), 3)\n node = nodes[0]\n self.assertEqual(node.id, '5')\n self.assertEqual(node.name, 'Compute 5')\n self.assertEqual(node.state, OpenNebulaNodeDriver.NODE_STATE_MAP['ACTIVE'])\n self.assertEqual(node.public_ips[0].id, '5')\n self.assertEqual(node.public_ips[0].name, 'Network 5')\n self.assertEqual(node.public_ips[0].address, '192.168.0.1')\n self.assertEqual(node.public_ips[0].size, 1)\n self.assertEqual(node.public_ips[0].extra['mac'], '02:00:c0:a8:00:01')\n self.assertEqual(node.public_ips[1].id, '15')\n self.assertEqual(node.public_ips[1].name, 'Network 15')\n self.assertEqual(node.public_ips[1].address, '192.168.1.1')\n self.assertEqual(node.public_ips[1].size, 1)\n self.assertEqual(node.public_ips[1].extra['mac'], '02:00:c0:a8:01:01')\n self.assertEqual(node.private_ips, [])\n self.assertTrue(len([size for size in self.driver.list_sizes() if size.id == node.size.id]) == 1)\n self.assertEqual(node.size.id, '1')\n self.assertEqual(node.size.name, 'small')\n self.assertEqual(node.size.ram, 1024)\n self.assertTrue(node.size.cpu is None or isinstance(node.size.cpu, int))\n self.assertTrue(node.size.vcpu is None or isinstance(node.size.vcpu, int))\n self.assertEqual(node.size.cpu, 1)\n self.assertEqual(node.size.vcpu, None)\n self.assertEqual(node.size.disk, None)\n self.assertEqual(node.size.bandwidth, None)\n self.assertEqual(node.size.price, None)\n self.assertTrue(len([image for image in self.driver.list_images() if image.id == node.image.id]) == 1)\n self.assertEqual(node.image.id, '5')\n self.assertEqual(node.image.name, 'Ubuntu 9.04 LAMP')\n self.assertEqual(node.image.extra['type'], 'DISK')\n self.assertEqual(node.image.extra['target'], 'hda')\n context = node.extra['context']\n self.assertEqual(context['hostname'], 'compute-5')\n node = nodes[1]\n self.assertEqual(node.id, '15')\n self.assertEqual(node.name, 'Compute 15')\n self.assertEqual(node.state, OpenNebulaNodeDriver.NODE_STATE_MAP['ACTIVE'])\n self.assertEqual(node.public_ips[0].id, '5')\n self.assertEqual(node.public_ips[0].name, 'Network 5')\n self.assertEqual(node.public_ips[0].address, '192.168.0.2')\n self.assertEqual(node.public_ips[0].size, 1)\n self.assertEqual(node.public_ips[0].extra['mac'], '02:00:c0:a8:00:02')\n self.assertEqual(node.public_ips[1].id, '15')\n self.assertEqual(node.public_ips[1].name, 'Network 15')\n self.assertEqual(node.public_ips[1].address, '192.168.1.2')\n self.assertEqual(node.public_ips[1].size, 1)\n self.assertEqual(node.public_ips[1].extra['mac'], '02:00:c0:a8:01:02')\n self.assertEqual(node.private_ips, [])\n self.assertTrue(len([size for size in self.driver.list_sizes() if size.id == node.size.id]) == 1)\n self.assertEqual(node.size.id, '1')\n self.assertEqual(node.size.name, 'small')\n self.assertEqual(node.size.ram, 1024)\n self.assertTrue(node.size.cpu is None or isinstance(node.size.cpu, int))\n self.assertTrue(node.size.vcpu is None or isinstance(node.size.vcpu, int))\n self.assertEqual(node.size.cpu, 1)\n self.assertEqual(node.size.vcpu, None)\n self.assertEqual(node.size.disk, None)\n self.assertEqual(node.size.bandwidth, None)\n self.assertEqual(node.size.price, None)\n self.assertTrue(len([image for image in self.driver.list_images() if image.id == node.image.id]) == 1)\n self.assertEqual(node.image.id, '15')\n self.assertEqual(node.image.name, 'Ubuntu 9.04 LAMP')\n self.assertEqual(node.image.extra['type'], 'DISK')\n self.assertEqual(node.image.extra['target'], 'hda')\n context = node.extra['context']\n self.assertEqual(context['hostname'], 'compute-15')\n node = nodes[2]\n self.assertEqual(node.id, '25')\n self.assertEqual(node.name, 'Compute 25')\n self.assertEqual(node.state, NodeState.UNKNOWN)\n self.assertEqual(node.public_ips[0].id, '5')\n self.assertEqual(node.public_ips[0].name, 'Network 5')\n self.assertEqual(node.public_ips[0].address, '192.168.0.3')\n self.assertEqual(node.public_ips[0].size, 1)\n self.assertEqual(node.public_ips[0].extra['mac'], '02:00:c0:a8:00:03')\n self.assertEqual(node.public_ips[1].id, '15')\n self.assertEqual(node.public_ips[1].name, 'Network 15')\n self.assertEqual(node.public_ips[1].address, '192.168.1.3')\n self.assertEqual(node.public_ips[1].size, 1)\n self.assertEqual(node.public_ips[1].extra['mac'], '02:00:c0:a8:01:03')\n self.assertEqual(node.private_ips, [])\n self.assertEqual(node.size, None)\n self.assertEqual(node.image, None)\n context = node.extra['context']\n self.assertEqual(context, {})\n", "method_code": " def list_nodes(self):\n return self._to_nodes(self.connection.request('/compute').object)\n ", "context": "class OpenNebulaNodeDriver(NodeDriver):\n def list_nodes(self): ...\n def __new__(cls, key, secret=None, api_version=DEFAULT_API_VERSION, **kwargs): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def ex_list_networks(self, location=None): ...\n def ex_node_action(self, node, action): ...\n def _to_images(self, object): ...\n def _to_image(self, image): ...\n def _to_networks(self, object): ...\n def _to_network(self, element): ...\n def _to_nodes(self, object): ...\n def _to_node(self, compute): ...\n def _extract_networks(self, compute): ...\n def _extract_images(self, compute): ...\n\n connectionCls = OpenNebulaConnection\n name = 'OpenNebula'\n website = 'http://opennebula.org/'\n type = Provider.OPENNEBULA\n NODE_STATE_MAP = {'INIT': NodeState.PENDING, 'PENDING': NodeState.PENDING, 'HOLD': NodeState.PENDING, 'ACTIVE': NodeState.RUNNING, 'STOPPED': NodeState.TERMINATED, 'SUSPENDED': NodeState.PENDING, 'DONE': NodeState.TERMINATED, 'FAILED': NodeState.TERMINATED}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_nodes", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000692.py"} {"focal_file": "libcloud/compute/drivers/opennebula.py", "focal_class": null, "focal_method": "list_images", "tests": "import unittest\n\nclass Test_list_images(unittest.TestCase):\n def test_list_images(self):\n \"\"\"\n Test list_images functionality.\n \"\"\"\n images = self.driver.list_images()\n self.assertEqual(len(images), 2)\n image = images[0]\n self.assertEqual(image.id, '5')\n self.assertEqual(image.name, 'Ubuntu 9.04 LAMP')\n self.assertEqual(image.extra['description'], 'Ubuntu 9.04 LAMP Description')\n self.assertEqual(image.extra['type'], 'OS')\n self.assertEqual(image.extra['size'], '2048')\n image = images[1]\n self.assertEqual(image.id, '15')\n self.assertEqual(image.name, 'Ubuntu 9.04 LAMP')\n self.assertEqual(image.extra['description'], 'Ubuntu 9.04 LAMP Description')\n self.assertEqual(image.extra['type'], 'OS')\n self.assertEqual(image.extra['size'], '2048')\n", "method_code": " def list_images(self, location=None):\n return self._to_images(self.connection.request('/storage').object)\n ", "context": "class OpenNebulaNodeDriver(NodeDriver):\n def list_images(self, location=None): ...\n def __new__(cls, key, secret=None, api_version=DEFAULT_API_VERSION, **kwargs): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def list_nodes(self): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def ex_list_networks(self, location=None): ...\n def ex_node_action(self, node, action): ...\n def _to_images(self, object): ...\n def _to_image(self, image): ...\n def _to_networks(self, object): ...\n def _to_network(self, element): ...\n def _to_nodes(self, object): ...\n def _to_node(self, compute): ...\n def _extract_networks(self, compute): ...\n def _extract_images(self, compute): ...\n\n connectionCls = OpenNebulaConnection\n name = 'OpenNebula'\n website = 'http://opennebula.org/'\n type = Provider.OPENNEBULA\n NODE_STATE_MAP = {'INIT': NodeState.PENDING, 'PENDING': NodeState.PENDING, 'HOLD': NodeState.PENDING, 'ACTIVE': NodeState.RUNNING, 'STOPPED': NodeState.TERMINATED, 'SUSPENDED': NodeState.PENDING, 'DONE': NodeState.TERMINATED, 'FAILED': NodeState.TERMINATED}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_images", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000693.py"} {"focal_file": "libcloud/compute/drivers/opennebula.py", "focal_class": null, "focal_method": "list_sizes", "tests": "import unittest\n\nclass Test_list_sizes(unittest.TestCase):\n def test_list_sizes(self):\n \"\"\"\n Test ex_list_networks functionality.\n \"\"\"\n sizes = self.driver.list_sizes()\n self.assertEqual(len(sizes), 3)\n size = sizes[0]\n self.assertEqual(size.id, '1')\n self.assertEqual(size.name, 'small')\n self.assertEqual(size.ram, 1024)\n self.assertEqual(size.cpu, 1)\n self.assertEqual(size.vcpu, None)\n self.assertEqual(size.disk, None)\n self.assertEqual(size.bandwidth, None)\n self.assertEqual(size.price, None)\n size = sizes[1]\n self.assertEqual(size.id, '2')\n self.assertEqual(size.name, 'medium')\n self.assertEqual(size.ram, 4096)\n self.assertEqual(size.cpu, 4)\n self.assertEqual(size.vcpu, None)\n self.assertEqual(size.disk, None)\n self.assertEqual(size.bandwidth, None)\n self.assertEqual(size.price, None)\n size = sizes[2]\n self.assertEqual(size.id, '3')\n self.assertEqual(size.name, 'large')\n self.assertEqual(size.ram, 8192)\n self.assertEqual(size.cpu, 8)\n self.assertEqual(size.vcpu, None)\n self.assertEqual(size.disk, None)\n self.assertEqual(size.bandwidth, None)\n self.assertEqual(size.price, None)\n", "method_code": " def list_sizes(self, location=None):\n \"\"\"\n Return list of sizes on a provider.\n \n @inherits: L{NodeDriver.list_sizes}\n \n @return: List of compute node sizes supported by the cloud provider.\n @rtype: C{list} of L{OpenNebulaNodeSize}\n \"\"\"\n return [NodeSize(id=1, name='small', ram=None, disk=None, bandwidth=None, price=None, driver=self), NodeSize(id=2, name='medium', ram=None, disk=None, bandwidth=None, price=None, driver=self), NodeSize(id=3, name='large', ram=None, disk=None, bandwidth=None, price=None, driver=self)]\n ", "context": "class OpenNebulaNodeDriver(NodeDriver):\n def list_sizes(self, location=None): ...\n def __new__(cls, key, secret=None, api_version=DEFAULT_API_VERSION, **kwargs): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def list_locations(self): ...\n def ex_list_networks(self, location=None): ...\n def ex_node_action(self, node, action): ...\n def _to_images(self, object): ...\n def _to_image(self, image): ...\n def _to_networks(self, object): ...\n def _to_network(self, element): ...\n def _to_nodes(self, object): ...\n def _to_node(self, compute): ...\n def _extract_networks(self, compute): ...\n def _extract_images(self, compute): ...\n\n connectionCls = OpenNebulaConnection\n name = 'OpenNebula'\n website = 'http://opennebula.org/'\n type = Provider.OPENNEBULA\n NODE_STATE_MAP = {'INIT': NodeState.PENDING, 'PENDING': NodeState.PENDING, 'HOLD': NodeState.PENDING, 'ACTIVE': NodeState.RUNNING, 'STOPPED': NodeState.TERMINATED, 'SUSPENDED': NodeState.PENDING, 'DONE': NodeState.TERMINATED, 'FAILED': NodeState.TERMINATED}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_sizes", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000694.py"} {"focal_file": "libcloud/compute/drivers/opennebula.py", "focal_class": null, "focal_method": "list_locations", "tests": "import unittest\n\nclass Test_list_locations(unittest.TestCase):\n def test_list_locations(self):\n \"\"\"\n Test list_locations functionality.\n \"\"\"\n locations = self.driver.list_locations()\n self.assertEqual(len(locations), 1)\n location = locations[0]\n self.assertEqual(location.id, '0')\n self.assertEqual(location.name, '')\n self.assertEqual(location.country, '')\n", "method_code": " def list_locations(self):\n return [NodeLocation(0, '', '', self)]\n ", "context": "class OpenNebulaNodeDriver(NodeDriver):\n def list_locations(self): ...\n def __new__(cls, key, secret=None, api_version=DEFAULT_API_VERSION, **kwargs): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def ex_list_networks(self, location=None): ...\n def ex_node_action(self, node, action): ...\n def _to_images(self, object): ...\n def _to_image(self, image): ...\n def _to_networks(self, object): ...\n def _to_network(self, element): ...\n def _to_nodes(self, object): ...\n def _to_node(self, compute): ...\n def _extract_networks(self, compute): ...\n def _extract_images(self, compute): ...\n\n connectionCls = OpenNebulaConnection\n name = 'OpenNebula'\n website = 'http://opennebula.org/'\n type = Provider.OPENNEBULA\n NODE_STATE_MAP = {'INIT': NodeState.PENDING, 'PENDING': NodeState.PENDING, 'HOLD': NodeState.PENDING, 'ACTIVE': NodeState.RUNNING, 'STOPPED': NodeState.TERMINATED, 'SUSPENDED': NodeState.PENDING, 'DONE': NodeState.TERMINATED, 'FAILED': NodeState.TERMINATED}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_locations", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000695.py"} {"focal_file": "libcloud/compute/drivers/opennebula.py", "focal_class": null, "focal_method": "ex_list_networks", "tests": "import unittest\n\nclass Test_ex_list_networks(unittest.TestCase):\n def test_ex_list_networks(self):\n \"\"\"\n Test ex_list_networks functionality.\n \"\"\"\n networks = self.driver.ex_list_networks()\n self.assertEqual(len(networks), 2)\n network = networks[0]\n self.assertEqual(network.id, '5')\n self.assertEqual(network.name, 'Network 5')\n self.assertEqual(network.address, '192.168.0.0')\n self.assertEqual(network.size, '256')\n self.assertEqual(network.extra['public'], 'YES')\n network = networks[1]\n self.assertEqual(network.id, '15')\n self.assertEqual(network.name, 'Network 15')\n self.assertEqual(network.address, '192.168.1.0')\n self.assertEqual(network.size, '256')\n self.assertEqual(network.extra['public'], 'NO')\n", "method_code": " def ex_list_networks(self, location=None):\n \"\"\"\n List virtual networks on a provider.\n \n @type location: L{NodeLocation}\n @param location: Location from which to request a list of virtual\n networks. (optional)\n \n @return: List of virtual networks available to be connected to a\n compute node.\n @rtype: C{list} of L{OpenNebulaNetwork}\n \"\"\"\n return self._to_networks(self.connection.request('/network').object)\n ", "context": "class OpenNebulaNodeDriver(NodeDriver):\n def ex_list_networks(self, location=None): ...\n def __new__(cls, key, secret=None, api_version=DEFAULT_API_VERSION, **kwargs): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def ex_node_action(self, node, action): ...\n def _to_images(self, object): ...\n def _to_image(self, image): ...\n def _to_networks(self, object): ...\n def _to_network(self, element): ...\n def _to_nodes(self, object): ...\n def _to_node(self, compute): ...\n def _extract_networks(self, compute): ...\n def _extract_images(self, compute): ...\n\n connectionCls = OpenNebulaConnection\n name = 'OpenNebula'\n website = 'http://opennebula.org/'\n type = Provider.OPENNEBULA\n NODE_STATE_MAP = {'INIT': NodeState.PENDING, 'PENDING': NodeState.PENDING, 'HOLD': NodeState.PENDING, 'ACTIVE': NodeState.RUNNING, 'STOPPED': NodeState.TERMINATED, 'SUSPENDED': NodeState.PENDING, 'DONE': NodeState.TERMINATED, 'FAILED': NodeState.TERMINATED}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_list_networks", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000696.py"} {"focal_file": "libcloud/compute/drivers/opennebula.py", "focal_class": null, "focal_method": "ex_node_action", "tests": "import unittest\n\nclass Test_ex_node_action(unittest.TestCase):\n def test_ex_node_action(self):\n \"\"\"\n Test ex_node_action functionality.\n \"\"\"\n node = Node(5, None, None, None, None, self.driver)\n ret = self.driver.ex_node_action(node, ACTION.STOP)\n self.assertTrue(ret)\n", "method_code": " def ex_node_action(self, node, action):\n \"\"\"\n Build action representation and instruct node to commit action.\n \n Build action representation from the compute node ID, and the\n action which should be carried out on that compute node. Then\n instruct the node to carry out that action.\n \n @param node: Compute node instance.\n @type node: L{Node}\n \n @param action: Action to be carried out on the compute node.\n @type action: C{str}\n \n @return: False if an HTTP Bad Request is received, else, True is\n returned.\n @rtype: C{bool}\n \"\"\"\n compute_node_id = str(node.id)\n compute = ET.Element('COMPUTE')\n compute_id = ET.SubElement(compute, 'ID')\n compute_id.text = compute_node_id\n state = ET.SubElement(compute, 'STATE')\n state.text = action\n xml = ET.tostring(compute)\n url = '/compute/%s' % compute_node_id\n resp = self.connection.request(url, method='PUT', data=xml)\n if resp.status == httplib.BAD_REQUEST:\n return False\n else:\n return True\n ", "context": "class OpenNebulaNodeDriver(NodeDriver):\n def ex_node_action(self, node, action): ...\n def __new__(cls, key, secret=None, api_version=DEFAULT_API_VERSION, **kwargs): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def ex_list_networks(self, location=None): ...\n def _to_images(self, object): ...\n def _to_image(self, image): ...\n def _to_networks(self, object): ...\n def _to_network(self, element): ...\n def _to_nodes(self, object): ...\n def _to_node(self, compute): ...\n def _extract_networks(self, compute): ...\n def _extract_images(self, compute): ...\n\n connectionCls = OpenNebulaConnection\n name = 'OpenNebula'\n website = 'http://opennebula.org/'\n type = Provider.OPENNEBULA\n NODE_STATE_MAP = {'INIT': NodeState.PENDING, 'PENDING': NodeState.PENDING, 'HOLD': NodeState.PENDING, 'ACTIVE': NodeState.RUNNING, 'STOPPED': NodeState.TERMINATED, 'SUSPENDED': NodeState.PENDING, 'DONE': NodeState.TERMINATED, 'FAILED': NodeState.TERMINATED}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_node_action", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/compute/drivers/opennebula.py", "focal_class": null, "focal_method": "ex_node_set_save_name", "tests": "import unittest\n\nclass Test_ex_node_set_save_name(unittest.TestCase):\n def test_ex_node_set_save_name(self):\n \"\"\"\n Test ex_node_action functionality.\n \"\"\"\n image = NodeImage(id=5, name='Ubuntu 9.04 LAMP', driver=self.driver)\n node = Node(5, None, None, None, None, self.driver, image=image)\n ret = self.driver.ex_node_set_save_name(node, 'test')\n self.assertTrue(ret)\n", "method_code": " def ex_node_set_save_name(self, node, name):\n \"\"\"\n Build action representation and instruct node to commit action.\n \n Build action representation from the compute node ID, the disk image\n which will be saved, and the name under which the image will be saved\n upon shutting down the compute node.\n \n @param node: Compute node instance.\n @type node: L{Node}\n \n @param name: Name under which the image should be saved after shutting\n down the compute node.\n @type name: C{str}\n \n @return: False if an HTTP Bad Request is received, else, True is\n returned.\n @rtype: C{bool}\n \"\"\"\n compute_node_id = str(node.id)\n compute = ET.Element('COMPUTE')\n compute_id = ET.SubElement(compute, 'ID')\n compute_id.text = compute_node_id\n disk = ET.SubElement(compute, 'DISK', {'id': str(node.image.id)})\n ET.SubElement(disk, 'STORAGE', {'href': '/storage/%s' % str(node.image.id), 'name': node.image.name})\n ET.SubElement(disk, 'SAVE_AS', {'name': str(name)})\n xml = ET.tostring(compute)\n url = '/compute/%s' % compute_node_id\n resp = self.connection.request(url, method='PUT', data=xml)\n if resp.status == httplib.BAD_REQUEST:\n return False\n else:\n return True\n ", "context": "class OpenNebula_3_0_NodeDriver(OpenNebula_2_0_NodeDriver):\n def ex_node_set_save_name(self, node, name): ...\n def _to_network(self, element): ...\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_node_set_save_name", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/compute/drivers/opennebula.py", "focal_class": null, "focal_method": "reboot_node", "tests": "import unittest\n\nclass Test_reboot_node(unittest.TestCase):\n def test_reboot_node(self):\n \"\"\"\n Test reboot_node functionality.\n \"\"\"\n image = NodeImage(id=5, name='Ubuntu 9.04 LAMP', driver=self.driver)\n node = Node(5, None, None, None, None, self.driver, image=image)\n ret = self.driver.reboot_node(node)\n self.assertTrue(ret)\n", "method_code": " def reboot_node(self, node):\n return self.ex_node_action(node, ACTION.REBOOT)\n ", "context": "class OpenNebula_3_2_NodeDriver(OpenNebula_3_0_NodeDriver):\n def reboot_node(self, node): ...\n def list_sizes(self, location=None): ...\n def _to_sizes(self, object): ...\n def _get_attributes_values(self, attributes, element): ...\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_reboot_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000699.py"} {"focal_file": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "list_locations", "tests": "import unittest\n\nclass Test_list_locations(unittest.TestCase):\n def test_list_locations(self):\n locations = self.driver.list_locations()\n self.assertEqual(len(locations), 1)\n", "method_code": " def list_locations(self):\n return [NodeLocation(0, '', '', self)]\n ", "context": "class OpenStackNodeDriver(NodeDriverOpenStackDriverMixin):\n def list_locations(self): ...\n def __new__(cls, key, secret=None, secure=True, host=None, port=None, api_version=DEFAULT_API_VERSION, **kwargs): ...\n def __init__(self, *args, **kwargs): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self, location=None, ex_only_active=True): ...\n def list_sizes(self, location=None): ...\n def _ex_connection_class_kwargs(self): ...\n def ex_get_node_details(self, node_id): ...\n def ex_soft_reboot_node(self, node): ...\n def ex_hard_reboot_node(self, node): ...\n\n api_name = 'openstack'\n name = 'OpenStack'\n website = 'http://openstack.org/'\n NODE_STATE_MAP = {'BUILD': NodeState.PENDING, 'REBUILD': NodeState.PENDING, 'ACTIVE': NodeState.RUNNING, 'SUSPENDED': NodeState.TERMINATED, 'DELETED': NodeState.TERMINATED, 'QUEUE_RESIZE': NodeState.PENDING, 'PREP_RESIZE': NodeState.PENDING, 'VERIFY_RESIZE': NodeState.RUNNING, 'PASSWORD': NodeState.PENDING, 'RESCUE': NodeState.PENDING, 'REBOOT': NodeState.REBOOTING, 'HARD_REBOOT': NodeState.REBOOTING, 'SHARE_IP': NodeState.PENDING, 'SHARE_IP_NO_CONFIG': NodeState.PENDING, 'DELETE_IP': NodeState.PENDING, 'UNKNOWN': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_locations", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000700.py"} {"focal_file": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "list_nodes", "tests": "import unittest\n\nclass Test_list_nodes(unittest.TestCase):\n def test_list_nodes(self):\n nodes = self.driver.list_nodes()\n self.assertEqual(len(nodes), 2)\n node = nodes[0]\n self.assertEqual('12065', node.id)\n self.assertEqual('50.57.94.35', node.public_ips[0])\n self.assertEqual('2001:4801:7808:52:16:3eff:fe47:788a', node.public_ips[1])\n self.assertTrue('10.182.64.34' in node.private_ips)\n self.assertTrue('12.16.18.28' in node.private_ips)\n self.assertTrue('fec0:4801:7808:52:16:3eff:fe60:187d' in node.private_ips)\n self.assertEqual(node.extra.get('flavorId'), '2')\n self.assertEqual(node.extra.get('imageId'), '7')\n self.assertEqual(node.extra.get('metadata'), {})\n self.assertEqual(node.extra['updated'], '2011-10-11T00:50:04Z')\n self.assertEqual(node.extra['created'], '2011-10-11T00:51:39Z')\n", "method_code": " def list_nodes(self):\n return self._to_nodes(self.connection.request('/servers/detail').object)\n ", "context": "class OpenStackNodeDriver(NodeDriverOpenStackDriverMixin):\n def list_nodes(self): ...\n def __new__(cls, key, secret=None, secure=True, host=None, port=None, api_version=DEFAULT_API_VERSION, **kwargs): ...\n def __init__(self, *args, **kwargs): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def list_images(self, location=None, ex_only_active=True): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def _ex_connection_class_kwargs(self): ...\n def ex_get_node_details(self, node_id): ...\n def ex_soft_reboot_node(self, node): ...\n def ex_hard_reboot_node(self, node): ...\n\n api_name = 'openstack'\n name = 'OpenStack'\n website = 'http://openstack.org/'\n NODE_STATE_MAP = {'BUILD': NodeState.PENDING, 'REBUILD': NodeState.PENDING, 'ACTIVE': NodeState.RUNNING, 'SUSPENDED': NodeState.TERMINATED, 'DELETED': NodeState.TERMINATED, 'QUEUE_RESIZE': NodeState.PENDING, 'PREP_RESIZE': NodeState.PENDING, 'VERIFY_RESIZE': NodeState.RUNNING, 'PASSWORD': NodeState.PENDING, 'RESCUE': NodeState.PENDING, 'REBOOT': NodeState.REBOOTING, 'HARD_REBOOT': NodeState.REBOOTING, 'SHARE_IP': NodeState.PENDING, 'SHARE_IP_NO_CONFIG': NodeState.PENDING, 'DELETE_IP': NodeState.PENDING, 'UNKNOWN': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_nodes", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000701.py"} {"focal_file": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "list_images", "tests": "import unittest\n\nclass Test_list_images(unittest.TestCase):\n def test_list_images(self):\n images = self.driver.list_images()\n self.assertEqual(len(images), 13, 'Wrong images count')\n image = images[0]\n self.assertEqual(image.id, '13')\n self.assertEqual(image.name, 'Windows 2008 SP2 x86 (B24)')\n self.assertEqual(image.extra['updated'], '2011-08-06T18:14:02Z')\n self.assertEqual(image.extra['created'], '2011-08-06T18:13:11Z')\n self.assertEqual(image.extra['status'], 'ACTIVE')\n self.assertEqual(image.extra['metadata']['os_type'], 'windows')\n self.assertEqual(image.extra['serverId'], '52415800-8b69-11e0-9b19-734f335aa7b3')\n self.assertEqual(image.extra['minDisk'], 0)\n self.assertEqual(image.extra['minRam'], 0)\n", "method_code": " def list_images(self, location=None, ex_only_active=True):\n \"\"\"\n @inherits: L{NodeDriver.list_images}\n \n @param ex_only_active: True if list only active\n @type ex_only_active: C{bool}\n \n \"\"\"\n return self._to_images(self.connection.request('/images/detail').object, ex_only_active)\n ", "context": "class OpenStackNodeDriver(NodeDriverOpenStackDriverMixin):\n def list_images(self, location=None, ex_only_active=True): ...\n def __new__(cls, key, secret=None, secure=True, host=None, port=None, api_version=DEFAULT_API_VERSION, **kwargs): ...\n def __init__(self, *args, **kwargs): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def _ex_connection_class_kwargs(self): ...\n def ex_get_node_details(self, node_id): ...\n def ex_soft_reboot_node(self, node): ...\n def ex_hard_reboot_node(self, node): ...\n\n api_name = 'openstack'\n name = 'OpenStack'\n website = 'http://openstack.org/'\n NODE_STATE_MAP = {'BUILD': NodeState.PENDING, 'REBUILD': NodeState.PENDING, 'ACTIVE': NodeState.RUNNING, 'SUSPENDED': NodeState.TERMINATED, 'DELETED': NodeState.TERMINATED, 'QUEUE_RESIZE': NodeState.PENDING, 'PREP_RESIZE': NodeState.PENDING, 'VERIFY_RESIZE': NodeState.RUNNING, 'PASSWORD': NodeState.PENDING, 'RESCUE': NodeState.PENDING, 'REBOOT': NodeState.REBOOTING, 'HARD_REBOOT': NodeState.REBOOTING, 'SHARE_IP': NodeState.PENDING, 'SHARE_IP_NO_CONFIG': NodeState.PENDING, 'DELETE_IP': NodeState.PENDING, 'UNKNOWN': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_images", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000702.py"} {"focal_file": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "create_node", "tests": "import unittest\n\nclass Test_create_node(unittest.TestCase):\n def test_create_node(self):\n image = NodeImage(id=11, name='Ubuntu 8.10 (intrepid)', driver=self.driver)\n size = NodeSize(1, '256 slice', None, None, None, None, driver=self.driver)\n node = self.driver.create_node(name='racktest', image=image, size=size)\n self.assertEqual(node.id, '26f7fbee-8ce1-4c28-887a-bfe8e4bb10fe')\n self.assertEqual(node.name, 'racktest')\n self.assertEqual(node.extra['password'], 'racktestvJq7d3')\n self.assertEqual(node.extra['metadata']['My Server Name'], 'Apache1')\n", "method_code": " def create_node(self, **kwargs):\n \"\"\"\n Create a new node\n \n @inherits: L{NodeDriver.create_node}\n \n @keyword ex_metadata: Key/Value metadata to associate with a node\n @type ex_metadata: C{dict}\n \n @keyword ex_files: File Path => File contents to create on\n the node\n @type ex_files: C{dict}\n \n @keyword ex_shared_ip_group_id: The server is launched into\n that shared IP group\n @type ex_shared_ip_group_id: C{str}\n \"\"\"\n name = kwargs['name']\n image = kwargs['image']\n size = kwargs['size']\n attributes = {'xmlns': self.XML_NAMESPACE, 'name': name, 'imageId': str(image.id), 'flavorId': str(size.id)}\n if 'ex_shared_ip_group' in kwargs:\n warnings.warn('ex_shared_ip_group argument is deprecated. Please use ex_shared_ip_group_id')\n if 'ex_shared_ip_group_id' in kwargs:\n shared_ip_group_id = kwargs['ex_shared_ip_group_id']\n attributes['sharedIpGroupId'] = shared_ip_group_id\n server_elm = ET.Element('server', attributes)\n metadata_elm = self._metadata_to_xml(kwargs.get('ex_metadata', {}))\n if metadata_elm:\n server_elm.append(metadata_elm)\n files_elm = self._files_to_xml(kwargs.get('ex_files', {}))\n if files_elm:\n server_elm.append(files_elm)\n resp = self.connection.request('/servers', method='POST', data=ET.tostring(server_elm))\n return self._to_node(resp.object)\n ", "context": "class OpenStack_1_0_NodeDriver(OpenStackNodeDriver):\n def create_node(self, **kwargs): ...\n def __init__(self, *args, **kwargs): ...\n def _to_images(self, object, ex_only_active): ...\n def _to_image(self, element): ...\n def _change_password_or_name(self, node, name=None, password=None): ...\n def ex_set_password(self, node, password): ...\n def ex_set_server_name(self, node, name): ...\n def ex_resize(self, node, size): ...\n def ex_confirm_resize(self, node): ...\n def ex_revert_resize(self, node): ...\n def ex_rebuild(self, node_id, image_id): ...\n def ex_create_ip_group(self, group_name, node_id=None): ...\n def ex_list_ip_groups(self, details=False): ...\n def ex_delete_ip_group(self, group_id): ...\n def ex_share_ip(self, group_id, node_id, ip, configure_node=True): ...\n def ex_unshare_ip(self, node_id, ip): ...\n def ex_list_ip_addresses(self, node_id): ...\n def _metadata_to_xml(self, metadata): ...\n def _files_to_xml(self, files): ...\n def _reboot_node(self, node, reboot_type='SOFT'): ...\n def _node_action(self, node, body): ...\n def _to_nodes(self, object): ...\n def _to_node_from_obj(self, obj): ...\n def _to_node(self, el): ...\n def _to_sizes(self, object): ...\n def _to_size(self, el): ...\n def ex_limits(self): ...\n def ex_save_image(self, node, name): ...\n def ex_delete_image(self, image): ...\n def _to_shared_ip_group(self, el): ...\n def _to_ip_addresses(self, el): ...\n def _get_size_price(self, size_id): ...\n\n self._ex_force_api_version = str(kwargs.pop('ex_force_api_version', None))\n self.XML_NAMESPACE = self.connectionCls.XML_NAMESPACE\n\n connectionCls = OpenStack_1_0_Connection\n type = Provider.OPENSTACK\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000703.py"} {"focal_file": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "ex_limits", "tests": "import unittest\n\nclass Test_ex_limits(unittest.TestCase):\n def test_ex_limits(self):\n limits = self.driver.ex_limits()\n self.assertTrue('rate' in limits)\n self.assertTrue('absolute' in limits)\n", "method_code": " def ex_limits(self):\n \"\"\"\n Extra call to get account's limits, such as\n rates (for example amount of POST requests per day)\n and absolute limits like total amount of available\n RAM to be used by servers.\n \n @return: dict with keys 'rate' and 'absolute'\n @rtype: C{dict}\n \"\"\"\n \n def _to_rate(el):\n rate = {}\n for item in list(el.items()):\n rate[item[0]] = item[1]\n return rate\n \n def _to_absolute(el):\n return {el.get('name'): el.get('value')}\n limits = self.connection.request('/limits').object\n rate = [_to_rate(el) for el in findall(limits, 'rate/limit', self.XML_NAMESPACE)]\n absolute = {}\n for item in findall(limits, 'absolute/limit', self.XML_NAMESPACE):\n absolute.update(_to_absolute(item))\n return {'rate': rate, 'absolute': absolute}\n ", "context": "class OpenStack_1_0_NodeDriver(OpenStackNodeDriver):\n def ex_limits(self): ...\n def __init__(self, *args, **kwargs): ...\n def _to_images(self, object, ex_only_active): ...\n def _to_image(self, element): ...\n def _change_password_or_name(self, node, name=None, password=None): ...\n def create_node(self, **kwargs): ...\n def ex_set_password(self, node, password): ...\n def ex_set_server_name(self, node, name): ...\n def ex_resize(self, node, size): ...\n def ex_confirm_resize(self, node): ...\n def ex_revert_resize(self, node): ...\n def ex_rebuild(self, node_id, image_id): ...\n def ex_create_ip_group(self, group_name, node_id=None): ...\n def ex_list_ip_groups(self, details=False): ...\n def ex_delete_ip_group(self, group_id): ...\n def ex_share_ip(self, group_id, node_id, ip, configure_node=True): ...\n def ex_unshare_ip(self, node_id, ip): ...\n def ex_list_ip_addresses(self, node_id): ...\n def _metadata_to_xml(self, metadata): ...\n def _files_to_xml(self, files): ...\n def _reboot_node(self, node, reboot_type='SOFT'): ...\n def _node_action(self, node, body): ...\n def _to_nodes(self, object): ...\n def _to_node_from_obj(self, obj): ...\n def _to_node(self, el): ...\n def _to_sizes(self, object): ...\n def _to_size(self, el): ...\n def ex_save_image(self, node, name): ...\n def ex_delete_image(self, image): ...\n def _to_shared_ip_group(self, el): ...\n def _to_ip_addresses(self, el): ...\n def _get_size_price(self, size_id): ...\n\n self._ex_force_api_version = str(kwargs.pop('ex_force_api_version', None))\n self.XML_NAMESPACE = self.connectionCls.XML_NAMESPACE\n\n connectionCls = OpenStack_1_0_Connection\n type = Provider.OPENSTACK\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_limits", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000704.py"} {"focal_file": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "ex_save_image", "tests": "import unittest\n\nclass Test_ex_save_image(unittest.TestCase):\n def test_ex_save_image(self):\n image = self.driver.ex_save_image(self.node, 'new_image')\n self.assertEqual(image.name, 'new_image')\n self.assertEqual(image.id, '4949f9ee-2421-4c81-8b49-13119446008b')\n", "method_code": " def ex_save_image(self, node, name):\n \"\"\"Create an image for node.\n \n @param node: node to use as a base for image\n @type node: L{Node}\n \n @param name: name for new image\n @type name: C{str}\n \n @rtype: L{NodeImage}\n \"\"\"\n image_elm = ET.Element('image', {'xmlns': self.XML_NAMESPACE, 'name': name, 'serverId': node.id})\n return self._to_image(self.connection.request('/images', method='POST', data=ET.tostring(image_elm)).object)\n ", "context": "class OpenStack_1_0_NodeDriver(OpenStackNodeDriver):\n def ex_save_image(self, node, name): ...\n def __init__(self, *args, **kwargs): ...\n def _to_images(self, object, ex_only_active): ...\n def _to_image(self, element): ...\n def _change_password_or_name(self, node, name=None, password=None): ...\n def create_node(self, **kwargs): ...\n def ex_set_password(self, node, password): ...\n def ex_set_server_name(self, node, name): ...\n def ex_resize(self, node, size): ...\n def ex_confirm_resize(self, node): ...\n def ex_revert_resize(self, node): ...\n def ex_rebuild(self, node_id, image_id): ...\n def ex_create_ip_group(self, group_name, node_id=None): ...\n def ex_list_ip_groups(self, details=False): ...\n def ex_delete_ip_group(self, group_id): ...\n def ex_share_ip(self, group_id, node_id, ip, configure_node=True): ...\n def ex_unshare_ip(self, node_id, ip): ...\n def ex_list_ip_addresses(self, node_id): ...\n def _metadata_to_xml(self, metadata): ...\n def _files_to_xml(self, files): ...\n def _reboot_node(self, node, reboot_type='SOFT'): ...\n def _node_action(self, node, body): ...\n def _to_nodes(self, object): ...\n def _to_node_from_obj(self, obj): ...\n def _to_node(self, el): ...\n def _to_sizes(self, object): ...\n def _to_size(self, el): ...\n def ex_limits(self): ...\n def ex_delete_image(self, image): ...\n def _to_shared_ip_group(self, el): ...\n def _to_ip_addresses(self, el): ...\n def _get_size_price(self, size_id): ...\n\n self._ex_force_api_version = str(kwargs.pop('ex_force_api_version', None))\n self.XML_NAMESPACE = self.connectionCls.XML_NAMESPACE\n\n connectionCls = OpenStack_1_0_Connection\n type = Provider.OPENSTACK\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_save_image", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000705.py"} {"focal_file": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "ex_delete_image", "tests": "import unittest\n\nclass Test_ex_delete_image(unittest.TestCase):\n def test_ex_delete_image(self):\n image = NodeImage(id='26365521-8c62-11f9-2c33-283d153ecc3a', name='My Backup', driver=self.driver)\n result = self.driver.ex_delete_image(image)\n self.assertTrue(result)\n", "method_code": " def ex_delete_image(self, image):\n \"\"\"Delete an image for node.\n \n @param image: the image to be deleted\n @type image: L{NodeImage}\n \n @rtype: C{bool}\n \"\"\"\n uri = '/images/%s' % image.id\n resp = self.connection.request(uri, method='DELETE')\n return resp.status == httplib.NO_CONTENT\n ", "context": "class OpenStack_1_0_NodeDriver(OpenStackNodeDriver):\n def ex_delete_image(self, image): ...\n def __init__(self, *args, **kwargs): ...\n def _to_images(self, object, ex_only_active): ...\n def _to_image(self, element): ...\n def _change_password_or_name(self, node, name=None, password=None): ...\n def create_node(self, **kwargs): ...\n def ex_set_password(self, node, password): ...\n def ex_set_server_name(self, node, name): ...\n def ex_resize(self, node, size): ...\n def ex_confirm_resize(self, node): ...\n def ex_revert_resize(self, node): ...\n def ex_rebuild(self, node_id, image_id): ...\n def ex_create_ip_group(self, group_name, node_id=None): ...\n def ex_list_ip_groups(self, details=False): ...\n def ex_delete_ip_group(self, group_id): ...\n def ex_share_ip(self, group_id, node_id, ip, configure_node=True): ...\n def ex_unshare_ip(self, node_id, ip): ...\n def ex_list_ip_addresses(self, node_id): ...\n def _metadata_to_xml(self, metadata): ...\n def _files_to_xml(self, files): ...\n def _reboot_node(self, node, reboot_type='SOFT'): ...\n def _node_action(self, node, body): ...\n def _to_nodes(self, object): ...\n def _to_node_from_obj(self, obj): ...\n def _to_node(self, el): ...\n def _to_sizes(self, object): ...\n def _to_size(self, el): ...\n def ex_limits(self): ...\n def ex_save_image(self, node, name): ...\n def _to_shared_ip_group(self, el): ...\n def _to_ip_addresses(self, el): ...\n def _get_size_price(self, size_id): ...\n\n self._ex_force_api_version = str(kwargs.pop('ex_force_api_version', None))\n self.XML_NAMESPACE = self.connectionCls.XML_NAMESPACE\n\n connectionCls = OpenStack_1_0_Connection\n type = Provider.OPENSTACK\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_delete_image", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000706.py"} {"focal_file": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "ex_list_ip_addresses", "tests": "import unittest\n\nclass Test_ex_list_ip_addresses(unittest.TestCase):\n def test_ex_list_ip_addresses(self):\n ret = self.driver.ex_list_ip_addresses(node_id=72258)\n self.assertEquals(2, len(ret.public_addresses))\n self.assertTrue('67.23.10.131' in ret.public_addresses)\n self.assertTrue('67.23.10.132' in ret.public_addresses)\n self.assertEquals(1, len(ret.private_addresses))\n self.assertTrue('10.176.42.16' in ret.private_addresses)\n", "method_code": " def ex_list_ip_addresses(self, node_id):\n \"\"\"\n List all server addresses.\n \n @param node_id: ID of the node which should be used\n @type node_id: C{str}\n \n @rtype: C{bool}\n \"\"\"\n if isinstance(node_id, Node):\n node_id = node_id.id\n uri = '/servers/%s/ips' % node_id\n resp = self.connection.request(uri, method='GET')\n return self._to_ip_addresses(resp.object)\n ", "context": "class OpenStack_1_0_NodeDriver(OpenStackNodeDriver):\n def ex_list_ip_addresses(self, node_id): ...\n def __init__(self, *args, **kwargs): ...\n def _to_images(self, object, ex_only_active): ...\n def _to_image(self, element): ...\n def _change_password_or_name(self, node, name=None, password=None): ...\n def create_node(self, **kwargs): ...\n def ex_set_password(self, node, password): ...\n def ex_set_server_name(self, node, name): ...\n def ex_resize(self, node, size): ...\n def ex_confirm_resize(self, node): ...\n def ex_revert_resize(self, node): ...\n def ex_rebuild(self, node_id, image_id): ...\n def ex_create_ip_group(self, group_name, node_id=None): ...\n def ex_list_ip_groups(self, details=False): ...\n def ex_delete_ip_group(self, group_id): ...\n def ex_share_ip(self, group_id, node_id, ip, configure_node=True): ...\n def ex_unshare_ip(self, node_id, ip): ...\n def _metadata_to_xml(self, metadata): ...\n def _files_to_xml(self, files): ...\n def _reboot_node(self, node, reboot_type='SOFT'): ...\n def _node_action(self, node, body): ...\n def _to_nodes(self, object): ...\n def _to_node_from_obj(self, obj): ...\n def _to_node(self, el): ...\n def _to_sizes(self, object): ...\n def _to_size(self, el): ...\n def ex_limits(self): ...\n def ex_save_image(self, node, name): ...\n def ex_delete_image(self, image): ...\n def _to_shared_ip_group(self, el): ...\n def _to_ip_addresses(self, el): ...\n def _get_size_price(self, size_id): ...\n\n self._ex_force_api_version = str(kwargs.pop('ex_force_api_version', None))\n self.XML_NAMESPACE = self.connectionCls.XML_NAMESPACE\n\n connectionCls = OpenStack_1_0_Connection\n type = Provider.OPENSTACK\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_list_ip_addresses", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000707.py"} {"focal_file": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "ex_list_ip_groups", "tests": "import unittest\n\nclass Test_ex_list_ip_groups(unittest.TestCase):\n def test_ex_list_ip_groups(self):\n ret = self.driver.ex_list_ip_groups()\n self.assertEquals(2, len(ret))\n self.assertEquals('1234', ret[0].id)\n self.assertEquals('Shared IP Group 1', ret[0].name)\n self.assertEquals('5678', ret[1].id)\n self.assertEquals('Shared IP Group 2', ret[1].name)\n self.assertTrue(ret[0].servers is None)\n\n def test_ex_list_ip_groups_detail(self):\n ret = self.driver.ex_list_ip_groups(details=True)\n self.assertEquals(2, len(ret))\n self.assertEquals('1234', ret[0].id)\n self.assertEquals('Shared IP Group 1', ret[0].name)\n self.assertEquals(2, len(ret[0].servers))\n self.assertEquals('422', ret[0].servers[0])\n self.assertEquals('3445', ret[0].servers[1])\n self.assertEquals('5678', ret[1].id)\n self.assertEquals('Shared IP Group 2', ret[1].name)\n self.assertEquals(3, len(ret[1].servers))\n self.assertEquals('23203', ret[1].servers[0])\n self.assertEquals('2456', ret[1].servers[1])\n self.assertEquals('9891', ret[1].servers[2])\n", "method_code": " def ex_list_ip_groups(self, details=False):\n \"\"\"\n Lists IDs and names for shared IP groups.\n If details lists all details for shared IP groups.\n \n @param details: True if details is required\n @type details: C{bool}\n \n @rtype: C{list} of L{OpenStack_1_0_SharedIpGroup}\n \"\"\"\n uri = '/shared_ip_groups/detail' if details else '/shared_ip_groups'\n resp = self.connection.request(uri, method='GET')\n groups = findall(resp.object, 'sharedIpGroup', self.XML_NAMESPACE)\n return [self._to_shared_ip_group(el) for el in groups]\n ", "context": "class OpenStack_1_0_NodeDriver(OpenStackNodeDriver):\n def ex_list_ip_groups(self, details=False): ...\n def __init__(self, *args, **kwargs): ...\n def _to_images(self, object, ex_only_active): ...\n def _to_image(self, element): ...\n def _change_password_or_name(self, node, name=None, password=None): ...\n def create_node(self, **kwargs): ...\n def ex_set_password(self, node, password): ...\n def ex_set_server_name(self, node, name): ...\n def ex_resize(self, node, size): ...\n def ex_confirm_resize(self, node): ...\n def ex_revert_resize(self, node): ...\n def ex_rebuild(self, node_id, image_id): ...\n def ex_create_ip_group(self, group_name, node_id=None): ...\n def ex_delete_ip_group(self, group_id): ...\n def ex_share_ip(self, group_id, node_id, ip, configure_node=True): ...\n def ex_unshare_ip(self, node_id, ip): ...\n def ex_list_ip_addresses(self, node_id): ...\n def _metadata_to_xml(self, metadata): ...\n def _files_to_xml(self, files): ...\n def _reboot_node(self, node, reboot_type='SOFT'): ...\n def _node_action(self, node, body): ...\n def _to_nodes(self, object): ...\n def _to_node_from_obj(self, obj): ...\n def _to_node(self, el): ...\n def _to_sizes(self, object): ...\n def _to_size(self, el): ...\n def ex_limits(self): ...\n def ex_save_image(self, node, name): ...\n def ex_delete_image(self, image): ...\n def _to_shared_ip_group(self, el): ...\n def _to_ip_addresses(self, el): ...\n def _get_size_price(self, size_id): ...\n\n self._ex_force_api_version = str(kwargs.pop('ex_force_api_version', None))\n self.XML_NAMESPACE = self.connectionCls.XML_NAMESPACE\n\n connectionCls = OpenStack_1_0_Connection\n type = Provider.OPENSTACK\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_list_ip_groups", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000708.py"} {"focal_file": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "ex_create_ip_group", "tests": "import unittest\n\nclass Test_ex_create_ip_group(unittest.TestCase):\n def test_ex_create_ip_group(self):\n ret = self.driver.ex_create_ip_group('Shared IP Group 1', '5467')\n self.assertEquals('1234', ret.id)\n self.assertEquals('Shared IP Group 1', ret.name)\n self.assertEquals(1, len(ret.servers))\n self.assertEquals('422', ret.servers[0])\n", "method_code": " def ex_create_ip_group(self, group_name, node_id=None):\n \"\"\"\n Creates a shared IP group.\n \n @param group_name: group name which should be used\n @type group_name: C{str}\n \n @param node_id: ID of the node which should be used\n @type node_id: C{str}\n \n @rtype: C{bool}\n \"\"\"\n if isinstance(node_id, Node):\n node_id = node_id.id\n group_elm = ET.Element('sharedIpGroup', {'xmlns': self.XML_NAMESPACE, 'name': group_name})\n if node_id:\n ET.SubElement(group_elm, 'server', {'id': node_id})\n resp = self.connection.request('/shared_ip_groups', method='POST', data=ET.tostring(group_elm))\n return self._to_shared_ip_group(resp.object)\n ", "context": "class OpenStack_1_0_NodeDriver(OpenStackNodeDriver):\n def ex_create_ip_group(self, group_name, node_id=None): ...\n def __init__(self, *args, **kwargs): ...\n def _to_images(self, object, ex_only_active): ...\n def _to_image(self, element): ...\n def _change_password_or_name(self, node, name=None, password=None): ...\n def create_node(self, **kwargs): ...\n def ex_set_password(self, node, password): ...\n def ex_set_server_name(self, node, name): ...\n def ex_resize(self, node, size): ...\n def ex_confirm_resize(self, node): ...\n def ex_revert_resize(self, node): ...\n def ex_rebuild(self, node_id, image_id): ...\n def ex_list_ip_groups(self, details=False): ...\n def ex_delete_ip_group(self, group_id): ...\n def ex_share_ip(self, group_id, node_id, ip, configure_node=True): ...\n def ex_unshare_ip(self, node_id, ip): ...\n def ex_list_ip_addresses(self, node_id): ...\n def _metadata_to_xml(self, metadata): ...\n def _files_to_xml(self, files): ...\n def _reboot_node(self, node, reboot_type='SOFT'): ...\n def _node_action(self, node, body): ...\n def _to_nodes(self, object): ...\n def _to_node_from_obj(self, obj): ...\n def _to_node(self, el): ...\n def _to_sizes(self, object): ...\n def _to_size(self, el): ...\n def ex_limits(self): ...\n def ex_save_image(self, node, name): ...\n def ex_delete_image(self, image): ...\n def _to_shared_ip_group(self, el): ...\n def _to_ip_addresses(self, el): ...\n def _get_size_price(self, size_id): ...\n\n self._ex_force_api_version = str(kwargs.pop('ex_force_api_version', None))\n self.XML_NAMESPACE = self.connectionCls.XML_NAMESPACE\n\n connectionCls = OpenStack_1_0_Connection\n type = Provider.OPENSTACK\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_create_ip_group", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000709.py"} {"focal_file": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "ex_delete_ip_group", "tests": "import unittest\n\nclass Test_ex_delete_ip_group(unittest.TestCase):\n def test_ex_delete_ip_group(self):\n ret = self.driver.ex_delete_ip_group('5467')\n self.assertEquals(True, ret)\n", "method_code": " def ex_delete_ip_group(self, group_id):\n \"\"\"\n Deletes the specified shared IP group.\n \n @param group_id: group id which should be used\n @type group_id: C{str}\n \n @rtype: C{bool}\n \"\"\"\n uri = '/shared_ip_groups/%s' % group_id\n resp = self.connection.request(uri, method='DELETE')\n return resp.status == httplib.NO_CONTENT\n ", "context": "class OpenStack_1_0_NodeDriver(OpenStackNodeDriver):\n def ex_delete_ip_group(self, group_id): ...\n def __init__(self, *args, **kwargs): ...\n def _to_images(self, object, ex_only_active): ...\n def _to_image(self, element): ...\n def _change_password_or_name(self, node, name=None, password=None): ...\n def create_node(self, **kwargs): ...\n def ex_set_password(self, node, password): ...\n def ex_set_server_name(self, node, name): ...\n def ex_resize(self, node, size): ...\n def ex_confirm_resize(self, node): ...\n def ex_revert_resize(self, node): ...\n def ex_rebuild(self, node_id, image_id): ...\n def ex_create_ip_group(self, group_name, node_id=None): ...\n def ex_list_ip_groups(self, details=False): ...\n def ex_share_ip(self, group_id, node_id, ip, configure_node=True): ...\n def ex_unshare_ip(self, node_id, ip): ...\n def ex_list_ip_addresses(self, node_id): ...\n def _metadata_to_xml(self, metadata): ...\n def _files_to_xml(self, files): ...\n def _reboot_node(self, node, reboot_type='SOFT'): ...\n def _node_action(self, node, body): ...\n def _to_nodes(self, object): ...\n def _to_node_from_obj(self, obj): ...\n def _to_node(self, el): ...\n def _to_sizes(self, object): ...\n def _to_size(self, el): ...\n def ex_limits(self): ...\n def ex_save_image(self, node, name): ...\n def ex_delete_image(self, image): ...\n def _to_shared_ip_group(self, el): ...\n def _to_ip_addresses(self, el): ...\n def _get_size_price(self, size_id): ...\n\n self._ex_force_api_version = str(kwargs.pop('ex_force_api_version', None))\n self.XML_NAMESPACE = self.connectionCls.XML_NAMESPACE\n\n connectionCls = OpenStack_1_0_Connection\n type = Provider.OPENSTACK\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_delete_ip_group", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 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": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "ex_share_ip", "tests": "import unittest\n\nclass Test_ex_share_ip(unittest.TestCase):\n def test_ex_share_ip(self):\n ret = self.driver.ex_share_ip('1234', '3445', '67.23.21.133')\n self.assertEquals(True, ret)\n", "method_code": " def ex_share_ip(self, group_id, node_id, ip, configure_node=True):\n \"\"\"\n Shares an IP address to the specified server.\n \n @param group_id: group id which should be used\n @type group_id: C{str}\n \n @param node_id: ID of the node which should be used\n @type node_id: C{str}\n \n @param ip: ip which should be used\n @type ip: C{str}\n \n @param configure_node: configure node\n @type configure_node: C{bool}\n \n @rtype: C{bool}\n \"\"\"\n if isinstance(node_id, Node):\n node_id = node_id.id\n if configure_node:\n str_configure = 'true'\n else:\n str_configure = 'false'\n elm = ET.Element('shareIp', {'xmlns': self.XML_NAMESPACE, 'sharedIpGroupId': group_id, 'configureServer': str_configure})\n uri = '/servers/%s/ips/public/%s' % (node_id, ip)\n resp = self.connection.request(uri, method='PUT', data=ET.tostring(elm))\n return resp.status == httplib.ACCEPTED\n ", "context": "class OpenStack_1_0_NodeDriver(OpenStackNodeDriver):\n def ex_share_ip(self, group_id, node_id, ip, configure_node=True): ...\n def __init__(self, *args, **kwargs): ...\n def _to_images(self, object, ex_only_active): ...\n def _to_image(self, element): ...\n def _change_password_or_name(self, node, name=None, password=None): ...\n def create_node(self, **kwargs): ...\n def ex_set_password(self, node, password): ...\n def ex_set_server_name(self, node, name): ...\n def ex_resize(self, node, size): ...\n def ex_confirm_resize(self, node): ...\n def ex_revert_resize(self, node): ...\n def ex_rebuild(self, node_id, image_id): ...\n def ex_create_ip_group(self, group_name, node_id=None): ...\n def ex_list_ip_groups(self, details=False): ...\n def ex_delete_ip_group(self, group_id): ...\n def ex_unshare_ip(self, node_id, ip): ...\n def ex_list_ip_addresses(self, node_id): ...\n def _metadata_to_xml(self, metadata): ...\n def _files_to_xml(self, files): ...\n def _reboot_node(self, node, reboot_type='SOFT'): ...\n def _node_action(self, node, body): ...\n def _to_nodes(self, object): ...\n def _to_node_from_obj(self, obj): ...\n def _to_node(self, el): ...\n def _to_sizes(self, object): ...\n def _to_size(self, el): ...\n def ex_limits(self): ...\n def ex_save_image(self, node, name): ...\n def ex_delete_image(self, image): ...\n def _to_shared_ip_group(self, el): ...\n def _to_ip_addresses(self, el): ...\n def _get_size_price(self, size_id): ...\n\n self._ex_force_api_version = str(kwargs.pop('ex_force_api_version', None))\n self.XML_NAMESPACE = self.connectionCls.XML_NAMESPACE\n\n connectionCls = OpenStack_1_0_Connection\n type = Provider.OPENSTACK\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_share_ip", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000711.py"} {"focal_file": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "ex_unshare_ip", "tests": "import unittest\n\nclass Test_ex_unshare_ip(unittest.TestCase):\n def test_ex_unshare_ip(self):\n ret = self.driver.ex_unshare_ip('3445', '67.23.21.133')\n self.assertEquals(True, ret)\n", "method_code": " def ex_unshare_ip(self, node_id, ip):\n \"\"\"\n Removes a shared IP address from the specified server.\n \n @param node_id: ID of the node which should be used\n @type node_id: C{str}\n \n @param ip: ip which should be used\n @type ip: C{str}\n \n @rtype: C{bool}\n \"\"\"\n if isinstance(node_id, Node):\n node_id = node_id.id\n uri = '/servers/%s/ips/public/%s' % (node_id, ip)\n resp = self.connection.request(uri, method='DELETE')\n return resp.status == httplib.ACCEPTED\n ", "context": "class OpenStack_1_0_NodeDriver(OpenStackNodeDriver):\n def ex_unshare_ip(self, node_id, ip): ...\n def __init__(self, *args, **kwargs): ...\n def _to_images(self, object, ex_only_active): ...\n def _to_image(self, element): ...\n def _change_password_or_name(self, node, name=None, password=None): ...\n def create_node(self, **kwargs): ...\n def ex_set_password(self, node, password): ...\n def ex_set_server_name(self, node, name): ...\n def ex_resize(self, node, size): ...\n def ex_confirm_resize(self, node): ...\n def ex_revert_resize(self, node): ...\n def ex_rebuild(self, node_id, image_id): ...\n def ex_create_ip_group(self, group_name, node_id=None): ...\n def ex_list_ip_groups(self, details=False): ...\n def ex_delete_ip_group(self, group_id): ...\n def ex_share_ip(self, group_id, node_id, ip, configure_node=True): ...\n def ex_list_ip_addresses(self, node_id): ...\n def _metadata_to_xml(self, metadata): ...\n def _files_to_xml(self, files): ...\n def _reboot_node(self, node, reboot_type='SOFT'): ...\n def _node_action(self, node, body): ...\n def _to_nodes(self, object): ...\n def _to_node_from_obj(self, obj): ...\n def _to_node(self, el): ...\n def _to_sizes(self, object): ...\n def _to_size(self, el): ...\n def ex_limits(self): ...\n def ex_save_image(self, node, name): ...\n def ex_delete_image(self, image): ...\n def _to_shared_ip_group(self, el): ...\n def _to_ip_addresses(self, el): ...\n def _get_size_price(self, size_id): ...\n\n self._ex_force_api_version = str(kwargs.pop('ex_force_api_version', None))\n self.XML_NAMESPACE = self.connectionCls.XML_NAMESPACE\n\n connectionCls = OpenStack_1_0_Connection\n type = Provider.OPENSTACK\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_unshare_ip", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 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": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "ex_resize", "tests": "import unittest\n\nclass Test_ex_resize(unittest.TestCase):\n def test_ex_resize(self):\n size = NodeSize(1, '256 slice', None, None, None, None, driver=self.driver)\n try:\n self.driver.ex_resize(self.node, size)\n except Exception:\n e = sys.exc_info()[1]\n self.fail('An error was raised: ' + repr(e))\n", "method_code": " def ex_resize(self, node, size):\n \"\"\"\n Change an existing server flavor / scale the server up or down.\n \n @param node: node to resize.\n @type node: L{Node}\n \n @param size: new size.\n @type size: L{NodeSize}\n \n @rtype: C{bool}\n \"\"\"\n elm = ET.Element('resize', {'xmlns': self.XML_NAMESPACE, 'flavorId': str(size.id)})\n resp = self.connection.request('/servers/%s/action' % node.id, method='POST', data=ET.tostring(elm))\n return resp.status == httplib.ACCEPTED\n ", "context": "class OpenStack_1_0_NodeDriver(OpenStackNodeDriver):\n def ex_resize(self, node, size): ...\n def __init__(self, *args, **kwargs): ...\n def _to_images(self, object, ex_only_active): ...\n def _to_image(self, element): ...\n def _change_password_or_name(self, node, name=None, password=None): ...\n def create_node(self, **kwargs): ...\n def ex_set_password(self, node, password): ...\n def ex_set_server_name(self, node, name): ...\n def ex_confirm_resize(self, node): ...\n def ex_revert_resize(self, node): ...\n def ex_rebuild(self, node_id, image_id): ...\n def ex_create_ip_group(self, group_name, node_id=None): ...\n def ex_list_ip_groups(self, details=False): ...\n def ex_delete_ip_group(self, group_id): ...\n def ex_share_ip(self, group_id, node_id, ip, configure_node=True): ...\n def ex_unshare_ip(self, node_id, ip): ...\n def ex_list_ip_addresses(self, node_id): ...\n def _metadata_to_xml(self, metadata): ...\n def _files_to_xml(self, files): ...\n def _reboot_node(self, node, reboot_type='SOFT'): ...\n def _node_action(self, node, body): ...\n def _to_nodes(self, object): ...\n def _to_node_from_obj(self, obj): ...\n def _to_node(self, el): ...\n def _to_sizes(self, object): ...\n def _to_size(self, el): ...\n def ex_limits(self): ...\n def ex_save_image(self, node, name): ...\n def ex_delete_image(self, image): ...\n def _to_shared_ip_group(self, el): ...\n def _to_ip_addresses(self, el): ...\n def _get_size_price(self, size_id): ...\n\n self._ex_force_api_version = str(kwargs.pop('ex_force_api_version', None))\n self.XML_NAMESPACE = self.connectionCls.XML_NAMESPACE\n\n connectionCls = OpenStack_1_0_Connection\n type = Provider.OPENSTACK\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_resize", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000713.py"} {"focal_file": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "ex_confirm_resize", "tests": "import unittest\n\nclass Test_ex_confirm_resize(unittest.TestCase):\n def test_ex_confirm_resize(self):\n try:\n self.driver.ex_confirm_resize(self.node)\n except Exception:\n e = sys.exc_info()[1]\n self.fail('An error was raised: ' + repr(e))\n", "method_code": " def ex_confirm_resize(self, node):\n \"\"\"\n Confirm a resize request which is currently in progress. If a resize\n request is not explicitly confirmed or reverted it's automatically\n confirmed after 24 hours.\n \n For more info refer to the API documentation: http://goo.gl/zjFI1\n \n @param node: node for which the resize request will be confirmed.\n @type node: L{Node}\n \n @rtype: C{bool}\n \"\"\"\n elm = ET.Element('confirmResize', {'xmlns': self.XML_NAMESPACE})\n resp = self.connection.request('/servers/%s/action' % node.id, method='POST', data=ET.tostring(elm))\n return resp.status == httplib.NO_CONTENT\n ", "context": "class OpenStack_1_0_NodeDriver(OpenStackNodeDriver):\n def ex_confirm_resize(self, node): ...\n def __init__(self, *args, **kwargs): ...\n def _to_images(self, object, ex_only_active): ...\n def _to_image(self, element): ...\n def _change_password_or_name(self, node, name=None, password=None): ...\n def create_node(self, **kwargs): ...\n def ex_set_password(self, node, password): ...\n def ex_set_server_name(self, node, name): ...\n def ex_resize(self, node, size): ...\n def ex_revert_resize(self, node): ...\n def ex_rebuild(self, node_id, image_id): ...\n def ex_create_ip_group(self, group_name, node_id=None): ...\n def ex_list_ip_groups(self, details=False): ...\n def ex_delete_ip_group(self, group_id): ...\n def ex_share_ip(self, group_id, node_id, ip, configure_node=True): ...\n def ex_unshare_ip(self, node_id, ip): ...\n def ex_list_ip_addresses(self, node_id): ...\n def _metadata_to_xml(self, metadata): ...\n def _files_to_xml(self, files): ...\n def _reboot_node(self, node, reboot_type='SOFT'): ...\n def _node_action(self, node, body): ...\n def _to_nodes(self, object): ...\n def _to_node_from_obj(self, obj): ...\n def _to_node(self, el): ...\n def _to_sizes(self, object): ...\n def _to_size(self, el): ...\n def ex_limits(self): ...\n def ex_save_image(self, node, name): ...\n def ex_delete_image(self, image): ...\n def _to_shared_ip_group(self, el): ...\n def _to_ip_addresses(self, el): ...\n def _get_size_price(self, size_id): ...\n\n self._ex_force_api_version = str(kwargs.pop('ex_force_api_version', None))\n self.XML_NAMESPACE = self.connectionCls.XML_NAMESPACE\n\n connectionCls = OpenStack_1_0_Connection\n type = Provider.OPENSTACK\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_confirm_resize", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000714.py"} {"focal_file": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "ex_revert_resize", "tests": "import unittest\n\nclass Test_ex_revert_resize(unittest.TestCase):\n def test_ex_revert_resize(self):\n try:\n self.driver.ex_revert_resize(self.node)\n except Exception:\n e = sys.exc_info()[1]\n self.fail('An error was raised: ' + repr(e))\n", "method_code": " def ex_revert_resize(self, node):\n \"\"\"\n Revert a resize request which is currently in progress.\n All resizes are automatically confirmed after 24 hours if they have\n not already been confirmed explicitly or reverted.\n \n For more info refer to the API documentation: http://goo.gl/AizBu\n \n @param node: node for which the resize request will be reverted.\n @type node: L{Node}\n \n @rtype: C{bool}\n \"\"\"\n elm = ET.Element('revertResize', {'xmlns': self.XML_NAMESPACE})\n resp = self.connection.request('/servers/%s/action' % node.id, method='POST', data=ET.tostring(elm))\n return resp.status == httplib.NO_CONTENT\n ", "context": "class OpenStack_1_0_NodeDriver(OpenStackNodeDriver):\n def ex_revert_resize(self, node): ...\n def __init__(self, *args, **kwargs): ...\n def _to_images(self, object, ex_only_active): ...\n def _to_image(self, element): ...\n def _change_password_or_name(self, node, name=None, password=None): ...\n def create_node(self, **kwargs): ...\n def ex_set_password(self, node, password): ...\n def ex_set_server_name(self, node, name): ...\n def ex_resize(self, node, size): ...\n def ex_confirm_resize(self, node): ...\n def ex_rebuild(self, node_id, image_id): ...\n def ex_create_ip_group(self, group_name, node_id=None): ...\n def ex_list_ip_groups(self, details=False): ...\n def ex_delete_ip_group(self, group_id): ...\n def ex_share_ip(self, group_id, node_id, ip, configure_node=True): ...\n def ex_unshare_ip(self, node_id, ip): ...\n def ex_list_ip_addresses(self, node_id): ...\n def _metadata_to_xml(self, metadata): ...\n def _files_to_xml(self, files): ...\n def _reboot_node(self, node, reboot_type='SOFT'): ...\n def _node_action(self, node, body): ...\n def _to_nodes(self, object): ...\n def _to_node_from_obj(self, obj): ...\n def _to_node(self, el): ...\n def _to_sizes(self, object): ...\n def _to_size(self, el): ...\n def ex_limits(self): ...\n def ex_save_image(self, node, name): ...\n def ex_delete_image(self, image): ...\n def _to_shared_ip_group(self, el): ...\n def _to_ip_addresses(self, el): ...\n def _get_size_price(self, size_id): ...\n\n self._ex_force_api_version = str(kwargs.pop('ex_force_api_version', None))\n self.XML_NAMESPACE = self.connectionCls.XML_NAMESPACE\n\n connectionCls = OpenStack_1_0_Connection\n type = Provider.OPENSTACK\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_revert_resize", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000715.py"} {"focal_file": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "list_sizes", "tests": "import unittest\n\nclass Test_list_sizes(unittest.TestCase):\n def test_list_sizes(self):\n sizes = self.driver.list_sizes()\n self.assertEqual(len(sizes), 8, 'Wrong sizes count')\n for size in sizes:\n self.assertTrue(isinstance(size.price, float), 'Wrong size price type')\n self.assertEqual(sizes[0].vcpus, 8)\n", "method_code": " def list_sizes(self, location=None):\n return self._to_sizes(self.connection.request('/flavors/detail').object)\n ", "context": "class OpenStackNodeDriver(NodeDriverOpenStackDriverMixin):\n def list_sizes(self, location=None): ...\n def __new__(cls, key, secret=None, secure=True, host=None, port=None, api_version=DEFAULT_API_VERSION, **kwargs): ...\n def __init__(self, *args, **kwargs): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self, location=None, ex_only_active=True): ...\n def list_locations(self): ...\n def _ex_connection_class_kwargs(self): ...\n def ex_get_node_details(self, node_id): ...\n def ex_soft_reboot_node(self, node): ...\n def ex_hard_reboot_node(self, node): ...\n\n api_name = 'openstack'\n name = 'OpenStack'\n website = 'http://openstack.org/'\n NODE_STATE_MAP = {'BUILD': NodeState.PENDING, 'REBUILD': NodeState.PENDING, 'ACTIVE': NodeState.RUNNING, 'SUSPENDED': NodeState.TERMINATED, 'DELETED': NodeState.TERMINATED, 'QUEUE_RESIZE': NodeState.PENDING, 'PREP_RESIZE': NodeState.PENDING, 'VERIFY_RESIZE': NodeState.RUNNING, 'PASSWORD': NodeState.PENDING, 'RESCUE': NodeState.PENDING, 'REBOOT': NodeState.REBOOTING, 'HARD_REBOOT': NodeState.REBOOTING, 'SHARE_IP': NodeState.PENDING, 'SHARE_IP_NO_CONFIG': NodeState.PENDING, 'DELETE_IP': NodeState.PENDING, 'UNKNOWN': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_sizes", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000716.py"} {"focal_file": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "ex_set_password", "tests": "import unittest\n\nclass Test_ex_set_password(unittest.TestCase):\n def test_ex_set_password(self):\n try:\n self.driver.ex_set_password(self.node, 'New1&53jPass')\n except Exception:\n e = sys.exc_info()[1]\n self.fail('An error was raised: ' + repr(e))\n", "method_code": " def ex_set_password(self, node, password):\n \"\"\"\n Sets the Node's root password.\n \n This will reboot the instance to complete the operation.\n \n L{Node.extra['password']} will be set to the new value if the\n operation was successful.\n \n @param node: node to set password\n @type node: L{Node}\n \n @param password: new password.\n @type password: C{str}\n \n @rtype: C{bool}\n \"\"\"\n return self._change_password_or_name(node, password=password)\n ", "context": "class OpenStack_1_0_NodeDriver(OpenStackNodeDriver):\n def ex_set_password(self, node, password): ...\n def __init__(self, *args, **kwargs): ...\n def _to_images(self, object, ex_only_active): ...\n def _to_image(self, element): ...\n def _change_password_or_name(self, node, name=None, password=None): ...\n def create_node(self, **kwargs): ...\n def ex_set_server_name(self, node, name): ...\n def ex_resize(self, node, size): ...\n def ex_confirm_resize(self, node): ...\n def ex_revert_resize(self, node): ...\n def ex_rebuild(self, node_id, image_id): ...\n def ex_create_ip_group(self, group_name, node_id=None): ...\n def ex_list_ip_groups(self, details=False): ...\n def ex_delete_ip_group(self, group_id): ...\n def ex_share_ip(self, group_id, node_id, ip, configure_node=True): ...\n def ex_unshare_ip(self, node_id, ip): ...\n def ex_list_ip_addresses(self, node_id): ...\n def _metadata_to_xml(self, metadata): ...\n def _files_to_xml(self, files): ...\n def _reboot_node(self, node, reboot_type='SOFT'): ...\n def _node_action(self, node, body): ...\n def _to_nodes(self, object): ...\n def _to_node_from_obj(self, obj): ...\n def _to_node(self, el): ...\n def _to_sizes(self, object): ...\n def _to_size(self, el): ...\n def ex_limits(self): ...\n def ex_save_image(self, node, name): ...\n def ex_delete_image(self, image): ...\n def _to_shared_ip_group(self, el): ...\n def _to_ip_addresses(self, el): ...\n def _get_size_price(self, size_id): ...\n\n self._ex_force_api_version = str(kwargs.pop('ex_force_api_version', None))\n self.XML_NAMESPACE = self.connectionCls.XML_NAMESPACE\n\n connectionCls = OpenStack_1_0_Connection\n type = Provider.OPENSTACK\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_set_password", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000717.py"} {"focal_file": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "ex_rebuild", "tests": "import unittest\n\nclass Test_ex_rebuild(unittest.TestCase):\n def test_ex_rebuild(self):\n image = NodeImage(id=11, name='Ubuntu 8.10 (intrepid)', driver=self.driver)\n try:\n self.driver.ex_rebuild(self.node, image=image)\n except Exception:\n e = sys.exc_info()[1]\n self.fail('An error was raised: ' + repr(e))\n", "method_code": " def ex_rebuild(self, node_id, image_id):\n \"\"\"\n Rebuilds the specified server.\n \n @param node_id: ID of the node which should be used\n @type node_id: C{str}\n \n @param image_id: ID of the image which should be used\n @type image_id: C{str}\n \n @rtype: C{bool}\n \"\"\"\n if isinstance(node_id, Node):\n node_id = node_id.id\n if isinstance(image_id, NodeImage):\n image_id = image_id.id\n elm = ET.Element('rebuild', {'xmlns': self.XML_NAMESPACE, 'imageId': image_id})\n resp = self.connection.request('/servers/%s/action' % node_id, method='POST', data=ET.tostring(elm))\n return resp.status == httplib.ACCEPTED\n ", "context": "class OpenStack_1_0_NodeDriver(OpenStackNodeDriver):\n def ex_rebuild(self, node_id, image_id): ...\n def __init__(self, *args, **kwargs): ...\n def _to_images(self, object, ex_only_active): ...\n def _to_image(self, element): ...\n def _change_password_or_name(self, node, name=None, password=None): ...\n def create_node(self, **kwargs): ...\n def ex_set_password(self, node, password): ...\n def ex_set_server_name(self, node, name): ...\n def ex_resize(self, node, size): ...\n def ex_confirm_resize(self, node): ...\n def ex_revert_resize(self, node): ...\n def ex_create_ip_group(self, group_name, node_id=None): ...\n def ex_list_ip_groups(self, details=False): ...\n def ex_delete_ip_group(self, group_id): ...\n def ex_share_ip(self, group_id, node_id, ip, configure_node=True): ...\n def ex_unshare_ip(self, node_id, ip): ...\n def ex_list_ip_addresses(self, node_id): ...\n def _metadata_to_xml(self, metadata): ...\n def _files_to_xml(self, files): ...\n def _reboot_node(self, node, reboot_type='SOFT'): ...\n def _node_action(self, node, body): ...\n def _to_nodes(self, object): ...\n def _to_node_from_obj(self, obj): ...\n def _to_node(self, el): ...\n def _to_sizes(self, object): ...\n def _to_size(self, el): ...\n def ex_limits(self): ...\n def ex_save_image(self, node, name): ...\n def ex_delete_image(self, image): ...\n def _to_shared_ip_group(self, el): ...\n def _to_ip_addresses(self, el): ...\n def _get_size_price(self, size_id): ...\n\n self._ex_force_api_version = str(kwargs.pop('ex_force_api_version', None))\n self.XML_NAMESPACE = self.connectionCls.XML_NAMESPACE\n\n connectionCls = OpenStack_1_0_Connection\n type = Provider.OPENSTACK\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_rebuild", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000718.py"} {"focal_file": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "ex_set_server_name", "tests": "import unittest\n\nclass Test_ex_set_server_name(unittest.TestCase):\n def test_ex_set_server_name(self):\n old_node = Node(id='12064', name=None, state=None, public_ips=None, private_ips=None, driver=self.driver)\n new_node = self.driver.ex_set_server_name(old_node, 'Bob')\n self.assertEqual('Bob', new_node.name)\n", "method_code": " def ex_set_server_name(self, node, name):\n \"\"\"\n Sets the Node's name.\n \n This will reboot the instance to complete the operation.\n \n @param node: node to set name\n @type node: L{Node}\n \n @param name: new name\n @type name: C{str}\n \n @rtype: C{bool}\n \"\"\"\n return self._change_password_or_name(node, name=name)\n ", "context": "class OpenStack_1_0_NodeDriver(OpenStackNodeDriver):\n def ex_set_server_name(self, node, name): ...\n def __init__(self, *args, **kwargs): ...\n def _to_images(self, object, ex_only_active): ...\n def _to_image(self, element): ...\n def _change_password_or_name(self, node, name=None, password=None): ...\n def create_node(self, **kwargs): ...\n def ex_set_password(self, node, password): ...\n def ex_resize(self, node, size): ...\n def ex_confirm_resize(self, node): ...\n def ex_revert_resize(self, node): ...\n def ex_rebuild(self, node_id, image_id): ...\n def ex_create_ip_group(self, group_name, node_id=None): ...\n def ex_list_ip_groups(self, details=False): ...\n def ex_delete_ip_group(self, group_id): ...\n def ex_share_ip(self, group_id, node_id, ip, configure_node=True): ...\n def ex_unshare_ip(self, node_id, ip): ...\n def ex_list_ip_addresses(self, node_id): ...\n def _metadata_to_xml(self, metadata): ...\n def _files_to_xml(self, files): ...\n def _reboot_node(self, node, reboot_type='SOFT'): ...\n def _node_action(self, node, body): ...\n def _to_nodes(self, object): ...\n def _to_node_from_obj(self, obj): ...\n def _to_node(self, el): ...\n def _to_sizes(self, object): ...\n def _to_size(self, el): ...\n def ex_limits(self): ...\n def ex_save_image(self, node, name): ...\n def ex_delete_image(self, image): ...\n def _to_shared_ip_group(self, el): ...\n def _to_ip_addresses(self, el): ...\n def _get_size_price(self, size_id): ...\n\n self._ex_force_api_version = str(kwargs.pop('ex_force_api_version', None))\n self.XML_NAMESPACE = self.connectionCls.XML_NAMESPACE\n\n connectionCls = OpenStack_1_0_Connection\n type = Provider.OPENSTACK\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_set_server_name", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 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": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "ex_set_metadata", "tests": "import unittest\n\nclass Test_ex_set_metadata(unittest.TestCase):\n def test_ex_set_metadata(self):\n old_node = Node(id='12063', name=None, state=None, public_ips=None, private_ips=None, driver=self.driver)\n metadata = {'Image Version': '2.1', 'Server Label': 'Web Head 1'}\n returned_metadata = self.driver.ex_set_metadata(old_node, metadata)\n self.assertEqual(metadata, returned_metadata)\n", "method_code": " def ex_set_metadata(self, node, metadata):\n \"\"\"\n Sets the Node's metadata.\n \n @param node: Node\n @type node: L{Node}\n \n @param metadata: Key/Value metadata to associate with a node\n @type metadata: C{dict}\n \n @rtype: C{dict}\n \"\"\"\n return self.connection.request('/servers/%s/metadata' % (node.id,), method='PUT', data={'metadata': metadata}).object['metadata']\n ", "context": "class OpenStack_1_1_NodeDriver(OpenStackNodeDriver):\n def ex_set_metadata(self, node, metadata): ...\n def __init__(self, *args, **kwargs): ...\n def create_node(self, **kwargs): ...\n def _to_images(self, obj, ex_only_active): ...\n def _to_image(self, api_image): ...\n def _to_nodes(self, obj): ...\n def _to_sizes(self, obj): ...\n def _create_args_to_params(self, node, **kwargs): ...\n def _files_to_personality(self, files): ...\n def _reboot_node(self, node, reboot_type='SOFT'): ...\n def ex_set_password(self, node, password): ...\n def ex_rebuild(self, node, image): ...\n def ex_resize(self, node, size): ...\n def ex_confirm_resize(self, node): ...\n def ex_revert_resize(self, node): ...\n def ex_save_image(self, node, name, metadata=None): ...\n def ex_set_server_name(self, node, name): ...\n def ex_get_metadata(self, node): ...\n def ex_update_node(self, node, **node_updates): ...\n def _to_networks(self, obj): ...\n def _to_network(self, obj): ...\n def ex_list_networks(self): ...\n def ex_create_network(self, name, cidr): ...\n def ex_delete_network(self, network): ...\n def _to_security_group_rules(self, obj): ...\n def _to_security_group_rule(self, obj): ...\n def _to_security_groups(self, obj): ...\n def _to_security_group(self, obj): ...\n def ex_list_security_groups(self): ...\n def ex_get_node_security_groups(self, node): ...\n def ex_create_security_group(self, name, description): ...\n def ex_delete_security_group(self, security_group): ...\n def ex_create_security_group_rule(self, security_group, ip_protocol, from_port, to_port, cidr=None, source_security_group=None): ...\n def ex_delete_security_group_rule(self, rule): ...\n def ex_get_size(self, size_id): ...\n def ex_get_image(self, image_id): ...\n def ex_delete_image(self, image): ...\n def _node_action(self, node, action, **params): ...\n def _update_node(self, node, **node_updates): ...\n def _to_node_from_obj(self, obj): ...\n def _to_node(self, api_node): ...\n def _to_size(self, api_flavor, price=None, bandwidth=None): ...\n def _get_size_price(self, size_id): ...\n def _extract_image_id_from_url(self, location_header): ...\n def ex_rescue(self, node, password=None): ...\n def ex_unrescue(self, node): ...\n\n self._ex_force_api_version = str(kwargs.pop('ex_force_api_version', None))\n\n connectionCls = OpenStack_1_1_Connection\n type = Provider.OPENSTACK\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_set_metadata", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "ex_get_metadata", "tests": "import unittest\n\nclass Test_ex_get_metadata(unittest.TestCase):\n def test_ex_get_metadata(self):\n node = Node(id='12063', name=None, state=None, public_ips=None, private_ips=None, driver=self.driver)\n metadata = {'Image Version': '2.1', 'Server Label': 'Web Head 1'}\n returned_metadata = self.driver.ex_get_metadata(node)\n self.assertEqual(metadata, returned_metadata)\n", "method_code": " def ex_get_metadata(self, node):\n \"\"\"\n Get a Node's metadata.\n \n @param node: Node\n @type node: L{Node}\n \n @return: Key/Value metadata associated with node.\n @rtype: C{dict}\n \"\"\"\n return self.connection.request('/servers/%s/metadata' % (node.id,), method='GET').object['metadata']\n ", "context": "class OpenStack_1_1_NodeDriver(OpenStackNodeDriver):\n def ex_get_metadata(self, node): ...\n def __init__(self, *args, **kwargs): ...\n def create_node(self, **kwargs): ...\n def _to_images(self, obj, ex_only_active): ...\n def _to_image(self, api_image): ...\n def _to_nodes(self, obj): ...\n def _to_sizes(self, obj): ...\n def _create_args_to_params(self, node, **kwargs): ...\n def _files_to_personality(self, files): ...\n def _reboot_node(self, node, reboot_type='SOFT'): ...\n def ex_set_password(self, node, password): ...\n def ex_rebuild(self, node, image): ...\n def ex_resize(self, node, size): ...\n def ex_confirm_resize(self, node): ...\n def ex_revert_resize(self, node): ...\n def ex_save_image(self, node, name, metadata=None): ...\n def ex_set_server_name(self, node, name): ...\n def ex_set_metadata(self, node, metadata): ...\n def ex_update_node(self, node, **node_updates): ...\n def _to_networks(self, obj): ...\n def _to_network(self, obj): ...\n def ex_list_networks(self): ...\n def ex_create_network(self, name, cidr): ...\n def ex_delete_network(self, network): ...\n def _to_security_group_rules(self, obj): ...\n def _to_security_group_rule(self, obj): ...\n def _to_security_groups(self, obj): ...\n def _to_security_group(self, obj): ...\n def ex_list_security_groups(self): ...\n def ex_get_node_security_groups(self, node): ...\n def ex_create_security_group(self, name, description): ...\n def ex_delete_security_group(self, security_group): ...\n def ex_create_security_group_rule(self, security_group, ip_protocol, from_port, to_port, cidr=None, source_security_group=None): ...\n def ex_delete_security_group_rule(self, rule): ...\n def ex_get_size(self, size_id): ...\n def ex_get_image(self, image_id): ...\n def ex_delete_image(self, image): ...\n def _node_action(self, node, action, **params): ...\n def _update_node(self, node, **node_updates): ...\n def _to_node_from_obj(self, obj): ...\n def _to_node(self, api_node): ...\n def _to_size(self, api_flavor, price=None, bandwidth=None): ...\n def _get_size_price(self, size_id): ...\n def _extract_image_id_from_url(self, location_header): ...\n def ex_rescue(self, node, password=None): ...\n def ex_unrescue(self, node): ...\n\n self._ex_force_api_version = str(kwargs.pop('ex_force_api_version', None))\n\n connectionCls = OpenStack_1_1_Connection\n type = Provider.OPENSTACK\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_get_metadata", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000721.py"} {"focal_file": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "ex_update_node", "tests": "import unittest\n\nclass Test_ex_update_node(unittest.TestCase):\n def test_ex_update_node(self):\n old_node = Node(id='12064', name=None, state=None, public_ips=None, private_ips=None, driver=self.driver)\n new_node = self.driver.ex_update_node(old_node, name='Bob')\n self.assertTrue(new_node)\n self.assertEqual('Bob', new_node.name)\n self.assertEqual('50.57.94.30', new_node.public_ips[0])\n", "method_code": " def ex_update_node(self, node, **node_updates):\n \"\"\"\n Update the Node's editable attributes. The OpenStack API currently\n supports editing name and IPv4/IPv6 access addresses.\n \n The driver currently only supports updating the node name.\n \n @param node: Node\n @type node: L{Node}\n \n @keyword name: New name for the server\n @type name: C{str}\n \n @rtype: L{Node}\n \"\"\"\n potential_data = self._create_args_to_params(node, **node_updates)\n updates = {'name': potential_data['name']}\n return self._update_node(node, **updates)\n ", "context": "class OpenStack_1_1_NodeDriver(OpenStackNodeDriver):\n def ex_update_node(self, node, **node_updates): ...\n def __init__(self, *args, **kwargs): ...\n def create_node(self, **kwargs): ...\n def _to_images(self, obj, ex_only_active): ...\n def _to_image(self, api_image): ...\n def _to_nodes(self, obj): ...\n def _to_sizes(self, obj): ...\n def _create_args_to_params(self, node, **kwargs): ...\n def _files_to_personality(self, files): ...\n def _reboot_node(self, node, reboot_type='SOFT'): ...\n def ex_set_password(self, node, password): ...\n def ex_rebuild(self, node, image): ...\n def ex_resize(self, node, size): ...\n def ex_confirm_resize(self, node): ...\n def ex_revert_resize(self, node): ...\n def ex_save_image(self, node, name, metadata=None): ...\n def ex_set_server_name(self, node, name): ...\n def ex_get_metadata(self, node): ...\n def ex_set_metadata(self, node, metadata): ...\n def _to_networks(self, obj): ...\n def _to_network(self, obj): ...\n def ex_list_networks(self): ...\n def ex_create_network(self, name, cidr): ...\n def ex_delete_network(self, network): ...\n def _to_security_group_rules(self, obj): ...\n def _to_security_group_rule(self, obj): ...\n def _to_security_groups(self, obj): ...\n def _to_security_group(self, obj): ...\n def ex_list_security_groups(self): ...\n def ex_get_node_security_groups(self, node): ...\n def ex_create_security_group(self, name, description): ...\n def ex_delete_security_group(self, security_group): ...\n def ex_create_security_group_rule(self, security_group, ip_protocol, from_port, to_port, cidr=None, source_security_group=None): ...\n def ex_delete_security_group_rule(self, rule): ...\n def ex_get_size(self, size_id): ...\n def ex_get_image(self, image_id): ...\n def ex_delete_image(self, image): ...\n def _node_action(self, node, action, **params): ...\n def _update_node(self, node, **node_updates): ...\n def _to_node_from_obj(self, obj): ...\n def _to_node(self, api_node): ...\n def _to_size(self, api_flavor, price=None, bandwidth=None): ...\n def _get_size_price(self, size_id): ...\n def _extract_image_id_from_url(self, location_header): ...\n def ex_rescue(self, node, password=None): ...\n def ex_unrescue(self, node): ...\n\n self._ex_force_api_version = str(kwargs.pop('ex_force_api_version', None))\n\n connectionCls = OpenStack_1_1_Connection\n type = Provider.OPENSTACK\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_update_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000722.py"} {"focal_file": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "ex_get_node_details", "tests": "import unittest\n\nclass Test_ex_get_node_details(unittest.TestCase):\n def test_ex_get_node_details(self):\n node_id = '12064'\n node = self.driver.ex_get_node_details(node_id)\n self.assertEqual(node.id, '12064')\n self.assertEqual(node.name, 'lc-test')\n", "method_code": " def ex_get_node_details(self, node_id):\n \"\"\"\n Lists details of the specified server.\n \n @param node_id: ID of the node which should be used\n @type node_id: C{str}\n \n @rtype: L{Node}\n \"\"\"\n if isinstance(node_id, Node):\n node_id = node_id.id\n uri = '/servers/%s' % node_id\n resp = self.connection.request(uri, method='GET')\n if resp.status == httplib.NOT_FOUND:\n return None\n return self._to_node_from_obj(resp.object)\n ", "context": "class OpenStackNodeDriver(NodeDriverOpenStackDriverMixin):\n def ex_get_node_details(self, node_id): ...\n def __new__(cls, key, secret=None, secure=True, host=None, port=None, api_version=DEFAULT_API_VERSION, **kwargs): ...\n def __init__(self, *args, **kwargs): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self, location=None, ex_only_active=True): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def _ex_connection_class_kwargs(self): ...\n def ex_soft_reboot_node(self, node): ...\n def ex_hard_reboot_node(self, node): ...\n\n api_name = 'openstack'\n name = 'OpenStack'\n website = 'http://openstack.org/'\n NODE_STATE_MAP = {'BUILD': NodeState.PENDING, 'REBUILD': NodeState.PENDING, 'ACTIVE': NodeState.RUNNING, 'SUSPENDED': NodeState.TERMINATED, 'DELETED': NodeState.TERMINATED, 'QUEUE_RESIZE': NodeState.PENDING, 'PREP_RESIZE': NodeState.PENDING, 'VERIFY_RESIZE': NodeState.RUNNING, 'PASSWORD': NodeState.PENDING, 'RESCUE': NodeState.PENDING, 'REBOOT': NodeState.REBOOTING, 'HARD_REBOOT': NodeState.REBOOTING, 'SHARE_IP': NodeState.PENDING, 'SHARE_IP_NO_CONFIG': NodeState.PENDING, 'DELETE_IP': NodeState.PENDING, 'UNKNOWN': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_get_node_details", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000723.py"} {"focal_file": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "ex_get_size", "tests": "import unittest\n\nclass Test_ex_get_size(unittest.TestCase):\n def test_ex_get_size(self):\n size_id = '7'\n size = self.driver.ex_get_size(size_id)\n self.assertEqual(size.id, size_id)\n self.assertEqual(size.name, '15.5GB slice')\n", "method_code": " def ex_get_size(self, size_id):\n \"\"\"\n Get a NodeSize\n \n @param size_id: ID of the size which should be used\n @type size_id: C{str}\n \n @rtype: L{NodeSize}\n \"\"\"\n return self._to_size(self.connection.request('/flavors/%s' % (size_id,)).object['flavor'])\n ", "context": "class OpenStack_1_1_NodeDriver(OpenStackNodeDriver):\n def ex_get_size(self, size_id): ...\n def __init__(self, *args, **kwargs): ...\n def create_node(self, **kwargs): ...\n def _to_images(self, obj, ex_only_active): ...\n def _to_image(self, api_image): ...\n def _to_nodes(self, obj): ...\n def _to_sizes(self, obj): ...\n def _create_args_to_params(self, node, **kwargs): ...\n def _files_to_personality(self, files): ...\n def _reboot_node(self, node, reboot_type='SOFT'): ...\n def ex_set_password(self, node, password): ...\n def ex_rebuild(self, node, image): ...\n def ex_resize(self, node, size): ...\n def ex_confirm_resize(self, node): ...\n def ex_revert_resize(self, node): ...\n def ex_save_image(self, node, name, metadata=None): ...\n def ex_set_server_name(self, node, name): ...\n def ex_get_metadata(self, node): ...\n def ex_set_metadata(self, node, metadata): ...\n def ex_update_node(self, node, **node_updates): ...\n def _to_networks(self, obj): ...\n def _to_network(self, obj): ...\n def ex_list_networks(self): ...\n def ex_create_network(self, name, cidr): ...\n def ex_delete_network(self, network): ...\n def _to_security_group_rules(self, obj): ...\n def _to_security_group_rule(self, obj): ...\n def _to_security_groups(self, obj): ...\n def _to_security_group(self, obj): ...\n def ex_list_security_groups(self): ...\n def ex_get_node_security_groups(self, node): ...\n def ex_create_security_group(self, name, description): ...\n def ex_delete_security_group(self, security_group): ...\n def ex_create_security_group_rule(self, security_group, ip_protocol, from_port, to_port, cidr=None, source_security_group=None): ...\n def ex_delete_security_group_rule(self, rule): ...\n def ex_get_image(self, image_id): ...\n def ex_delete_image(self, image): ...\n def _node_action(self, node, action, **params): ...\n def _update_node(self, node, **node_updates): ...\n def _to_node_from_obj(self, obj): ...\n def _to_node(self, api_node): ...\n def _to_size(self, api_flavor, price=None, bandwidth=None): ...\n def _get_size_price(self, size_id): ...\n def _extract_image_id_from_url(self, location_header): ...\n def ex_rescue(self, node, password=None): ...\n def ex_unrescue(self, node): ...\n\n self._ex_force_api_version = str(kwargs.pop('ex_force_api_version', None))\n\n connectionCls = OpenStack_1_1_Connection\n type = Provider.OPENSTACK\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_get_size", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000724.py"} {"focal_file": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "ex_get_image", "tests": "import unittest\n\nclass Test_ex_get_image(unittest.TestCase):\n def test_ex_get_image(self):\n image_id = '13'\n image = self.driver.ex_get_image(image_id)\n self.assertEqual(image.id, image_id)\n self.assertEqual(image.name, 'Windows 2008 SP2 x86 (B24)')\n self.assertEqual(image.extra['serverId'], None)\n self.assertEqual(image.extra['minDisk'], '5')\n self.assertEqual(image.extra['minRam'], '256')\n", "method_code": " def ex_get_image(self, image_id):\n \"\"\"\n Get a NodeImage\n \n @param image_id: ID of the image which should be used\n @type image_id: C{str}\n \n @rtype: L{NodeImage}\n \"\"\"\n return self._to_image(self.connection.request('/images/%s' % (image_id,)).object['image'])\n ", "context": "class OpenStack_1_1_NodeDriver(OpenStackNodeDriver):\n def ex_get_image(self, image_id): ...\n def __init__(self, *args, **kwargs): ...\n def create_node(self, **kwargs): ...\n def _to_images(self, obj, ex_only_active): ...\n def _to_image(self, api_image): ...\n def _to_nodes(self, obj): ...\n def _to_sizes(self, obj): ...\n def _create_args_to_params(self, node, **kwargs): ...\n def _files_to_personality(self, files): ...\n def _reboot_node(self, node, reboot_type='SOFT'): ...\n def ex_set_password(self, node, password): ...\n def ex_rebuild(self, node, image): ...\n def ex_resize(self, node, size): ...\n def ex_confirm_resize(self, node): ...\n def ex_revert_resize(self, node): ...\n def ex_save_image(self, node, name, metadata=None): ...\n def ex_set_server_name(self, node, name): ...\n def ex_get_metadata(self, node): ...\n def ex_set_metadata(self, node, metadata): ...\n def ex_update_node(self, node, **node_updates): ...\n def _to_networks(self, obj): ...\n def _to_network(self, obj): ...\n def ex_list_networks(self): ...\n def ex_create_network(self, name, cidr): ...\n def ex_delete_network(self, network): ...\n def _to_security_group_rules(self, obj): ...\n def _to_security_group_rule(self, obj): ...\n def _to_security_groups(self, obj): ...\n def _to_security_group(self, obj): ...\n def ex_list_security_groups(self): ...\n def ex_get_node_security_groups(self, node): ...\n def ex_create_security_group(self, name, description): ...\n def ex_delete_security_group(self, security_group): ...\n def ex_create_security_group_rule(self, security_group, ip_protocol, from_port, to_port, cidr=None, source_security_group=None): ...\n def ex_delete_security_group_rule(self, rule): ...\n def ex_get_size(self, size_id): ...\n def ex_delete_image(self, image): ...\n def _node_action(self, node, action, **params): ...\n def _update_node(self, node, **node_updates): ...\n def _to_node_from_obj(self, obj): ...\n def _to_node(self, api_node): ...\n def _to_size(self, api_flavor, price=None, bandwidth=None): ...\n def _get_size_price(self, size_id): ...\n def _extract_image_id_from_url(self, location_header): ...\n def ex_rescue(self, node, password=None): ...\n def ex_unrescue(self, node): ...\n\n self._ex_force_api_version = str(kwargs.pop('ex_force_api_version', None))\n\n connectionCls = OpenStack_1_1_Connection\n type = Provider.OPENSTACK\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_get_image", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000725.py"} {"focal_file": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "_extract_image_id_from_url", "tests": "import unittest\n\nclass Test_extract_image_id_from_url(unittest.TestCase):\n def test_extract_image_id_from_url(self):\n url = 'http://127.0.0.1/v1.1/68/images/1d4a8ea9-aae7-4242-a42d-5ff4702f2f14'\n url_two = 'http://127.0.0.1/v1.1/68/images/13'\n image_id = self.driver._extract_image_id_from_url(url)\n image_id_two = self.driver._extract_image_id_from_url(url_two)\n self.assertEqual(image_id, '1d4a8ea9-aae7-4242-a42d-5ff4702f2f14')\n self.assertEqual(image_id_two, '13')\n", "method_code": " def _extract_image_id_from_url(self, location_header):\n path = urlparse.urlparse(location_header).path\n image_id = path.split('/')[-1]\n return image_id\n ", "context": "class OpenStack_1_1_NodeDriver(OpenStackNodeDriver):\n def _extract_image_id_from_url(self, location_header): ...\n def __init__(self, *args, **kwargs): ...\n def create_node(self, **kwargs): ...\n def _to_images(self, obj, ex_only_active): ...\n def _to_image(self, api_image): ...\n def _to_nodes(self, obj): ...\n def _to_sizes(self, obj): ...\n def _create_args_to_params(self, node, **kwargs): ...\n def _files_to_personality(self, files): ...\n def _reboot_node(self, node, reboot_type='SOFT'): ...\n def ex_set_password(self, node, password): ...\n def ex_rebuild(self, node, image): ...\n def ex_resize(self, node, size): ...\n def ex_confirm_resize(self, node): ...\n def ex_revert_resize(self, node): ...\n def ex_save_image(self, node, name, metadata=None): ...\n def ex_set_server_name(self, node, name): ...\n def ex_get_metadata(self, node): ...\n def ex_set_metadata(self, node, metadata): ...\n def ex_update_node(self, node, **node_updates): ...\n def _to_networks(self, obj): ...\n def _to_network(self, obj): ...\n def ex_list_networks(self): ...\n def ex_create_network(self, name, cidr): ...\n def ex_delete_network(self, network): ...\n def _to_security_group_rules(self, obj): ...\n def _to_security_group_rule(self, obj): ...\n def _to_security_groups(self, obj): ...\n def _to_security_group(self, obj): ...\n def ex_list_security_groups(self): ...\n def ex_get_node_security_groups(self, node): ...\n def ex_create_security_group(self, name, description): ...\n def ex_delete_security_group(self, security_group): ...\n def ex_create_security_group_rule(self, security_group, ip_protocol, from_port, to_port, cidr=None, source_security_group=None): ...\n def ex_delete_security_group_rule(self, rule): ...\n def ex_get_size(self, size_id): ...\n def ex_get_image(self, image_id): ...\n def ex_delete_image(self, image): ...\n def _node_action(self, node, action, **params): ...\n def _update_node(self, node, **node_updates): ...\n def _to_node_from_obj(self, obj): ...\n def _to_node(self, api_node): ...\n def _to_size(self, api_flavor, price=None, bandwidth=None): ...\n def _get_size_price(self, size_id): ...\n def ex_rescue(self, node, password=None): ...\n def ex_unrescue(self, node): ...\n\n self._ex_force_api_version = str(kwargs.pop('ex_force_api_version', None))\n\n connectionCls = OpenStack_1_1_Connection\n type = Provider.OPENSTACK\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_extract_image_id_from_url", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000726.py"} {"focal_file": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "ex_unrescue", "tests": "import unittest\n\nclass Test_ex_unrescue(unittest.TestCase):\n def test_ex_unrescue(self):\n node = Node(id=12064, name=None, state=None, public_ips=None, private_ips=None, driver=self.driver)\n result = self.driver.ex_unrescue(node)\n self.assertTrue(result)\n", "method_code": " def ex_unrescue(self, node):\n \"\"\"\n Unrescue a node\n \n @param node: node\n @type node: L{Node}\n \n @rtype: C{bool}\n \"\"\"\n resp = self._node_action(node, 'unrescue')\n return resp.status == httplib.ACCEPTED\n ", "context": "class OpenStack_1_1_NodeDriver(OpenStackNodeDriver):\n def ex_unrescue(self, node): ...\n def __init__(self, *args, **kwargs): ...\n def create_node(self, **kwargs): ...\n def _to_images(self, obj, ex_only_active): ...\n def _to_image(self, api_image): ...\n def _to_nodes(self, obj): ...\n def _to_sizes(self, obj): ...\n def _create_args_to_params(self, node, **kwargs): ...\n def _files_to_personality(self, files): ...\n def _reboot_node(self, node, reboot_type='SOFT'): ...\n def ex_set_password(self, node, password): ...\n def ex_rebuild(self, node, image): ...\n def ex_resize(self, node, size): ...\n def ex_confirm_resize(self, node): ...\n def ex_revert_resize(self, node): ...\n def ex_save_image(self, node, name, metadata=None): ...\n def ex_set_server_name(self, node, name): ...\n def ex_get_metadata(self, node): ...\n def ex_set_metadata(self, node, metadata): ...\n def ex_update_node(self, node, **node_updates): ...\n def _to_networks(self, obj): ...\n def _to_network(self, obj): ...\n def ex_list_networks(self): ...\n def ex_create_network(self, name, cidr): ...\n def ex_delete_network(self, network): ...\n def _to_security_group_rules(self, obj): ...\n def _to_security_group_rule(self, obj): ...\n def _to_security_groups(self, obj): ...\n def _to_security_group(self, obj): ...\n def ex_list_security_groups(self): ...\n def ex_get_node_security_groups(self, node): ...\n def ex_create_security_group(self, name, description): ...\n def ex_delete_security_group(self, security_group): ...\n def ex_create_security_group_rule(self, security_group, ip_protocol, from_port, to_port, cidr=None, source_security_group=None): ...\n def ex_delete_security_group_rule(self, rule): ...\n def ex_get_size(self, size_id): ...\n def ex_get_image(self, image_id): ...\n def ex_delete_image(self, image): ...\n def _node_action(self, node, action, **params): ...\n def _update_node(self, node, **node_updates): ...\n def _to_node_from_obj(self, obj): ...\n def _to_node(self, api_node): ...\n def _to_size(self, api_flavor, price=None, bandwidth=None): ...\n def _get_size_price(self, size_id): ...\n def _extract_image_id_from_url(self, location_header): ...\n def ex_rescue(self, node, password=None): ...\n\n self._ex_force_api_version = str(kwargs.pop('ex_force_api_version', None))\n\n connectionCls = OpenStack_1_1_Connection\n type = Provider.OPENSTACK\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_unrescue", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "ex_get_node_security_groups", "tests": "import unittest\n\nclass Test_ex_get_node_security_groups(unittest.TestCase):\n def test_ex_get_node_security_groups(self):\n node = Node(id='1c01300f-ef97-4937-8f03-ac676d6234be', name=None, state=None, public_ips=None, private_ips=None, driver=self.driver)\n security_groups = self.driver.ex_get_node_security_groups(node)\n self.assertEqual(len(security_groups), 2, 'Wrong security groups count')\n security_group = security_groups[1]\n self.assertEqual(security_group.id, 4)\n self.assertEqual(security_group.tenant_id, '68')\n self.assertEqual(security_group.name, 'ftp')\n self.assertEqual(security_group.description, 'FTP Client-Server - Open 20-21 ports')\n self.assertEqual(security_group.rules[0].id, 1)\n self.assertEqual(security_group.rules[0].parent_group_id, 4)\n self.assertEqual(security_group.rules[0].ip_protocol, 'tcp')\n self.assertEqual(security_group.rules[0].from_port, 20)\n self.assertEqual(security_group.rules[0].to_port, 21)\n self.assertEqual(security_group.rules[0].ip_range, '0.0.0.0/0')\n", "method_code": " def ex_get_node_security_groups(self, node):\n \"\"\"\n Get Security Groups of the specified server.\n \n @rtype: C{list} of L{OpenStackSecurityGroup}\n \"\"\"\n return self._to_security_groups(self.connection.request('/servers/%s/os-security-groups' % node.id).object)\n ", "context": "class OpenStack_1_1_NodeDriver(OpenStackNodeDriver):\n def ex_get_node_security_groups(self, node): ...\n def __init__(self, *args, **kwargs): ...\n def create_node(self, **kwargs): ...\n def _to_images(self, obj, ex_only_active): ...\n def _to_image(self, api_image): ...\n def _to_nodes(self, obj): ...\n def _to_sizes(self, obj): ...\n def _create_args_to_params(self, node, **kwargs): ...\n def _files_to_personality(self, files): ...\n def _reboot_node(self, node, reboot_type='SOFT'): ...\n def ex_set_password(self, node, password): ...\n def ex_rebuild(self, node, image): ...\n def ex_resize(self, node, size): ...\n def ex_confirm_resize(self, node): ...\n def ex_revert_resize(self, node): ...\n def ex_save_image(self, node, name, metadata=None): ...\n def ex_set_server_name(self, node, name): ...\n def ex_get_metadata(self, node): ...\n def ex_set_metadata(self, node, metadata): ...\n def ex_update_node(self, node, **node_updates): ...\n def _to_networks(self, obj): ...\n def _to_network(self, obj): ...\n def ex_list_networks(self): ...\n def ex_create_network(self, name, cidr): ...\n def ex_delete_network(self, network): ...\n def _to_security_group_rules(self, obj): ...\n def _to_security_group_rule(self, obj): ...\n def _to_security_groups(self, obj): ...\n def _to_security_group(self, obj): ...\n def ex_list_security_groups(self): ...\n def ex_create_security_group(self, name, description): ...\n def ex_delete_security_group(self, security_group): ...\n def ex_create_security_group_rule(self, security_group, ip_protocol, from_port, to_port, cidr=None, source_security_group=None): ...\n def ex_delete_security_group_rule(self, rule): ...\n def ex_get_size(self, size_id): ...\n def ex_get_image(self, image_id): ...\n def ex_delete_image(self, image): ...\n def _node_action(self, node, action, **params): ...\n def _update_node(self, node, **node_updates): ...\n def _to_node_from_obj(self, obj): ...\n def _to_node(self, api_node): ...\n def _to_size(self, api_flavor, price=None, bandwidth=None): ...\n def _get_size_price(self, size_id): ...\n def _extract_image_id_from_url(self, location_header): ...\n def ex_rescue(self, node, password=None): ...\n def ex_unrescue(self, node): ...\n\n self._ex_force_api_version = str(kwargs.pop('ex_force_api_version', None))\n\n connectionCls = OpenStack_1_1_Connection\n type = Provider.OPENSTACK\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_get_node_security_groups", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000728.py"} {"focal_file": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "ex_list_security_groups", "tests": "import unittest\n\nclass Test_ex_list_security_groups(unittest.TestCase):\n def test_ex_list_security_groups(self):\n security_groups = self.driver.ex_list_security_groups()\n self.assertEqual(len(security_groups), 2, 'Wrong security groups count')\n security_group = security_groups[1]\n self.assertEqual(security_group.id, 4)\n self.assertEqual(security_group.tenant_id, '68')\n self.assertEqual(security_group.name, 'ftp')\n self.assertEqual(security_group.description, 'FTP Client-Server - Open 20-21 ports')\n self.assertEqual(security_group.rules[0].id, 1)\n self.assertEqual(security_group.rules[0].parent_group_id, 4)\n self.assertEqual(security_group.rules[0].ip_protocol, 'tcp')\n self.assertEqual(security_group.rules[0].from_port, 20)\n self.assertEqual(security_group.rules[0].to_port, 21)\n self.assertEqual(security_group.rules[0].ip_range, '0.0.0.0/0')\n", "method_code": " def ex_list_security_groups(self):\n \"\"\"\n Get a list of Security Groups that are available.\n \n @rtype: C{list} of L{OpenStackSecurityGroup}\n \"\"\"\n return self._to_security_groups(self.connection.request('/os-security-groups').object)\n ", "context": "class OpenStack_1_1_NodeDriver(OpenStackNodeDriver):\n def ex_list_security_groups(self): ...\n def __init__(self, *args, **kwargs): ...\n def create_node(self, **kwargs): ...\n def _to_images(self, obj, ex_only_active): ...\n def _to_image(self, api_image): ...\n def _to_nodes(self, obj): ...\n def _to_sizes(self, obj): ...\n def _create_args_to_params(self, node, **kwargs): ...\n def _files_to_personality(self, files): ...\n def _reboot_node(self, node, reboot_type='SOFT'): ...\n def ex_set_password(self, node, password): ...\n def ex_rebuild(self, node, image): ...\n def ex_resize(self, node, size): ...\n def ex_confirm_resize(self, node): ...\n def ex_revert_resize(self, node): ...\n def ex_save_image(self, node, name, metadata=None): ...\n def ex_set_server_name(self, node, name): ...\n def ex_get_metadata(self, node): ...\n def ex_set_metadata(self, node, metadata): ...\n def ex_update_node(self, node, **node_updates): ...\n def _to_networks(self, obj): ...\n def _to_network(self, obj): ...\n def ex_list_networks(self): ...\n def ex_create_network(self, name, cidr): ...\n def ex_delete_network(self, network): ...\n def _to_security_group_rules(self, obj): ...\n def _to_security_group_rule(self, obj): ...\n def _to_security_groups(self, obj): ...\n def _to_security_group(self, obj): ...\n def ex_get_node_security_groups(self, node): ...\n def ex_create_security_group(self, name, description): ...\n def ex_delete_security_group(self, security_group): ...\n def ex_create_security_group_rule(self, security_group, ip_protocol, from_port, to_port, cidr=None, source_security_group=None): ...\n def ex_delete_security_group_rule(self, rule): ...\n def ex_get_size(self, size_id): ...\n def ex_get_image(self, image_id): ...\n def ex_delete_image(self, image): ...\n def _node_action(self, node, action, **params): ...\n def _update_node(self, node, **node_updates): ...\n def _to_node_from_obj(self, obj): ...\n def _to_node(self, api_node): ...\n def _to_size(self, api_flavor, price=None, bandwidth=None): ...\n def _get_size_price(self, size_id): ...\n def _extract_image_id_from_url(self, location_header): ...\n def ex_rescue(self, node, password=None): ...\n def ex_unrescue(self, node): ...\n\n self._ex_force_api_version = str(kwargs.pop('ex_force_api_version', None))\n\n connectionCls = OpenStack_1_1_Connection\n type = Provider.OPENSTACK\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_list_security_groups", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000729.py"} {"focal_file": "libcloud/compute/drivers/openstack.py", "focal_class": null, "focal_method": "ex_create_security_group", "tests": "import unittest\n\nclass Test_ex_create_security_group(unittest.TestCase):\n def test_ex_create_security_group(self):\n name = 'test'\n description = 'Test Security Group'\n security_group = self.driver.ex_create_security_group(name, description)\n self.assertEqual(security_group.id, 6)\n self.assertEqual(security_group.tenant_id, '68')\n self.assertEqual(security_group.name, name)\n self.assertEqual(security_group.description, description)\n self.assertEqual(len(security_group.rules), 0)\n", "method_code": " def ex_create_security_group(self, name, description):\n \"\"\"\n Create a new Security Group\n \n @param name: Name of the new Security Group\n @type name: C{str}\n \n @param description: Description of the new Security Group\n @type description: C{str}\n \n @rtype: L{OpenStackSecurityGroup}\n \"\"\"\n return self._to_security_group(self.connection.request('/os-security-groups', method='POST', data={'security_group': {'name': name, 'description': description}}).object['security_group'])\n ", "context": "class OpenStack_1_1_NodeDriver(OpenStackNodeDriver):\n def ex_create_security_group(self, name, description): ...\n def __init__(self, *args, **kwargs): ...\n def create_node(self, **kwargs): ...\n def _to_images(self, obj, ex_only_active): ...\n def _to_image(self, api_image): ...\n def _to_nodes(self, obj): ...\n def _to_sizes(self, obj): ...\n def _create_args_to_params(self, node, **kwargs): ...\n def _files_to_personality(self, files): ...\n def _reboot_node(self, node, reboot_type='SOFT'): ...\n def ex_set_password(self, node, password): ...\n def ex_rebuild(self, node, image): ...\n def ex_resize(self, node, size): ...\n def ex_confirm_resize(self, node): ...\n def ex_revert_resize(self, node): ...\n def ex_save_image(self, node, name, metadata=None): ...\n def ex_set_server_name(self, node, name): ...\n def ex_get_metadata(self, node): ...\n def ex_set_metadata(self, node, metadata): ...\n def ex_update_node(self, node, **node_updates): ...\n def _to_networks(self, obj): ...\n def _to_network(self, obj): ...\n def ex_list_networks(self): ...\n def ex_create_network(self, name, cidr): ...\n def ex_delete_network(self, network): ...\n def _to_security_group_rules(self, obj): ...\n def _to_security_group_rule(self, obj): ...\n def _to_security_groups(self, obj): ...\n def _to_security_group(self, obj): ...\n def ex_list_security_groups(self): ...\n def ex_get_node_security_groups(self, node): ...\n def ex_delete_security_group(self, security_group): ...\n def ex_create_security_group_rule(self, security_group, ip_protocol, from_port, to_port, cidr=None, source_security_group=None): ...\n def ex_delete_security_group_rule(self, rule): ...\n def ex_get_size(self, size_id): ...\n def ex_get_image(self, image_id): ...\n def ex_delete_image(self, image): ...\n def _node_action(self, node, action, **params): ...\n def _update_node(self, node, **node_updates): ...\n def _to_node_from_obj(self, obj): ...\n def _to_node(self, api_node): ...\n def _to_size(self, api_flavor, price=None, bandwidth=None): ...\n def _get_size_price(self, size_id): ...\n def _extract_image_id_from_url(self, location_header): ...\n def ex_rescue(self, node, password=None): ...\n def ex_unrescue(self, node): ...\n\n self._ex_force_api_version = str(kwargs.pop('ex_force_api_version', None))\n\n connectionCls = OpenStack_1_1_Connection\n type = Provider.OPENSTACK\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_create_security_group", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000730.py"} {"focal_file": "libcloud/compute/drivers/openstack.py", "focal_class": "OpenStackSecurityGroup", "focal_method": "ex_delete_security_group", "tests": "import unittest\n\nclass Test_OpenStackSecurityGroup_ex_delete_security_group(unittest.TestCase):\n def test_ex_delete_security_group(self):\n security_group = OpenStackSecurityGroup(id=6, tenant_id=None, name=None, description=None, driver=self.driver)\n result = self.driver.ex_delete_security_group(security_group)\n self.assertTrue(result)\n", "method_code": " def ex_delete_security_group(self, security_group):\n \"\"\"\n Delete a Security Group.\n \n @param security_group: Security Group should be deleted\n @type security_group: L{OpenStackSecurityGroup}\n \n @rtype: C{bool}\n \"\"\"\n resp = self.connection.request('/os-security-groups/%s' % security_group.id, method='DELETE')\n return resp.status == httplib.NO_CONTENT\n ", "context": "class OpenStack_1_1_NodeDriver(OpenStackNodeDriver):\n def ex_delete_security_group(self, security_group): ...\n def __init__(self, *args, **kwargs): ...\n def create_node(self, **kwargs): ...\n def _to_images(self, obj, ex_only_active): ...\n def _to_image(self, api_image): ...\n def _to_nodes(self, obj): ...\n def _to_sizes(self, obj): ...\n def _create_args_to_params(self, node, **kwargs): ...\n def _files_to_personality(self, files): ...\n def _reboot_node(self, node, reboot_type='SOFT'): ...\n def ex_set_password(self, node, password): ...\n def ex_rebuild(self, node, image): ...\n def ex_resize(self, node, size): ...\n def ex_confirm_resize(self, node): ...\n def ex_revert_resize(self, node): ...\n def ex_save_image(self, node, name, metadata=None): ...\n def ex_set_server_name(self, node, name): ...\n def ex_get_metadata(self, node): ...\n def ex_set_metadata(self, node, metadata): ...\n def ex_update_node(self, node, **node_updates): ...\n def _to_networks(self, obj): ...\n def _to_network(self, obj): ...\n def ex_list_networks(self): ...\n def ex_create_network(self, name, cidr): ...\n def ex_delete_network(self, network): ...\n def _to_security_group_rules(self, obj): ...\n def _to_security_group_rule(self, obj): ...\n def _to_security_groups(self, obj): ...\n def _to_security_group(self, obj): ...\n def ex_list_security_groups(self): ...\n def ex_get_node_security_groups(self, node): ...\n def ex_create_security_group(self, name, description): ...\n def ex_create_security_group_rule(self, security_group, ip_protocol, from_port, to_port, cidr=None, source_security_group=None): ...\n def ex_delete_security_group_rule(self, rule): ...\n def ex_get_size(self, size_id): ...\n def ex_get_image(self, image_id): ...\n def ex_delete_image(self, image): ...\n def _node_action(self, node, action, **params): ...\n def _update_node(self, node, **node_updates): ...\n def _to_node_from_obj(self, obj): ...\n def _to_node(self, api_node): ...\n def _to_size(self, api_flavor, price=None, bandwidth=None): ...\n def _get_size_price(self, size_id): ...\n def _extract_image_id_from_url(self, location_header): ...\n def ex_rescue(self, node, password=None): ...\n def ex_unrescue(self, node): ...\n\n self._ex_force_api_version = str(kwargs.pop('ex_force_api_version', None))\n\n connectionCls = OpenStack_1_1_Connection\n type = Provider.OPENSTACK\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_delete_security_group", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000731.py"} {"focal_file": "libcloud/compute/drivers/openstack.py", "focal_class": "OpenStackSecurityGroup", "focal_method": "ex_create_security_group_rule", "tests": "import unittest\n\nclass Test_OpenStackSecurityGroup_ex_create_security_group_rule(unittest.TestCase):\n def test_ex_create_security_group_rule(self):\n security_group = OpenStackSecurityGroup(id=6, tenant_id=None, name=None, description=None, driver=self.driver)\n security_group_rule = self.driver.ex_create_security_group_rule(security_group, 'tcp', 14, 16, '0.0.0.0/0')\n self.assertEqual(security_group_rule.id, 2)\n self.assertEqual(security_group_rule.parent_group_id, 6)\n self.assertEqual(security_group_rule.ip_protocol, 'tcp')\n self.assertEqual(security_group_rule.from_port, 14)\n self.assertEqual(security_group_rule.to_port, 16)\n self.assertEqual(security_group_rule.ip_range, '0.0.0.0/0')\n self.assertEqual(security_group_rule.tenant_id, None)\n", "method_code": " def ex_create_security_group_rule(self, security_group, ip_protocol, from_port, to_port, cidr=None, source_security_group=None):\n \"\"\"\n Create a new Rule in a Security Group\n \n @param security_group: Security Group in which to add the rule\n @type security_group: L{OpenStackSecurityGroup}\n \n @param ip_protocol: Protocol to which this rule applies\n Examples: tcp, udp, ...\n @type ip_protocol: C{str}\n \n @param from_port: First port of the port range\n @type from_port: C{int}\n \n @param to_port: Last port of the port range\n @type to_port: C{int}\n \n @param cidr: CIDR notation of the source IP range for this rule\n @type cidr: C{str}\n \n @param source_security_group: Existing Security Group to use as the\n source (instead of CIDR)\n @type source_security_group: L{OpenStackSecurityGroup\n \n @rtype: L{OpenStackSecurityGroupRule}\n \"\"\"\n source_security_group_id = None\n if type(source_security_group) == OpenStackSecurityGroup:\n source_security_group_id = source_security_group.id\n return self._to_security_group_rule(self.connection.request('/os-security-group-rules', method='POST', data={'security_group_rule': {'ip_protocol': ip_protocol, 'from_port': from_port, 'to_port': to_port, 'cidr': cidr, 'group_id': source_security_group_id, 'parent_group_id': security_group.id}}).object['security_group_rule'])\n ", "context": "class OpenStack_1_1_NodeDriver(OpenStackNodeDriver):\n def ex_create_security_group_rule(self, security_group, ip_protocol, from_port, to_port, cidr=None, source_security_group=None): ...\n def __init__(self, *args, **kwargs): ...\n def create_node(self, **kwargs): ...\n def _to_images(self, obj, ex_only_active): ...\n def _to_image(self, api_image): ...\n def _to_nodes(self, obj): ...\n def _to_sizes(self, obj): ...\n def _create_args_to_params(self, node, **kwargs): ...\n def _files_to_personality(self, files): ...\n def _reboot_node(self, node, reboot_type='SOFT'): ...\n def ex_set_password(self, node, password): ...\n def ex_rebuild(self, node, image): ...\n def ex_resize(self, node, size): ...\n def ex_confirm_resize(self, node): ...\n def ex_revert_resize(self, node): ...\n def ex_save_image(self, node, name, metadata=None): ...\n def ex_set_server_name(self, node, name): ...\n def ex_get_metadata(self, node): ...\n def ex_set_metadata(self, node, metadata): ...\n def ex_update_node(self, node, **node_updates): ...\n def _to_networks(self, obj): ...\n def _to_network(self, obj): ...\n def ex_list_networks(self): ...\n def ex_create_network(self, name, cidr): ...\n def ex_delete_network(self, network): ...\n def _to_security_group_rules(self, obj): ...\n def _to_security_group_rule(self, obj): ...\n def _to_security_groups(self, obj): ...\n def _to_security_group(self, obj): ...\n def ex_list_security_groups(self): ...\n def ex_get_node_security_groups(self, node): ...\n def ex_create_security_group(self, name, description): ...\n def ex_delete_security_group(self, security_group): ...\n def ex_delete_security_group_rule(self, rule): ...\n def ex_get_size(self, size_id): ...\n def ex_get_image(self, image_id): ...\n def ex_delete_image(self, image): ...\n def _node_action(self, node, action, **params): ...\n def _update_node(self, node, **node_updates): ...\n def _to_node_from_obj(self, obj): ...\n def _to_node(self, api_node): ...\n def _to_size(self, api_flavor, price=None, bandwidth=None): ...\n def _get_size_price(self, size_id): ...\n def _extract_image_id_from_url(self, location_header): ...\n def ex_rescue(self, node, password=None): ...\n def ex_unrescue(self, node): ...\n\n self._ex_force_api_version = str(kwargs.pop('ex_force_api_version', None))\n\n connectionCls = OpenStack_1_1_Connection\n type = Provider.OPENSTACK\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_create_security_group_rule", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000732.py"} {"focal_file": "libcloud/compute/drivers/openstack.py", "focal_class": "OpenStackSecurityGroupRule", "focal_method": "ex_delete_security_group_rule", "tests": "import unittest\n\nclass Test_OpenStackSecurityGroupRule_ex_delete_security_group_rule(unittest.TestCase):\n def test_ex_delete_security_group_rule(self):\n security_group_rule = OpenStackSecurityGroupRule(id=2, parent_group_id=None, ip_protocol=None, from_port=None, to_port=None, driver=self.driver)\n result = self.driver.ex_delete_security_group_rule(security_group_rule)\n self.assertTrue(result)\n", "method_code": " def ex_delete_security_group_rule(self, rule):\n \"\"\"\n Delete a Rule from a Security Group.\n \n @param rule: Rule should be deleted\n @type rule: L{OpenStackSecurityGroupRule}\n \n @rtype: C{bool}\n \"\"\"\n resp = self.connection.request('/os-security-group-rules/%s' % rule.id, method='DELETE')\n return resp.status == httplib.NO_CONTENT\n ", "context": "class OpenStack_1_1_NodeDriver(OpenStackNodeDriver):\n def ex_delete_security_group_rule(self, rule): ...\n def __init__(self, *args, **kwargs): ...\n def create_node(self, **kwargs): ...\n def _to_images(self, obj, ex_only_active): ...\n def _to_image(self, api_image): ...\n def _to_nodes(self, obj): ...\n def _to_sizes(self, obj): ...\n def _create_args_to_params(self, node, **kwargs): ...\n def _files_to_personality(self, files): ...\n def _reboot_node(self, node, reboot_type='SOFT'): ...\n def ex_set_password(self, node, password): ...\n def ex_rebuild(self, node, image): ...\n def ex_resize(self, node, size): ...\n def ex_confirm_resize(self, node): ...\n def ex_revert_resize(self, node): ...\n def ex_save_image(self, node, name, metadata=None): ...\n def ex_set_server_name(self, node, name): ...\n def ex_get_metadata(self, node): ...\n def ex_set_metadata(self, node, metadata): ...\n def ex_update_node(self, node, **node_updates): ...\n def _to_networks(self, obj): ...\n def _to_network(self, obj): ...\n def ex_list_networks(self): ...\n def ex_create_network(self, name, cidr): ...\n def ex_delete_network(self, network): ...\n def _to_security_group_rules(self, obj): ...\n def _to_security_group_rule(self, obj): ...\n def _to_security_groups(self, obj): ...\n def _to_security_group(self, obj): ...\n def ex_list_security_groups(self): ...\n def ex_get_node_security_groups(self, node): ...\n def ex_create_security_group(self, name, description): ...\n def ex_delete_security_group(self, security_group): ...\n def ex_create_security_group_rule(self, security_group, ip_protocol, from_port, to_port, cidr=None, source_security_group=None): ...\n def ex_get_size(self, size_id): ...\n def ex_get_image(self, image_id): ...\n def ex_delete_image(self, image): ...\n def _node_action(self, node, action, **params): ...\n def _update_node(self, node, **node_updates): ...\n def _to_node_from_obj(self, obj): ...\n def _to_node(self, api_node): ...\n def _to_size(self, api_flavor, price=None, bandwidth=None): ...\n def _get_size_price(self, size_id): ...\n def _extract_image_id_from_url(self, location_header): ...\n def ex_rescue(self, node, password=None): ...\n def ex_unrescue(self, node): ...\n\n self._ex_force_api_version = str(kwargs.pop('ex_force_api_version', None))\n\n connectionCls = OpenStack_1_1_Connection\n type = Provider.OPENSTACK\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_delete_security_group_rule", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000733.py"} {"focal_file": "libcloud/compute/drivers/opsource.py", "focal_class": null, "focal_method": "ex_shutdown_graceful", "tests": "import unittest\n\nclass Test_ex_shutdown_graceful(unittest.TestCase):\n def test_ex_shutdown_graceful(self):\n node = Node(id='11', name=None, state=None, public_ips=None, private_ips=None, driver=self.driver)\n ret = self.driver.ex_shutdown_graceful(node)\n self.assertTrue(ret is True)\n\n def test_ex_shutdown_graceful_INPROGRESS(self):\n OpsourceMockHttp.type = 'INPROGRESS'\n node = Node(id='11', name=None, state=None, public_ips=None, private_ips=None, driver=self.driver)\n try:\n self.driver.ex_shutdown_graceful(node)\n self.assertTrue(False)\n except OpsourceAPIException:\n self.assertTrue(True)\n", "method_code": " def ex_shutdown_graceful(self, node):\n \"\"\"\n This function will attempt to \"gracefully\" stop a server by\n initiating a shutdown sequence within the guest operating system.\n A successful response on this function means the system has\n successfully passed the request into the operating system.\n \n @param node: Node which should be used\n @type node: L{Node}\n \n @rtype: C{bool}\n \"\"\"\n body = self.connection.request_with_orgId('server/%s?shutdown' % node.id).object\n result = findtext(body, 'result', GENERAL_NS)\n return result == 'SUCCESS'\n ", "context": "class OpsourceNodeDriver(NodeDriver):\n def ex_shutdown_graceful(self, node): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def list_networks(self, location=None): ...\n def _to_base_images(self, object): ...\n def _to_base_image(self, element): ...\n def ex_start_node(self, node): ...\n def ex_power_off(self, node): ...\n def ex_list_networks(self): ...\n def ex_get_location_by_id(self, id): ...\n def _to_networks(self, object): ...\n def _to_network(self, element): ...\n def _to_locations(self, object): ...\n def _to_location(self, element): ...\n def _to_nodes(self, object): ...\n def _to_node(self, element): ...\n def _to_status(self, element): ...\n\n connectionCls = OpsourceConnection\n name = 'Opsource'\n website = 'http://www.opsource.net/'\n type = Provider.OPSOURCE\n features = {'create_node': ['password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_shutdown_graceful", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0], "pynose_source_file": "test_000734.py"} {"focal_file": "libcloud/compute/drivers/opsource.py", "focal_class": null, "focal_method": "ex_start_node", "tests": "import unittest\n\nclass Test_ex_start_node(unittest.TestCase):\n def test_ex_start_node(self):\n node = Node(id='11', name=None, state=None, public_ips=None, private_ips=None, driver=self.driver)\n ret = self.driver.ex_start_node(node)\n self.assertTrue(ret is True)\n\n def test_ex_start_node_INPROGRESS(self):\n OpsourceMockHttp.type = 'INPROGRESS'\n node = Node(id='11', name=None, state=None, public_ips=None, private_ips=None, driver=self.driver)\n try:\n self.driver.ex_start_node(node)\n self.assertTrue(False)\n except OpsourceAPIException:\n self.assertTrue(True)\n", "method_code": " def ex_start_node(self, node):\n \"\"\"\n Powers on an existing deployed server\n \n @param node: Node which should be used\n @type node: L{Node}\n \n @rtype: C{bool}\n \"\"\"\n body = self.connection.request_with_orgId('server/%s?start' % node.id).object\n result = findtext(body, 'result', GENERAL_NS)\n return result == 'SUCCESS'\n ", "context": "class OpsourceNodeDriver(NodeDriver):\n def ex_start_node(self, node): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def list_networks(self, location=None): ...\n def _to_base_images(self, object): ...\n def _to_base_image(self, element): ...\n def ex_shutdown_graceful(self, node): ...\n def ex_power_off(self, node): ...\n def ex_list_networks(self): ...\n def ex_get_location_by_id(self, id): ...\n def _to_networks(self, object): ...\n def _to_network(self, element): ...\n def _to_locations(self, object): ...\n def _to_location(self, element): ...\n def _to_nodes(self, object): ...\n def _to_node(self, element): ...\n def _to_status(self, element): ...\n\n connectionCls = OpsourceConnection\n name = 'Opsource'\n website = 'http://www.opsource.net/'\n type = Provider.OPSOURCE\n features = {'create_node': ['password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_start_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0], "pynose_source_file": "test_000735.py"} {"focal_file": "libcloud/compute/drivers/opsource.py", "focal_class": null, "focal_method": "ex_power_off", "tests": "import unittest\n\nclass Test_ex_power_off(unittest.TestCase):\n def test_ex_power_off(self):\n node = Node(id='11', name=None, state=None, public_ips=None, private_ips=None, driver=self.driver)\n ret = self.driver.ex_power_off(node)\n self.assertTrue(ret is True)\n", "method_code": " def ex_power_off(self, node):\n \"\"\"\n This function will abruptly power-off a server. Unlike\n ex_shutdown_graceful, success ensures the node will stop but some OS\n and application configurations may be adversely affected by the\n equivalent of pulling the power plug out of the machine.\n \n @param node: Node which should be used\n @type node: L{Node}\n \n @rtype: C{bool}\n \"\"\"\n body = self.connection.request_with_orgId('server/%s?poweroff' % node.id).object\n result = findtext(body, 'result', GENERAL_NS)\n return result == 'SUCCESS'\n ", "context": "class OpsourceNodeDriver(NodeDriver):\n def ex_power_off(self, node): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def list_networks(self, location=None): ...\n def _to_base_images(self, object): ...\n def _to_base_image(self, element): ...\n def ex_start_node(self, node): ...\n def ex_shutdown_graceful(self, node): ...\n def ex_list_networks(self): ...\n def ex_get_location_by_id(self, id): ...\n def _to_networks(self, object): ...\n def _to_network(self, element): ...\n def _to_locations(self, object): ...\n def _to_location(self, element): ...\n def _to_nodes(self, object): ...\n def _to_node(self, element): ...\n def _to_status(self, element): ...\n\n connectionCls = OpsourceConnection\n name = 'Opsource'\n website = 'http://www.opsource.net/'\n type = Provider.OPSOURCE\n features = {'create_node': ['password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_power_off", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000736.py"} {"focal_file": "libcloud/compute/drivers/opsource.py", "focal_class": null, "focal_method": "ex_list_networks", "tests": "import unittest\n\nclass Test_ex_list_networks(unittest.TestCase):\n def test_ex_list_networks(self):\n nets = self.driver.ex_list_networks()\n self.assertEqual(nets[0].name, 'test-net1')\n self.assertTrue(isinstance(nets[0].location, NodeLocation))\n", "method_code": " def ex_list_networks(self):\n \"\"\"\n List networks deployed across all data center locations for your\n organization. The response includes the location of each network.\n \n @return: a list of OpsourceNetwork objects\n @rtype: C{list} of L{OpsourceNetwork}\n \"\"\"\n response = self.connection.request_with_orgId('networkWithLocation').object\n return self._to_networks(response)\n ", "context": "class OpsourceNodeDriver(NodeDriver):\n def ex_list_networks(self): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def list_networks(self, location=None): ...\n def _to_base_images(self, object): ...\n def _to_base_image(self, element): ...\n def ex_start_node(self, node): ...\n def ex_shutdown_graceful(self, node): ...\n def ex_power_off(self, node): ...\n def ex_get_location_by_id(self, id): ...\n def _to_networks(self, object): ...\n def _to_network(self, element): ...\n def _to_locations(self, object): ...\n def _to_location(self, element): ...\n def _to_nodes(self, object): ...\n def _to_node(self, element): ...\n def _to_status(self, element): ...\n\n connectionCls = OpsourceConnection\n name = 'Opsource'\n website = 'http://www.opsource.net/'\n type = Provider.OPSOURCE\n features = {'create_node': ['password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_list_networks", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000737.py"} {"focal_file": "libcloud/compute/drivers/rimuhosting.py", "focal_class": null, "focal_method": "list_nodes", "tests": "import unittest\n\nclass Test_list_nodes(unittest.TestCase):\n def test_list_nodes(self):\n nodes = self.driver.list_nodes()\n self.assertEqual(len(nodes), 1)\n node = nodes[0]\n self.assertEqual(node.public_ips[0], '1.2.3.4')\n self.assertEqual(node.public_ips[1], '1.2.3.5')\n self.assertEqual(node.extra['order_oid'], 88833465)\n self.assertEqual(node.id, 'order-88833465-api-ivan-net-nz')\n", "method_code": " def list_nodes(self):\n res = self.connection.request('/orders;include_inactive=N').object\n return list(map(lambda x: self._to_node(x), res['about_orders']))\n ", "context": "class RimuHostingNodeDriver(NodeDriver):\n def list_nodes(self): ...\n def __init__(self, key, host=API_HOST, port=443, api_context=API_CONTEXT, secure=True): ...\n def _order_uri(self, node, resource): ...\n def _to_node(self, order): ...\n def _to_size(self, plan): ...\n def _to_image(self, image): ...\n def list_sizes(self, location=None): ...\n def list_images(self, location=None): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def create_node(self, **kwargs): ...\n def list_locations(self): ...\n\n self.key = key\n self.secure = secure\n self.connection = self.connectionCls(key, secure)\n self.connection.host = host\n self.connection.api_context = api_context\n self.connection.port = port\n self.connection.driver = self\n\n type = Provider.RIMUHOSTING\n name = 'RimuHosting'\n website = 'http://rimuhosting.com/'\n connectionCls = RimuHostingConnection\n features = {'create_node': ['password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_nodes", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000738.py"} {"focal_file": "libcloud/compute/drivers/rimuhosting.py", "focal_class": null, "focal_method": "list_sizes", "tests": "import unittest\n\nclass Test_list_sizes(unittest.TestCase):\n def test_list_sizes(self):\n sizes = self.driver.list_sizes()\n self.assertEqual(len(sizes), 1)\n size = sizes[0]\n self.assertEqual(size.ram, 950)\n self.assertEqual(size.disk, 20)\n self.assertEqual(size.bandwidth, 75)\n self.assertEqual(size.price, 32.54)\n", "method_code": " def list_sizes(self, location=None):\n if location is None:\n location = ''\n else:\n location = ';dc_location=%s' % location.id\n res = self.connection.request('/pricing-plans;server-type=VPS%s' % location).object\n return list(map(lambda x: self._to_size(x), res['pricing_plan_infos']))\n ", "context": "class RimuHostingNodeDriver(NodeDriver):\n def list_sizes(self, location=None): ...\n def __init__(self, key, host=API_HOST, port=443, api_context=API_CONTEXT, secure=True): ...\n def _order_uri(self, node, resource): ...\n def _to_node(self, order): ...\n def _to_size(self, plan): ...\n def _to_image(self, image): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def create_node(self, **kwargs): ...\n def list_locations(self): ...\n\n self.key = key\n self.secure = secure\n self.connection = self.connectionCls(key, secure)\n self.connection.host = host\n self.connection.api_context = api_context\n self.connection.port = port\n self.connection.driver = self\n\n type = Provider.RIMUHOSTING\n name = 'RimuHosting'\n website = 'http://rimuhosting.com/'\n connectionCls = RimuHostingConnection\n features = {'create_node': ['password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_sizes", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000739.py"} {"focal_file": "libcloud/compute/drivers/rimuhosting.py", "focal_class": null, "focal_method": "list_images", "tests": "import unittest\n\nclass Test_list_images(unittest.TestCase):\n def test_list_images(self):\n images = self.driver.list_images()\n self.assertEqual(len(images), 6)\n image = images[0]\n self.assertEqual(image.name, 'Debian 5.0 (aka Lenny, RimuHosting recommended distro)')\n self.assertEqual(image.id, 'lenny')\n", "method_code": " def list_images(self, location=None):\n res = self.connection.request('/distributions').object\n return list(map(lambda x: self._to_image(x), res['distro_infos']))\n ", "context": "class RimuHostingNodeDriver(NodeDriver):\n def list_images(self, location=None): ...\n def __init__(self, key, host=API_HOST, port=443, api_context=API_CONTEXT, secure=True): ...\n def _order_uri(self, node, resource): ...\n def _to_node(self, order): ...\n def _to_size(self, plan): ...\n def _to_image(self, image): ...\n def list_sizes(self, location=None): ...\n def list_nodes(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def create_node(self, **kwargs): ...\n def list_locations(self): ...\n\n self.key = key\n self.secure = secure\n self.connection = self.connectionCls(key, secure)\n self.connection.host = host\n self.connection.api_context = api_context\n self.connection.port = port\n self.connection.driver = self\n\n type = Provider.RIMUHOSTING\n name = 'RimuHosting'\n website = 'http://rimuhosting.com/'\n connectionCls = RimuHostingConnection\n features = {'create_node': ['password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_images", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000740.py"} {"focal_file": "libcloud/compute/drivers/rimuhosting.py", "focal_class": null, "focal_method": "reboot_node", "tests": "import unittest\n\nclass Test_reboot_node(unittest.TestCase):\n def test_reboot_node(self):\n node = self.driver.list_nodes()[0]\n self.driver.reboot_node(node)\n", "method_code": " def reboot_node(self, node):\n data = {'reboot_request': {'running_state': 'RESTARTING'}}\n uri = self._order_uri(node, 'vps/running-state')\n self.connection.request(uri, data=json.dumps(data), method='PUT')\n return True\n ", "context": "class RimuHostingNodeDriver(NodeDriver):\n def reboot_node(self, node): ...\n def __init__(self, key, host=API_HOST, port=443, api_context=API_CONTEXT, secure=True): ...\n def _order_uri(self, node, resource): ...\n def _to_node(self, order): ...\n def _to_size(self, plan): ...\n def _to_image(self, image): ...\n def list_sizes(self, location=None): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def destroy_node(self, node): ...\n def create_node(self, **kwargs): ...\n def list_locations(self): ...\n\n self.key = key\n self.secure = secure\n self.connection = self.connectionCls(key, secure)\n self.connection.host = host\n self.connection.api_context = api_context\n self.connection.port = port\n self.connection.driver = self\n\n type = Provider.RIMUHOSTING\n name = 'RimuHosting'\n website = 'http://rimuhosting.com/'\n connectionCls = RimuHostingConnection\n features = {'create_node': ['password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_reboot_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000741.py"} {"focal_file": "libcloud/compute/drivers/rimuhosting.py", "focal_class": null, "focal_method": "destroy_node", "tests": "import unittest\n\nclass Test_destroy_node(unittest.TestCase):\n def test_destroy_node(self):\n node = self.driver.list_nodes()[0]\n self.driver.destroy_node(node)\n", "method_code": " def destroy_node(self, node):\n uri = self._order_uri(node, 'vps')\n self.connection.request(uri, method='DELETE')\n return True\n ", "context": "class RimuHostingNodeDriver(NodeDriver):\n def destroy_node(self, node): ...\n def __init__(self, key, host=API_HOST, port=443, api_context=API_CONTEXT, secure=True): ...\n def _order_uri(self, node, resource): ...\n def _to_node(self, order): ...\n def _to_size(self, plan): ...\n def _to_image(self, image): ...\n def list_sizes(self, location=None): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def reboot_node(self, node): ...\n def create_node(self, **kwargs): ...\n def list_locations(self): ...\n\n self.key = key\n self.secure = secure\n self.connection = self.connectionCls(key, secure)\n self.connection.host = host\n self.connection.api_context = api_context\n self.connection.port = port\n self.connection.driver = self\n\n type = Provider.RIMUHOSTING\n name = 'RimuHosting'\n website = 'http://rimuhosting.com/'\n connectionCls = RimuHostingConnection\n features = {'create_node': ['password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_destroy_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000742.py"} {"focal_file": "libcloud/compute/drivers/rimuhosting.py", "focal_class": null, "focal_method": "create_node", "tests": "import unittest\n\nclass Test_create_node(unittest.TestCase):\n def test_create_node(self):\n size = self.driver.list_sizes()[0]\n image = self.driver.list_images()[0]\n self.driver.create_node(name='api.ivan.net.nz', image=image, size=size)\n", "method_code": " def create_node(self, **kwargs):\n \"\"\"Creates a RimuHosting instance\n \n @inherits: L{NodeDriver.create_node}\n \n @keyword name: Must be a FQDN. e.g example.com.\n @type name: C{str}\n \n @keyword ex_billing_oid: If not set,\n a billing method is automatically picked.\n @type ex_billing_oid: C{str}\n \n @keyword ex_host_server_oid: The host server to set the VPS up on.\n @type ex_host_server_oid: C{str}\n \n @keyword ex_vps_order_oid_to_clone: Clone another VPS to use as\n the image for the new VPS.\n @type ex_vps_order_oid_to_clone: C{str}\n \n @keyword ex_num_ips: Number of IPs to allocate. Defaults to 1.\n @type ex_num_ips: C{int}\n \n @keyword ex_extra_ip_reason: Reason for needing the extra IPs.\n @type ex_extra_ip_reason: C{str}\n \n @keyword ex_memory_mb: Memory to allocate to the VPS.\n @type ex_memory_mb: C{int}\n \n @keyword ex_disk_space_mb: Diskspace to allocate to the VPS.\n Defaults to 4096 (4GB).\n @type ex_disk_space_mb: C{int}\n \n @keyword ex_disk_space_2_mb: Secondary disk size allocation.\n Disabled by default.\n @type ex_disk_space_2_mb: C{int}\n \n @keyword ex_control_panel: Control panel to install on the VPS.\n @type ex_control_panel: C{str}\n \"\"\"\n name = kwargs['name']\n image = kwargs['image']\n size = kwargs['size']\n data = {'instantiation_options': {'domain_name': name, 'distro': image.id}, 'pricing_plan_code': size.id}\n if 'ex_control_panel' in kwargs:\n data['instantiation_options']['control_panel'] = kwargs['ex_control_panel']\n if 'auth' in kwargs:\n auth = kwargs['auth']\n if not isinstance(auth, NodeAuthPassword):\n raise ValueError('auth must be of NodeAuthPassword type')\n data['instantiation_options']['password'] = auth.password\n if 'ex_billing_oid' in kwargs:\n data['billing_oid'] = kwargs['ex_billing_oid']\n if 'ex_host_server_oid' in kwargs:\n data['host_server_oid'] = kwargs['ex_host_server_oid']\n if 'ex_vps_order_oid_to_clone' in kwargs:\n data['vps_order_oid_to_clone'] = kwargs['ex_vps_order_oid_to_clone']\n if 'ex_num_ips' in kwargs and int(kwargs['ex_num_ips']) > 1:\n if not 'ex_extra_ip_reason' in kwargs:\n raise RimuHostingException('Need an reason for having an extra IP')\n else:\n if not 'ip_request' in data:\n data['ip_request'] = {}\n data['ip_request']['num_ips'] = int(kwargs['ex_num_ips'])\n data['ip_request']['extra_ip_reason'] = kwargs['ex_extra_ip_reason']\n if 'ex_memory_mb' in kwargs:\n if not 'vps_parameters' in data:\n data['vps_parameters'] = {}\n data['vps_parameters']['memory_mb'] = kwargs['ex_memory_mb']\n if 'ex_disk_space_mb' in kwargs:\n if not 'ex_vps_parameters' in data:\n data['vps_parameters'] = {}\n data['vps_parameters']['disk_space_mb'] = kwargs['ex_disk_space_mb']\n if 'ex_disk_space_2_mb' in kwargs:\n if not 'vps_parameters' in data:\n data['vps_parameters'] = {}\n data['vps_parameters']['disk_space_2_mb'] = kwargs['ex_disk_space_2_mb']\n res = self.connection.request('/orders/new-vps', method='POST', data=json.dumps({'new-vps': data})).object\n node = self._to_node(res['about_order'])\n node.extra['password'] = res['new_order_request']['instantiation_options']['password']\n return node\n ", "context": "class RimuHostingNodeDriver(NodeDriver):\n def create_node(self, **kwargs): ...\n def __init__(self, key, host=API_HOST, port=443, api_context=API_CONTEXT, secure=True): ...\n def _order_uri(self, node, resource): ...\n def _to_node(self, order): ...\n def _to_size(self, plan): ...\n def _to_image(self, image): ...\n def list_sizes(self, location=None): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def list_locations(self): ...\n\n self.key = key\n self.secure = secure\n self.connection = self.connectionCls(key, secure)\n self.connection.host = host\n self.connection.api_context = api_context\n self.connection.port = port\n self.connection.driver = self\n\n type = Provider.RIMUHOSTING\n name = 'RimuHosting'\n website = 'http://rimuhosting.com/'\n connectionCls = RimuHostingConnection\n features = {'create_node': ['password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000743.py"} {"focal_file": "libcloud/compute/drivers/slicehost.py", "focal_class": null, "focal_method": "list_nodes", "tests": "import unittest\n\nclass Test_list_nodes(unittest.TestCase):\n def test_list_nodes(self):\n ret = self.driver.list_nodes()\n self.assertEqual(len(ret), 1)\n node = ret[0]\n self.assertTrue('174.143.212.229' in node.public_ips)\n self.assertTrue('10.176.164.199' in node.private_ips)\n self.assertEqual(node.state, NodeState.PENDING)\n SlicehostMockHttp.type = 'UNAUTHORIZED'\n try:\n ret = self.driver.list_nodes()\n except InvalidCredsError:\n e = sys.exc_info()[1]\n self.assertEqual(e.value, 'HTTP Basic: Access denied.')\n else:\n self.fail('test should have thrown')\n", "method_code": " def list_nodes(self):\n return self._to_nodes(self.connection.request('/slices.xml').object)\n ", "context": "class SlicehostNodeDriver(NodeDriver):\n def list_nodes(self): ...\n def list_sizes(self, location=None): ...\n def list_images(self, location=None): ...\n def list_locations(self): ...\n def create_node(self, **kwargs): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def _to_nodes(self, object): ...\n def _to_node(self, element): ...\n def _to_sizes(self, object): ...\n def _to_size(self, element): ...\n def _to_images(self, object): ...\n def _to_image(self, element): ...\n\n connectionCls = SlicehostConnection\n type = Provider.SLICEHOST\n name = 'Slicehost'\n website = 'http://slicehost.com/'\n features = {'create_node': ['generates_password']}\n NODE_STATE_MAP = {'active': NodeState.RUNNING, 'build': NodeState.PENDING, 'reboot': NodeState.REBOOTING, 'hard_reboot': NodeState.REBOOTING, 'terminated': NodeState.TERMINATED}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_nodes", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000744.py"} {"focal_file": "libcloud/compute/drivers/slicehost.py", "focal_class": null, "focal_method": "list_sizes", "tests": "import unittest\n\nclass Test_list_sizes(unittest.TestCase):\n def test_list_sizes(self):\n ret = self.driver.list_sizes()\n self.assertEqual(len(ret), 7)\n size = ret[0]\n self.assertEqual(size.name, '256 slice')\n", "method_code": " def list_sizes(self, location=None):\n return self._to_sizes(self.connection.request('/flavors.xml').object)\n ", "context": "class SlicehostNodeDriver(NodeDriver):\n def list_sizes(self, location=None): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def list_locations(self): ...\n def create_node(self, **kwargs): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def _to_nodes(self, object): ...\n def _to_node(self, element): ...\n def _to_sizes(self, object): ...\n def _to_size(self, element): ...\n def _to_images(self, object): ...\n def _to_image(self, element): ...\n\n connectionCls = SlicehostConnection\n type = Provider.SLICEHOST\n name = 'Slicehost'\n website = 'http://slicehost.com/'\n features = {'create_node': ['generates_password']}\n NODE_STATE_MAP = {'active': NodeState.RUNNING, 'build': NodeState.PENDING, 'reboot': NodeState.REBOOTING, 'hard_reboot': NodeState.REBOOTING, 'terminated': NodeState.TERMINATED}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_sizes", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000745.py"} {"focal_file": "libcloud/compute/drivers/slicehost.py", "focal_class": null, "focal_method": "list_images", "tests": "import unittest\n\nclass Test_list_images(unittest.TestCase):\n def test_list_images(self):\n ret = self.driver.list_images()\n self.assertEqual(len(ret), 11)\n image = ret[0]\n self.assertEqual(image.name, 'CentOS 5.2')\n self.assertEqual(image.id, '2')\n", "method_code": " def list_images(self, location=None):\n return self._to_images(self.connection.request('/images.xml').object)\n ", "context": "class SlicehostNodeDriver(NodeDriver):\n def list_images(self, location=None): ...\n def list_nodes(self): ...\n def list_sizes(self, location=None): ...\n def list_locations(self): ...\n def create_node(self, **kwargs): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def _to_nodes(self, object): ...\n def _to_node(self, element): ...\n def _to_sizes(self, object): ...\n def _to_size(self, element): ...\n def _to_images(self, object): ...\n def _to_image(self, element): ...\n\n connectionCls = SlicehostConnection\n type = Provider.SLICEHOST\n name = 'Slicehost'\n website = 'http://slicehost.com/'\n features = {'create_node': ['generates_password']}\n NODE_STATE_MAP = {'active': NodeState.RUNNING, 'build': NodeState.PENDING, 'reboot': NodeState.REBOOTING, 'hard_reboot': NodeState.REBOOTING, 'terminated': NodeState.TERMINATED}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_images", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000746.py"} {"focal_file": "libcloud/compute/drivers/slicehost.py", "focal_class": null, "focal_method": "reboot_node", "tests": "import unittest\n\nclass Test_reboot_node(unittest.TestCase):\n def test_reboot_node(self):\n node = Node(id=1, name=None, state=None, public_ips=None, private_ips=None, driver=self.driver)\n ret = node.reboot()\n self.assertTrue(ret is True)\n ret = self.driver.reboot_node(node)\n self.assertTrue(ret is True)\n SlicehostMockHttp.type = 'FORBIDDEN'\n try:\n ret = self.driver.reboot_node(node)\n except Exception:\n e = sys.exc_info()[1]\n self.assertEqual(e.args[0], 'Permission denied')\n else:\n self.fail('test should have thrown')\n", "method_code": " def reboot_node(self, node):\n uri = '/slices/%s/reboot.xml' % node.id\n node = self._to_nodes(self.connection.request(uri, method='PUT').object)[0]\n return node.state == NodeState.REBOOTING\n ", "context": "class SlicehostNodeDriver(NodeDriver):\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def list_sizes(self, location=None): ...\n def list_images(self, location=None): ...\n def list_locations(self): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def _to_nodes(self, object): ...\n def _to_node(self, element): ...\n def _to_sizes(self, object): ...\n def _to_size(self, element): ...\n def _to_images(self, object): ...\n def _to_image(self, element): ...\n\n connectionCls = SlicehostConnection\n type = Provider.SLICEHOST\n name = 'Slicehost'\n website = 'http://slicehost.com/'\n features = {'create_node': ['generates_password']}\n NODE_STATE_MAP = {'active': NodeState.RUNNING, 'build': NodeState.PENDING, 'reboot': NodeState.REBOOTING, 'hard_reboot': NodeState.REBOOTING, 'terminated': NodeState.TERMINATED}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_reboot_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000747.py"} {"focal_file": "libcloud/compute/drivers/slicehost.py", "focal_class": null, "focal_method": "destroy_node", "tests": "import unittest\n\nclass Test_destroy_node(unittest.TestCase):\n def test_destroy_node(self):\n node = Node(id=1, name=None, state=None, public_ips=None, private_ips=None, driver=self.driver)\n ret = node.destroy()\n self.assertTrue(ret is True)\n ret = self.driver.destroy_node(node)\n self.assertTrue(ret is True)\n", "method_code": " def destroy_node(self, node):\n \"\"\"Destroys the node\n \n Requires 'Allow Slices to be deleted or rebuilt from the API' to be\n ticked at https://manage.slicehost.com/api, otherwise returns::\n \n You must enable slice deletes in the SliceManager\n Permission denied\n \n \n @inherits: L{NodeDriver.destroy_node}\n \"\"\"\n uri = '/slices/%s/destroy.xml' % node.id\n self.connection.request(uri, method='PUT')\n return True\n ", "context": "class SlicehostNodeDriver(NodeDriver):\n def destroy_node(self, node): ...\n def list_nodes(self): ...\n def list_sizes(self, location=None): ...\n def list_images(self, location=None): ...\n def list_locations(self): ...\n def create_node(self, **kwargs): ...\n def reboot_node(self, node): ...\n def _to_nodes(self, object): ...\n def _to_node(self, element): ...\n def _to_sizes(self, object): ...\n def _to_size(self, element): ...\n def _to_images(self, object): ...\n def _to_image(self, element): ...\n\n connectionCls = SlicehostConnection\n type = Provider.SLICEHOST\n name = 'Slicehost'\n website = 'http://slicehost.com/'\n features = {'create_node': ['generates_password']}\n NODE_STATE_MAP = {'active': NodeState.RUNNING, 'build': NodeState.PENDING, 'reboot': NodeState.REBOOTING, 'hard_reboot': NodeState.REBOOTING, 'terminated': NodeState.TERMINATED}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_destroy_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000748.py"} {"focal_file": "libcloud/compute/drivers/slicehost.py", "focal_class": null, "focal_method": "create_node", "tests": "import unittest\n\nclass Test_create_node(unittest.TestCase):\n def test_create_node(self):\n image = NodeImage(id=11, name='ubuntu 8.10', driver=self.driver)\n size = NodeSize(1, '256 slice', None, None, None, None, driver=self.driver)\n node = self.driver.create_node(name='slicetest', image=image, size=size)\n self.assertEqual(node.name, 'slicetest')\n self.assertEqual(node.extra.get('password'), 'fooadfa1231')\n", "method_code": " def create_node(self, **kwargs):\n name = kwargs['name']\n image = kwargs['image']\n size = kwargs['size']\n uri = '/slices.xml'\n root = ET.Element('slice')\n el_name = ET.SubElement(root, 'name')\n el_name.text = name\n flavor_id = ET.SubElement(root, 'flavor-id')\n flavor_id.text = str(size.id)\n image_id = ET.SubElement(root, 'image-id')\n image_id.text = str(image.id)\n xml = ET.tostring(root)\n node = self._to_nodes(self.connection.request(uri, method='POST', data=xml, headers={'Content-Type': 'application/xml'}).object)[0]\n return node\n ", "context": "class SlicehostNodeDriver(NodeDriver):\n def create_node(self, **kwargs): ...\n def list_nodes(self): ...\n def list_sizes(self, location=None): ...\n def list_images(self, location=None): ...\n def list_locations(self): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def _to_nodes(self, object): ...\n def _to_node(self, element): ...\n def _to_sizes(self, object): ...\n def _to_size(self, element): ...\n def _to_images(self, object): ...\n def _to_image(self, element): ...\n\n connectionCls = SlicehostConnection\n type = Provider.SLICEHOST\n name = 'Slicehost'\n website = 'http://slicehost.com/'\n features = {'create_node': ['generates_password']}\n NODE_STATE_MAP = {'active': NodeState.RUNNING, 'build': NodeState.PENDING, 'reboot': NodeState.REBOOTING, 'hard_reboot': NodeState.REBOOTING, 'terminated': NodeState.TERMINATED}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000749.py"} {"focal_file": "libcloud/compute/drivers/softlayer.py", "focal_class": null, "focal_method": "list_nodes", "tests": "import unittest\n\nclass Test_list_nodes(unittest.TestCase):\n def test_list_nodes(self):\n node = self.driver.list_nodes()[0]\n self.assertEqual(node.name, 'test1')\n self.assertEqual(node.state, NodeState.RUNNING)\n self.assertEqual(node.extra['password'], 'TEST')\n", "method_code": " def list_nodes(self):\n mask = {'virtualGuests': {'powerState': '', 'operatingSystem': {'passwords': ''}, 'billingItem': ''}}\n res = self.connection.request('SoftLayer_Account', 'getVirtualGuests', object_mask=mask).object\n return [self._to_node(h) for h in res]\n ", "context": "class SoftLayerNodeDriver(NodeDriver):\n def list_nodes(self): ...\n def _to_node(self, host): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def _get_order_information(self, node_id, timeout=1200, check_interval=5): ...\n def create_node(self, **kwargs): ...\n def _to_image(self, img): ...\n def list_images(self, location=None): ...\n def _to_size(self, id, size): ...\n def list_sizes(self, location=None): ...\n def _to_loc(self, loc): ...\n def list_locations(self): ...\n\n connectionCls = SoftLayerConnection\n name = 'SoftLayer'\n website = 'http://www.softlayer.com/'\n type = Provider.SOFTLAYER\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_nodes", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000750.py"} {"focal_file": "libcloud/compute/drivers/softlayer.py", "focal_class": null, "focal_method": "list_locations", "tests": "import unittest\n\nclass Test_list_locations(unittest.TestCase):\n def test_list_locations(self):\n locations = self.driver.list_locations()\n dal = next((l for l in locations if l.id == 'dal05'))\n self.assertEqual(dal.country, 'US')\n self.assertEqual(dal.id, 'dal05')\n self.assertEqual(dal.name, 'Dallas 5')\n", "method_code": " def list_locations(self):\n res = self.connection.request('SoftLayer_Location_Datacenter', 'getDatacenters').object\n return [self._to_loc(l) for l in res]\n ", "context": "class SoftLayerNodeDriver(NodeDriver):\n def list_locations(self): ...\n def _to_node(self, host): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def _get_order_information(self, node_id, timeout=1200, check_interval=5): ...\n def create_node(self, **kwargs): ...\n def _to_image(self, img): ...\n def list_images(self, location=None): ...\n def _to_size(self, id, size): ...\n def list_sizes(self, location=None): ...\n def _to_loc(self, loc): ...\n def list_nodes(self): ...\n\n connectionCls = SoftLayerConnection\n name = 'SoftLayer'\n website = 'http://www.softlayer.com/'\n type = Provider.SOFTLAYER\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_locations", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000751.py"} {"focal_file": "libcloud/compute/drivers/softlayer.py", "focal_class": null, "focal_method": "list_images", "tests": "import unittest\n\nclass Test_list_images(unittest.TestCase):\n def test_list_images(self):\n images = self.driver.list_images()\n image = images[0]\n self.assertEqual(image.id, 'CENTOS_6_64')\n", "method_code": " def list_images(self, location=None):\n result = self.connection.request('SoftLayer_Virtual_Guest', 'getCreateObjectOptions').object\n return [self._to_image(i) for i in result['operatingSystems']]\n ", "context": "class SoftLayerNodeDriver(NodeDriver):\n def list_images(self, location=None): ...\n def _to_node(self, host): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def _get_order_information(self, node_id, timeout=1200, check_interval=5): ...\n def create_node(self, **kwargs): ...\n def _to_image(self, img): ...\n def _to_size(self, id, size): ...\n def list_sizes(self, location=None): ...\n def _to_loc(self, loc): ...\n def list_locations(self): ...\n def list_nodes(self): ...\n\n connectionCls = SoftLayerConnection\n name = 'SoftLayer'\n website = 'http://www.softlayer.com/'\n type = Provider.SOFTLAYER\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_images", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000752.py"} {"focal_file": "libcloud/compute/drivers/softlayer.py", "focal_class": null, "focal_method": "list_sizes", "tests": "import unittest\n\nclass Test_list_sizes(unittest.TestCase):\n def test_list_sizes(self):\n sizes = self.driver.list_sizes()\n self.assertEqual(len(sizes), 10)\n size = [s for s in sizes if s.id == 'sl2_local_disk']\n self.assertEqual(len(size), 1)\n", "method_code": " def list_sizes(self, location=None):\n return [self._to_size(id, s) for id, s in SL_TEMPLATES.items()]\n ", "context": "class SoftLayerNodeDriver(NodeDriver):\n def list_sizes(self, location=None): ...\n def _to_node(self, host): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def _get_order_information(self, node_id, timeout=1200, check_interval=5): ...\n def create_node(self, **kwargs): ...\n def _to_image(self, img): ...\n def list_images(self, location=None): ...\n def _to_size(self, id, size): ...\n def _to_loc(self, loc): ...\n def list_locations(self): ...\n def list_nodes(self): ...\n\n connectionCls = SoftLayerConnection\n name = 'SoftLayer'\n website = 'http://www.softlayer.com/'\n type = Provider.SOFTLAYER\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_sizes", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000753.py"} {"focal_file": "libcloud/compute/drivers/softlayer.py", "focal_class": null, "focal_method": "create_node", "tests": "import unittest\n\nclass Test_create_node(unittest.TestCase):\n def test_create_node(self):\n self.driver.create_node(name='Test', location=self.driver.list_locations()[0], size=self.driver.list_sizes()[0], image=self.driver.list_images()[0])\n\n def test_create_node_san(self):\n size = [s for s in self.driver.list_sizes() if 'san' in s.id][0]\n self.driver.create_node(name='Test', size=size)\n", "method_code": " def create_node(self, **kwargs):\n \"\"\"Create a new SoftLayer node\n \n @inherits: L{NodeDriver.create_node}\n \n @keyword ex_domain: e.g. libcloud.org\n @type ex_domain: C{str}\n @keyword ex_cpus: e.g. 2\n @type ex_cpus: C{int}\n @keyword ex_disk: e.g. 100\n @type ex_disk: C{int}\n @keyword ex_ram: e.g. 2048\n @type ex_ram: C{int}\n @keyword ex_bandwidth: e.g. 100\n @type ex_bandwidth: C{int}\n @keyword ex_local_disk: e.g. True\n @type ex_local_disk: C{bool}\n @keyword ex_datacenter: e.g. Dal05\n @type ex_datacenter: C{str}\n @keyword ex_os: e.g. UBUNTU_LATEST\n @type ex_os: C{str}\n \"\"\"\n name = kwargs['name']\n os = 'DEBIAN_LATEST'\n if 'ex_os' in kwargs:\n os = kwargs['ex_os']\n elif 'image' in kwargs:\n os = kwargs['image'].id\n size = kwargs.get('size', NodeSize(id=None, name='Custom', ram=None, disk=None, bandwidth=None, price=None, driver=self.connection.driver))\n ex_size_data = SL_TEMPLATES.get(size.id) or {}\n cpu_count = kwargs.get('ex_cpus') or ex_size_data.get('cpus') or 1\n ram = kwargs.get('ex_ram') or size.ram or 2048\n bandwidth = kwargs.get('ex_bandwidth') or size.bandwidth or 10\n hourly = 'true' if kwargs.get('ex_hourly', True) else 'false'\n local_disk = 'true'\n if ex_size_data.get('local_disk') is False:\n local_disk = 'false'\n if kwargs.get('ex_local_disk') is False:\n local_disk = 'false'\n disk_size = 100\n if size.disk:\n disk_size = size.disk\n if kwargs.get('ex_disk'):\n disk_size = kwargs.get('ex_disk')\n datacenter = ''\n if 'ex_datacenter' in kwargs:\n datacenter = kwargs['ex_datacenter']\n elif 'location' in kwargs:\n datacenter = kwargs['location'].id\n domain = kwargs.get('ex_domain')\n if domain is None:\n if name.find('.') != -1:\n domain = name[name.find('.') + 1:]\n if domain is None:\n domain = 'example.com'\n newCCI = {'hostname': name, 'domain': domain, 'startCpus': cpu_count, 'maxMemory': ram, 'networkComponents': [{'maxSpeed': bandwidth}], 'hourlyBillingFlag': hourly, 'operatingSystemReferenceCode': os, 'localDiskFlag': local_disk, 'blockDevices': [{'device': '0', 'diskImage': {'capacity': disk_size}}]}\n if datacenter:\n newCCI['datacenter'] = {'name': datacenter}\n res = self.connection.request('SoftLayer_Virtual_Guest', 'createObject', newCCI).object\n node_id = res['id']\n raw_node = self._get_order_information(node_id)\n return self._to_node(raw_node)\n ", "context": "class SoftLayerNodeDriver(NodeDriver):\n def create_node(self, **kwargs): ...\n def _to_node(self, host): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def _get_order_information(self, node_id, timeout=1200, check_interval=5): ...\n def _to_image(self, img): ...\n def list_images(self, location=None): ...\n def _to_size(self, id, size): ...\n def list_sizes(self, location=None): ...\n def _to_loc(self, loc): ...\n def list_locations(self): ...\n def list_nodes(self): ...\n\n connectionCls = SoftLayerConnection\n name = 'SoftLayer'\n website = 'http://www.softlayer.com/'\n type = Provider.SOFTLAYER\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000754.py"} {"focal_file": "libcloud/compute/drivers/softlayer.py", "focal_class": null, "focal_method": "reboot_node", "tests": "import unittest\n\nclass Test_reboot_node(unittest.TestCase):\n def test_reboot_node(self):\n node = self.driver.list_nodes()[0]\n self.driver.reboot_node(node)\n", "method_code": " def reboot_node(self, node):\n self.connection.request('SoftLayer_Virtual_Guest', 'rebootSoft', id=node.id)\n return True\n ", "context": "class SoftLayerNodeDriver(NodeDriver):\n def reboot_node(self, node): ...\n def _to_node(self, host): ...\n def destroy_node(self, node): ...\n def _get_order_information(self, node_id, timeout=1200, check_interval=5): ...\n def create_node(self, **kwargs): ...\n def _to_image(self, img): ...\n def list_images(self, location=None): ...\n def _to_size(self, id, size): ...\n def list_sizes(self, location=None): ...\n def _to_loc(self, loc): ...\n def list_locations(self): ...\n def list_nodes(self): ...\n\n connectionCls = SoftLayerConnection\n name = 'SoftLayer'\n website = 'http://www.softlayer.com/'\n type = Provider.SOFTLAYER\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_reboot_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000755.py"} {"focal_file": "libcloud/compute/drivers/softlayer.py", "focal_class": null, "focal_method": "destroy_node", "tests": "import unittest\n\nclass Test_destroy_node(unittest.TestCase):\n def test_destroy_node(self):\n node = self.driver.list_nodes()[0]\n self.driver.destroy_node(node)\n", "method_code": " def destroy_node(self, node):\n self.connection.request('SoftLayer_Virtual_Guest', 'deleteObject', id=node.id)\n return True\n ", "context": "class SoftLayerNodeDriver(NodeDriver):\n def destroy_node(self, node): ...\n def _to_node(self, host): ...\n def reboot_node(self, node): ...\n def _get_order_information(self, node_id, timeout=1200, check_interval=5): ...\n def create_node(self, **kwargs): ...\n def _to_image(self, img): ...\n def list_images(self, location=None): ...\n def _to_size(self, id, size): ...\n def list_sizes(self, location=None): ...\n def _to_loc(self, loc): ...\n def list_locations(self): ...\n def list_nodes(self): ...\n\n connectionCls = SoftLayerConnection\n name = 'SoftLayer'\n website = 'http://www.softlayer.com/'\n type = Provider.SOFTLAYER\n features = {'create_node': ['generates_password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_destroy_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000756.py"} {"focal_file": "libcloud/compute/ssh.py", "focal_class": "ShellOutSSHClient", "focal_method": "connect", "tests": "import unittest\n\nclass Test_ShellOutSSHClient_connect(unittest.TestCase):\n def test_connect_success(self):\n client = ShellOutSSHClient(hostname='localhost', username='root')\n self.assertTrue(client.connect())\n", "method_code": " def connect(self):\n \"\"\"\n Connect to the remote node over SSH.\n \n @return: True if the connection has been successfuly established, False\n otherwise.\n @rtype: C{bool}\n \"\"\"\n raise NotImplementedError('connect not implemented for this ssh client')\n ", "context": "class BaseSSHClient(object):\n def connect(self): ...\n def __init__(self, hostname, port=22, username='root', password=None, key=None, timeout=None): ...\n def put(self, path, contents=None, chmod=None, mode='w'): ...\n def delete(self, path): ...\n def run(self, cmd): ...\n def close(self): ...\n\n self.hostname = hostname\n self.port = port\n self.username = username\n self.password = password\n self.key = key\n self.timeout = timeout\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_connect_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 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": "libcloud/compute/ssh.py", "focal_class": "ShellOutSSHClient", "focal_method": "_get_base_ssh_command", "tests": "import unittest\n\nclass Test_ShellOutSSHClient_get_base_ssh_command(unittest.TestCase):\n def test_get_base_ssh_command(self):\n client1 = ShellOutSSHClient(hostname='localhost', username='root')\n client2 = ShellOutSSHClient(hostname='localhost', username='root', key='/home/my.key')\n client3 = ShellOutSSHClient(hostname='localhost', username='root', key='/home/my.key', timeout=5)\n cmd1 = client1._get_base_ssh_command()\n cmd2 = client2._get_base_ssh_command()\n cmd3 = client3._get_base_ssh_command()\n self.assertEquals(cmd1, ['ssh', 'root@localhost'])\n self.assertEquals(cmd2, ['ssh', '-i', '/home/my.key', 'root@localhost'])\n self.assertEquals(cmd3, ['ssh', '-i', '/home/my.key', '-oConnectTimeout=5', 'root@localhost'])\n", "method_code": " def _get_base_ssh_command(self):\n cmd = ['ssh']\n if self.key:\n cmd += ['-i', self.key]\n if self.timeout:\n cmd += ['-oConnectTimeout=%s' % self.timeout]\n cmd += ['%s@%s' % (self.username, self.hostname)]\n return cmd\n ", "context": "class ShellOutSSHClient(BaseSSHClient):\n def _get_base_ssh_command(self): ...\n def __init__(self, hostname, port=22, username='root', password=None, key=None, timeout=None): ...\n def connect(self): ...\n def run(self, cmd): ...\n def put(self, path, contents=None, chmod=None, mode='w'): ...\n def delete(self, path): ...\n def close(self): ...\n def _get_and_setup_logger(self): ...\n def _run_remote_shell_command(self, cmd): ...\n\n self.logger = self._get_and_setup_logger()\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_get_base_ssh_command", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000758.py"} {"focal_file": "libcloud/compute/drivers/vcl.py", "focal_class": null, "focal_method": "list_nodes", "tests": "import unittest\n\nclass Test_list_nodes(unittest.TestCase):\n def test_list_nodes(self):\n node = self.driver.list_nodes(ipaddr='192.168.1.1')[0]\n self.assertEqual(node.name, 'CentOS 5.4 Base (32 bit VM)')\n self.assertEqual(node.state, NodeState.RUNNING)\n self.assertEqual(node.extra['pass'], 'ehkNGW')\n", "method_code": " def list_nodes(self, ipaddr):\n \"\"\"\n List nodes\n \n @param ipaddr: IP address which should be used\n @type ipaddr: C{str}\n \n @rtype: C{list} of L{Node}\n \"\"\"\n res = self._vcl_request('XMLRPCgetRequestIds')\n return self._to_nodes(res['requests'], ipaddr)\n ", "context": "class VCLNodeDriver(NodeDriver):\n def list_nodes(self, ipaddr): ...\n def __init__(self, key, secret, secure=True, host=None, port=None, *args, **kwargs): ...\n def _vcl_request(self, method, *args): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def _to_image(self, img): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def _to_connect_data(self, request_id, ipaddr): ...\n def _to_status(self, requestid, imagename, ipaddr): ...\n def _to_nodes(self, res, ipaddr): ...\n def ex_update_node_access(self, node, ipaddr): ...\n def ex_extend_request_time(self, node, minutes): ...\n def ex_get_request_end_time(self, node): ...\n\n NODE_STATE_MAP = {'ready': NodeState.RUNNING, 'failed': NodeState.TERMINATED, 'timedout': NodeState.TERMINATED, 'loading': NodeState.PENDING, 'time': NodeState.PENDING, 'future': NodeState.PENDING, 'error': NodeState.UNKNOWN, 'notready': NodeState.PENDING, 'notavailable': NodeState.TERMINATED, 'success': NodeState.PENDING}\n connectionCls = VCLConnection\n name = 'VCL'\n website = 'http://incubator.apache.org/vcl/'\n type = Provider.VCL\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_nodes", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000759.py"} {"focal_file": "libcloud/compute/drivers/vcl.py", "focal_class": null, "focal_method": "list_images", "tests": "import unittest\n\nclass Test_list_images(unittest.TestCase):\n def test_list_images(self):\n images = self.driver.list_images()\n image = images[0]\n self.assertEqual(image.id, '8')\n", "method_code": " def list_images(self, location=None):\n \"\"\"\n List images available to the user provided credentials\n \n @inherits: L{NodeDriver.list_images}\n \"\"\"\n res = self.connection.request('XMLRPCgetImages').object\n return [self._to_image(i) for i in res]\n ", "context": "class VCLNodeDriver(NodeDriver):\n def list_images(self, location=None): ...\n def __init__(self, key, secret, secure=True, host=None, port=None, *args, **kwargs): ...\n def _vcl_request(self, method, *args): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def _to_image(self, img): ...\n def list_sizes(self, location=None): ...\n def _to_connect_data(self, request_id, ipaddr): ...\n def _to_status(self, requestid, imagename, ipaddr): ...\n def _to_nodes(self, res, ipaddr): ...\n def list_nodes(self, ipaddr): ...\n def ex_update_node_access(self, node, ipaddr): ...\n def ex_extend_request_time(self, node, minutes): ...\n def ex_get_request_end_time(self, node): ...\n\n NODE_STATE_MAP = {'ready': NodeState.RUNNING, 'failed': NodeState.TERMINATED, 'timedout': NodeState.TERMINATED, 'loading': NodeState.PENDING, 'time': NodeState.PENDING, 'future': NodeState.PENDING, 'error': NodeState.UNKNOWN, 'notready': NodeState.PENDING, 'notavailable': NodeState.TERMINATED, 'success': NodeState.PENDING}\n connectionCls = VCLConnection\n name = 'VCL'\n website = 'http://incubator.apache.org/vcl/'\n type = Provider.VCL\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_images", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000760.py"} {"focal_file": "libcloud/compute/drivers/vcl.py", "focal_class": null, "focal_method": "list_sizes", "tests": "import unittest\n\nclass Test_list_sizes(unittest.TestCase):\n def test_list_sizes(self):\n sizes = self.driver.list_sizes()\n self.assertEqual(len(sizes), 1)\n", "method_code": " def list_sizes(self, location=None):\n \"\"\"\n VCL does not choosing sizes for node creation.\n Size of images are statically set by administrators.\n \n @inherits: L{NodeDriver.list_sizes}\n \"\"\"\n return [NodeSize('t1.micro', 'none', '512', 0, 0, 0, self)]\n ", "context": "class VCLNodeDriver(NodeDriver):\n def list_sizes(self, location=None): ...\n def __init__(self, key, secret, secure=True, host=None, port=None, *args, **kwargs): ...\n def _vcl_request(self, method, *args): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def _to_image(self, img): ...\n def list_images(self, location=None): ...\n def _to_connect_data(self, request_id, ipaddr): ...\n def _to_status(self, requestid, imagename, ipaddr): ...\n def _to_nodes(self, res, ipaddr): ...\n def list_nodes(self, ipaddr): ...\n def ex_update_node_access(self, node, ipaddr): ...\n def ex_extend_request_time(self, node, minutes): ...\n def ex_get_request_end_time(self, node): ...\n\n NODE_STATE_MAP = {'ready': NodeState.RUNNING, 'failed': NodeState.TERMINATED, 'timedout': NodeState.TERMINATED, 'loading': NodeState.PENDING, 'time': NodeState.PENDING, 'future': NodeState.PENDING, 'error': NodeState.UNKNOWN, 'notready': NodeState.PENDING, 'notavailable': NodeState.TERMINATED, 'success': NodeState.PENDING}\n connectionCls = VCLConnection\n name = 'VCL'\n website = 'http://incubator.apache.org/vcl/'\n type = Provider.VCL\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_sizes", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000761.py"} {"focal_file": "libcloud/compute/drivers/vcl.py", "focal_class": null, "focal_method": "create_node", "tests": "import unittest\n\nclass Test_create_node(unittest.TestCase):\n def test_create_node(self):\n image = self.driver.list_images()[0]\n node = self.driver.create_node(image=image)\n self.assertEqual(node.id, '51')\n", "method_code": " def create_node(self, **kwargs):\n \"\"\"Create a new VCL reservation\n size and name ignored, image is the id from list_image\n \n @inherits: L{NodeDriver.create_node}\n \n @keyword image: image is the id from list_image\n @type image: C{str}\n \n @keyword start: start time as unix timestamp\n @type start: C{str}\n \n @keyword length: length of time in minutes\n @type length: C{str}\n \"\"\"\n image = kwargs['image']\n start = kwargs.get('start', int(time.time()))\n length = kwargs.get('length', '60')\n res = self._vcl_request('XMLRPCaddRequest', image.id, start, length)\n return Node(id=res['requestid'], name=image.name, state=self.NODE_STATE_MAP[res['status']], public_ips=[], private_ips=[], driver=self, image=image.name)\n ", "context": "class VCLNodeDriver(NodeDriver):\n def create_node(self, **kwargs): ...\n def __init__(self, key, secret, secure=True, host=None, port=None, *args, **kwargs): ...\n def _vcl_request(self, method, *args): ...\n def destroy_node(self, node): ...\n def _to_image(self, img): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def _to_connect_data(self, request_id, ipaddr): ...\n def _to_status(self, requestid, imagename, ipaddr): ...\n def _to_nodes(self, res, ipaddr): ...\n def list_nodes(self, ipaddr): ...\n def ex_update_node_access(self, node, ipaddr): ...\n def ex_extend_request_time(self, node, minutes): ...\n def ex_get_request_end_time(self, node): ...\n\n NODE_STATE_MAP = {'ready': NodeState.RUNNING, 'failed': NodeState.TERMINATED, 'timedout': NodeState.TERMINATED, 'loading': NodeState.PENDING, 'time': NodeState.PENDING, 'future': NodeState.PENDING, 'error': NodeState.UNKNOWN, 'notready': NodeState.PENDING, 'notavailable': NodeState.TERMINATED, 'success': NodeState.PENDING}\n connectionCls = VCLConnection\n name = 'VCL'\n website = 'http://incubator.apache.org/vcl/'\n type = Provider.VCL\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/compute/drivers/vcl.py", "focal_class": null, "focal_method": "destroy_node", "tests": "import unittest\n\nclass Test_destroy_node(unittest.TestCase):\n def test_destroy_node(self):\n node = self.driver.list_nodes(ipaddr='192.168.1.1')[0]\n self.assertTrue(self.driver.destroy_node(node))\n", "method_code": " def destroy_node(self, node):\n \"\"\"\n End VCL reservation for the node passed in.\n Throws error if request fails.\n \n @param node: The node to be destroyed\n @type node: L{Node}\n \n @rtype: C{bool}\n \"\"\"\n try:\n self._vcl_request('XMLRPCendRequest', node.id)\n except LibcloudError:\n return False\n return True\n ", "context": "class VCLNodeDriver(NodeDriver):\n def destroy_node(self, node): ...\n def __init__(self, key, secret, secure=True, host=None, port=None, *args, **kwargs): ...\n def _vcl_request(self, method, *args): ...\n def create_node(self, **kwargs): ...\n def _to_image(self, img): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def _to_connect_data(self, request_id, ipaddr): ...\n def _to_status(self, requestid, imagename, ipaddr): ...\n def _to_nodes(self, res, ipaddr): ...\n def list_nodes(self, ipaddr): ...\n def ex_update_node_access(self, node, ipaddr): ...\n def ex_extend_request_time(self, node, minutes): ...\n def ex_get_request_end_time(self, node): ...\n\n NODE_STATE_MAP = {'ready': NodeState.RUNNING, 'failed': NodeState.TERMINATED, 'timedout': NodeState.TERMINATED, 'loading': NodeState.PENDING, 'time': NodeState.PENDING, 'future': NodeState.PENDING, 'error': NodeState.UNKNOWN, 'notready': NodeState.PENDING, 'notavailable': NodeState.TERMINATED, 'success': NodeState.PENDING}\n connectionCls = VCLConnection\n name = 'VCL'\n website = 'http://incubator.apache.org/vcl/'\n type = Provider.VCL\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_destroy_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000763.py"} {"focal_file": "libcloud/compute/drivers/vcl.py", "focal_class": null, "focal_method": "ex_update_node_access", "tests": "import unittest\n\nclass Test_ex_update_node_access(unittest.TestCase):\n def test_ex_update_node_access(self):\n node = self.driver.list_nodes(ipaddr='192.168.1.1')[0]\n node = self.driver.ex_update_node_access(node, ipaddr='192.168.1.2')\n self.assertEqual(node.name, 'CentOS 5.4 Base (32 bit VM)')\n self.assertEqual(node.state, NodeState.RUNNING)\n self.assertEqual(node.extra['pass'], 'ehkNGW')\n", "method_code": " def ex_update_node_access(self, node, ipaddr):\n \"\"\"\n Update the remote ip accessing the node.\n \n @param node: the reservation node to update\n @type node: L{Node}\n \n @param ipaddr: the ipaddr used to access the node\n @type ipaddr: C{str}\n \n @return: node with updated information\n @rtype: L{Node}\n \"\"\"\n return self._to_status(node.id, node.image, ipaddr)\n ", "context": "class VCLNodeDriver(NodeDriver):\n def ex_update_node_access(self, node, ipaddr): ...\n def __init__(self, key, secret, secure=True, host=None, port=None, *args, **kwargs): ...\n def _vcl_request(self, method, *args): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def _to_image(self, img): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def _to_connect_data(self, request_id, ipaddr): ...\n def _to_status(self, requestid, imagename, ipaddr): ...\n def _to_nodes(self, res, ipaddr): ...\n def list_nodes(self, ipaddr): ...\n def ex_extend_request_time(self, node, minutes): ...\n def ex_get_request_end_time(self, node): ...\n\n NODE_STATE_MAP = {'ready': NodeState.RUNNING, 'failed': NodeState.TERMINATED, 'timedout': NodeState.TERMINATED, 'loading': NodeState.PENDING, 'time': NodeState.PENDING, 'future': NodeState.PENDING, 'error': NodeState.UNKNOWN, 'notready': NodeState.PENDING, 'notavailable': NodeState.TERMINATED, 'success': NodeState.PENDING}\n connectionCls = VCLConnection\n name = 'VCL'\n website = 'http://incubator.apache.org/vcl/'\n type = Provider.VCL\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_update_node_access", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000764.py"} {"focal_file": "libcloud/compute/drivers/vcl.py", "focal_class": null, "focal_method": "ex_extend_request_time", "tests": "import unittest\n\nclass Test_ex_extend_request_time(unittest.TestCase):\n def test_ex_extend_request_time(self):\n node = self.driver.list_nodes(ipaddr='192.168.1.1')[0]\n self.assertTrue(self.driver.ex_extend_request_time(node, 60))\n", "method_code": " def ex_extend_request_time(self, node, minutes):\n \"\"\"\n Time in minutes to extend the requested node's reservation time\n \n @param node: the reservation node to update\n @type node: L{Node}\n \n @param minutes: the number of mintes to update\n @type minutes: C{str}\n \n @return: true on success, throws error on failure\n @rtype: C{bool}\n \"\"\"\n return self._vcl_request('XMLRPCextendRequest', node.id, minutes)\n ", "context": "class VCLNodeDriver(NodeDriver):\n def ex_extend_request_time(self, node, minutes): ...\n def __init__(self, key, secret, secure=True, host=None, port=None, *args, **kwargs): ...\n def _vcl_request(self, method, *args): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def _to_image(self, img): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def _to_connect_data(self, request_id, ipaddr): ...\n def _to_status(self, requestid, imagename, ipaddr): ...\n def _to_nodes(self, res, ipaddr): ...\n def list_nodes(self, ipaddr): ...\n def ex_update_node_access(self, node, ipaddr): ...\n def ex_get_request_end_time(self, node): ...\n\n NODE_STATE_MAP = {'ready': NodeState.RUNNING, 'failed': NodeState.TERMINATED, 'timedout': NodeState.TERMINATED, 'loading': NodeState.PENDING, 'time': NodeState.PENDING, 'future': NodeState.PENDING, 'error': NodeState.UNKNOWN, 'notready': NodeState.PENDING, 'notavailable': NodeState.TERMINATED, 'success': NodeState.PENDING}\n connectionCls = VCLConnection\n name = 'VCL'\n website = 'http://incubator.apache.org/vcl/'\n type = Provider.VCL\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_extend_request_time", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/compute/drivers/vcl.py", "focal_class": null, "focal_method": "ex_get_request_end_time", "tests": "import unittest\n\nclass Test_ex_get_request_end_time(unittest.TestCase):\n def test_ex_get_request_end_time(self):\n node = self.driver.list_nodes(ipaddr='192.168.1.1')[0]\n self.assertEqual(self.driver.ex_get_request_end_time(node), 1334168100)\n", "method_code": " def ex_get_request_end_time(self, node):\n \"\"\"\n Get the ending time of the node reservation.\n \n @param node: the reservation node to update\n @type node: L{Node}\n \n @return: unix timestamp\n @rtype: C{int}\n \"\"\"\n res = self._vcl_request('XMLRPCgetRequestIds')\n time = 0\n for i in res['requests']:\n if i['requestid'] == node.id:\n time = i['end']\n return time\n ", "context": "class VCLNodeDriver(NodeDriver):\n def ex_get_request_end_time(self, node): ...\n def __init__(self, key, secret, secure=True, host=None, port=None, *args, **kwargs): ...\n def _vcl_request(self, method, *args): ...\n def create_node(self, **kwargs): ...\n def destroy_node(self, node): ...\n def _to_image(self, img): ...\n def list_images(self, location=None): ...\n def list_sizes(self, location=None): ...\n def _to_connect_data(self, request_id, ipaddr): ...\n def _to_status(self, requestid, imagename, ipaddr): ...\n def _to_nodes(self, res, ipaddr): ...\n def list_nodes(self, ipaddr): ...\n def ex_update_node_access(self, node, ipaddr): ...\n def ex_extend_request_time(self, node, minutes): ...\n\n NODE_STATE_MAP = {'ready': NodeState.RUNNING, 'failed': NodeState.TERMINATED, 'timedout': NodeState.TERMINATED, 'loading': NodeState.PENDING, 'time': NodeState.PENDING, 'future': NodeState.PENDING, 'error': NodeState.UNKNOWN, 'notready': NodeState.PENDING, 'notavailable': NodeState.TERMINATED, 'success': NodeState.PENDING}\n connectionCls = VCLConnection\n name = 'VCL'\n website = 'http://incubator.apache.org/vcl/'\n type = Provider.VCL\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_get_request_end_time", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000766.py"} {"focal_file": "libcloud/compute/drivers/vcloud.py", "focal_class": null, "focal_method": "list_images", "tests": "import unittest\n\nclass Test_list_images(unittest.TestCase):\n def test_list_images(self):\n ret = self.driver.list_images()\n self.assertEqual('https://vm-vcloud/api/vAppTemplate/vappTemplate-ac1bc027-bf8c-4050-8643-4971f691c158', ret[0].id)\n", "method_code": " def list_images(self, location=None):\n images = []\n for vdc in self.vdcs:\n res = self.connection.request(get_url_path(vdc.id)).object\n res_ents = res.findall(fixxpath(res, 'ResourceEntities/ResourceEntity'))\n images += [self._to_image(i) for i in res_ents if i.get('type') == 'application/vnd.vmware.vcloud.vAppTemplate+xml']\n for catalog in self._get_catalog_hrefs():\n for cat_item in self._get_catalogitems_hrefs(catalog):\n res = self._get_catalogitem(cat_item)\n res_ents = res.findall(fixxpath(res, 'Entity'))\n images += [self._to_image(i) for i in res_ents if i.get('type') == 'application/vnd.vmware.vcloud.vAppTemplate+xml']\n \n def idfun(image):\n return image.id\n return self._uniquer(images, idfun)\n ", "context": "class VCloudNodeDriver(NodeDriver):\n def list_images(self, location=None): ...\n def __new__(cls, key, secret=None, secure=True, host=None, port=None, api_version=DEFAULT_API_VERSION, **kwargs): ...\n def vdcs(self): ...\n def _to_vdc(self, vdc_elm): ...\n def _get_vdc(self, vdc_name): ...\n def networks(self): ...\n def _to_image(self, image): ...\n def _to_node(self, elm): ...\n def _get_catalog_hrefs(self): ...\n def _wait_for_task_completion(self, task_href, timeout=DEFAULT_TASK_COMPLETION_TIMEOUT): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def ex_list_nodes(self, vdcs=None): ...\n def _to_size(self, ram): ...\n def list_sizes(self, location=None): ...\n def _get_catalogitems_hrefs(self, catalog): ...\n def _get_catalogitem(self, catalog_item): ...\n def _uniquer(self, seq, idfun=None): ...\n def create_node(self, **kwargs): ...\n\n type = Provider.VCLOUD\n name = 'vCloud'\n website = 'http://www.vmware.com/products/vcloud/'\n connectionCls = VCloudConnection\n org = None\n _vdcs = None\n NODE_STATE_MAP = {'0': NodeState.PENDING, '1': NodeState.PENDING, '2': NodeState.PENDING, '3': NodeState.PENDING, '4': NodeState.RUNNING}\n features = {'create_node': ['password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_images", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000767.py"} {"focal_file": "libcloud/compute/drivers/vcloud.py", "focal_class": null, "focal_method": "list_sizes", "tests": "import unittest\n\nclass Test_list_sizes(unittest.TestCase):\n def test_list_sizes(self):\n ret = self.driver.list_sizes()\n self.assertEqual(ret[0].ram, 512)\n", "method_code": " def list_sizes(self, location=None):\n sizes = [self._to_size(i) for i in VIRTUAL_MEMORY_VALS]\n return sizes\n ", "context": "class VCloudNodeDriver(NodeDriver):\n def list_sizes(self, location=None): ...\n def __new__(cls, key, secret=None, secure=True, host=None, port=None, api_version=DEFAULT_API_VERSION, **kwargs): ...\n def vdcs(self): ...\n def _to_vdc(self, vdc_elm): ...\n def _get_vdc(self, vdc_name): ...\n def networks(self): ...\n def _to_image(self, image): ...\n def _to_node(self, elm): ...\n def _get_catalog_hrefs(self): ...\n def _wait_for_task_completion(self, task_href, timeout=DEFAULT_TASK_COMPLETION_TIMEOUT): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def ex_list_nodes(self, vdcs=None): ...\n def _to_size(self, ram): ...\n def _get_catalogitems_hrefs(self, catalog): ...\n def _get_catalogitem(self, catalog_item): ...\n def list_images(self, location=None): ...\n def _uniquer(self, seq, idfun=None): ...\n def create_node(self, **kwargs): ...\n\n type = Provider.VCLOUD\n name = 'vCloud'\n website = 'http://www.vmware.com/products/vcloud/'\n connectionCls = VCloudConnection\n org = None\n _vdcs = None\n NODE_STATE_MAP = {'0': NodeState.PENDING, '1': NodeState.PENDING, '2': NodeState.PENDING, '3': NodeState.PENDING, '4': NodeState.RUNNING}\n features = {'create_node': ['password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_sizes", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000768.py"} {"focal_file": "libcloud/compute/drivers/vcloud.py", "focal_class": null, "focal_method": "create_node", "tests": "import unittest\n\nclass Test_create_node(unittest.TestCase):\n def test_create_node(self):\n image = self.driver.list_images()[0]\n size = self.driver.list_sizes()[0]\n node = self.driver.create_node(name='testNode', image=image, size=size, ex_vdc='MyVdc', ex_network='vCloud - Default', cpus=2)\n self.assertTrue(isinstance(node, Node))\n self.assertEqual('https://vm-vcloud/api/vApp/vapp-8c57a5b6-e61b-48ca-8a78-3b70ee65ef6a', node.id)\n self.assertEqual('testNode', node.name)\n\n def test_create_node_clone(self):\n image = self.driver.list_nodes()[0]\n node = self.driver.create_node(name='testNode', image=image)\n self.assertTrue(isinstance(node, Node))\n self.assertEqual('https://vm-vcloud/api/vApp/vapp-8c57a5b6-e61b-48ca-8a78-3b70ee65ef6a', node.id)\n self.assertEqual('testNode', node.name)\n", "method_code": " def create_node(self, **kwargs):\n \"\"\"Creates and returns node.\n \n \n @inherits: L{NodeDriver.create_node}\n \n @keyword ex_network: link to a \"Network\" e.g.,\n \"https://services.vcloudexpress.terremark.com/api/v0.8/network/7\"\n @type ex_network: C{str}\n \n @keyword ex_vdc: Name of organisation's virtual data\n center where vApp VMs will be deployed.\n @type ex_vdc: C{str}\n \n @keyword ex_cpus: number of virtual cpus (limit depends on provider)\n @type ex_cpus: C{int}\n \n @keyword ex_row: ????\n @type ex_row: C{str}\n \n @keyword ex_group: ????\n @type ex_group: C{str}\n \"\"\"\n name = kwargs['name']\n image = kwargs['image']\n size = kwargs['size']\n try:\n network = kwargs.get('ex_network', self.networks[0].get('href'))\n except IndexError:\n network = ''\n password = None\n if 'auth' in kwargs:\n auth = kwargs['auth']\n if isinstance(auth, NodeAuthPassword):\n password = auth.password\n else:\n raise ValueError('auth must be of NodeAuthPassword type')\n instantiate_xml = InstantiateVAppXML(name=name, template=image.id, net_href=network, cpus=str(kwargs.get('ex_cpus', 1)), memory=str(size.ram), password=password, row=kwargs.get('ex_row', None), group=kwargs.get('ex_group', None))\n vdc = self._get_vdc(kwargs.get('ex_vdc', None))\n res = self.connection.request('%s/action/instantiateVAppTemplate' % get_url_path(vdc.id), data=instantiate_xml.tostring(), method='POST', headers={'Content-Type': 'application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml'})\n vapp_path = get_url_path(res.object.get('href'))\n res = self.connection.request('%s/action/deploy' % vapp_path, method='POST')\n self._wait_for_task_completion(res.object.get('href'))\n res = self.connection.request('%s/power/action/powerOn' % vapp_path, method='POST')\n res = self.connection.request(vapp_path)\n node = self._to_node(res.object)\n return node\n ", "context": "class VCloudNodeDriver(NodeDriver):\n def create_node(self, **kwargs): ...\n def __new__(cls, key, secret=None, secure=True, host=None, port=None, api_version=DEFAULT_API_VERSION, **kwargs): ...\n def vdcs(self): ...\n def _to_vdc(self, vdc_elm): ...\n def _get_vdc(self, vdc_name): ...\n def networks(self): ...\n def _to_image(self, image): ...\n def _to_node(self, elm): ...\n def _get_catalog_hrefs(self): ...\n def _wait_for_task_completion(self, task_href, timeout=DEFAULT_TASK_COMPLETION_TIMEOUT): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def ex_list_nodes(self, vdcs=None): ...\n def _to_size(self, ram): ...\n def list_sizes(self, location=None): ...\n def _get_catalogitems_hrefs(self, catalog): ...\n def _get_catalogitem(self, catalog_item): ...\n def list_images(self, location=None): ...\n def _uniquer(self, seq, idfun=None): ...\n\n type = Provider.VCLOUD\n name = 'vCloud'\n website = 'http://www.vmware.com/products/vcloud/'\n connectionCls = VCloudConnection\n org = None\n _vdcs = None\n NODE_STATE_MAP = {'0': NodeState.PENDING, '1': NodeState.PENDING, '2': NodeState.PENDING, '3': NodeState.PENDING, '4': NodeState.RUNNING}\n features = {'create_node': ['password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000769.py"} {"focal_file": "libcloud/compute/drivers/vcloud.py", "focal_class": null, "focal_method": "list_nodes", "tests": "import unittest\n\nclass Test_list_nodes(unittest.TestCase):\n def test_list_nodes(self):\n ret = self.driver.list_nodes()\n node = ret[0]\n self.assertEqual(node.id, 'https://vm-vcloud/api/vApp/vapp-8c57a5b6-e61b-48ca-8a78-3b70ee65ef6a')\n self.assertEqual(node.name, 'testNode')\n self.assertEqual(node.state, NodeState.RUNNING)\n self.assertEqual(node.public_ips, ['65.41.67.2'])\n self.assertEqual(node.private_ips, ['65.41.67.2'])\n self.assertEqual(node.extra, {'vdc': 'MyVdc', 'vms': [{'id': 'https://vm-vcloud/api/vApp/vm-dd75d1d3-5b7b-48f0-aff3-69622ab7e045', 'name': 'testVm', 'state': NodeState.RUNNING, 'public_ips': ['65.41.67.2'], 'private_ips': ['65.41.67.2'], 'os_type': 'rhel5_64Guest'}]})\n node = ret[1]\n self.assertEqual(node.id, 'https://vm-vcloud/api/vApp/vapp-8c57a5b6-e61b-48ca-8a78-3b70ee65ef6b')\n self.assertEqual(node.name, 'testNode2')\n self.assertEqual(node.state, NodeState.RUNNING)\n self.assertEqual(node.public_ips, ['192.168.0.103'])\n self.assertEqual(node.private_ips, ['192.168.0.100'])\n self.assertEqual(node.extra, {'vdc': 'MyVdc', 'vms': [{'id': 'https://vm-vcloud/api/vApp/vm-dd75d1d3-5b7b-48f0-aff3-69622ab7e046', 'name': 'testVm2', 'state': NodeState.RUNNING, 'public_ips': ['192.168.0.103'], 'private_ips': ['192.168.0.100'], 'os_type': 'rhel5_64Guest'}]})\n\n def test_ex_list_nodes(self):\n self.assertEqual(len(self.driver.ex_list_nodes()), len(self.driver.list_nodes()))\n", "method_code": " def list_nodes(self):\n return self.ex_list_nodes()\n ", "context": "class VCloudNodeDriver(NodeDriver):\n def list_nodes(self): ...\n def __new__(cls, key, secret=None, secure=True, host=None, port=None, api_version=DEFAULT_API_VERSION, **kwargs): ...\n def vdcs(self): ...\n def _to_vdc(self, vdc_elm): ...\n def _get_vdc(self, vdc_name): ...\n def networks(self): ...\n def _to_image(self, image): ...\n def _to_node(self, elm): ...\n def _get_catalog_hrefs(self): ...\n def _wait_for_task_completion(self, task_href, timeout=DEFAULT_TASK_COMPLETION_TIMEOUT): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def ex_list_nodes(self, vdcs=None): ...\n def _to_size(self, ram): ...\n def list_sizes(self, location=None): ...\n def _get_catalogitems_hrefs(self, catalog): ...\n def _get_catalogitem(self, catalog_item): ...\n def list_images(self, location=None): ...\n def _uniquer(self, seq, idfun=None): ...\n def create_node(self, **kwargs): ...\n\n type = Provider.VCLOUD\n name = 'vCloud'\n website = 'http://www.vmware.com/products/vcloud/'\n connectionCls = VCloudConnection\n org = None\n _vdcs = None\n NODE_STATE_MAP = {'0': NodeState.PENDING, '1': NodeState.PENDING, '2': NodeState.PENDING, '3': NodeState.PENDING, '4': NodeState.RUNNING}\n features = {'create_node': ['password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_nodes", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000770.py"} {"focal_file": "libcloud/compute/drivers/vcloud.py", "focal_class": null, "focal_method": "reboot_node", "tests": "import unittest\n\nclass Test_reboot_node(unittest.TestCase):\n def test_reboot_node(self):\n node = self.driver.list_nodes()[0]\n ret = self.driver.reboot_node(node)\n self.assertTrue(ret)\n", "method_code": " def reboot_node(self, node):\n res = self.connection.request('%s/power/action/reset' % get_url_path(node.id), method='POST')\n return res.status in [httplib.ACCEPTED, httplib.NO_CONTENT]\n ", "context": "class VCloudNodeDriver(NodeDriver):\n def reboot_node(self, node): ...\n def __new__(cls, key, secret=None, secure=True, host=None, port=None, api_version=DEFAULT_API_VERSION, **kwargs): ...\n def vdcs(self): ...\n def _to_vdc(self, vdc_elm): ...\n def _get_vdc(self, vdc_name): ...\n def networks(self): ...\n def _to_image(self, image): ...\n def _to_node(self, elm): ...\n def _get_catalog_hrefs(self): ...\n def _wait_for_task_completion(self, task_href, timeout=DEFAULT_TASK_COMPLETION_TIMEOUT): ...\n def destroy_node(self, node): ...\n def list_nodes(self): ...\n def ex_list_nodes(self, vdcs=None): ...\n def _to_size(self, ram): ...\n def list_sizes(self, location=None): ...\n def _get_catalogitems_hrefs(self, catalog): ...\n def _get_catalogitem(self, catalog_item): ...\n def list_images(self, location=None): ...\n def _uniquer(self, seq, idfun=None): ...\n def create_node(self, **kwargs): ...\n\n type = Provider.VCLOUD\n name = 'vCloud'\n website = 'http://www.vmware.com/products/vcloud/'\n connectionCls = VCloudConnection\n org = None\n _vdcs = None\n NODE_STATE_MAP = {'0': NodeState.PENDING, '1': NodeState.PENDING, '2': NodeState.PENDING, '3': NodeState.PENDING, '4': NodeState.RUNNING}\n features = {'create_node': ['password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_reboot_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 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": "libcloud/compute/drivers/vcloud.py", "focal_class": null, "focal_method": "destroy_node", "tests": "import unittest\n\nclass Test_destroy_node(unittest.TestCase):\n def test_destroy_node(self):\n node = self.driver.list_nodes()[0]\n ret = self.driver.destroy_node(node)\n self.assertTrue(ret)\n", "method_code": " def destroy_node(self, node):\n node_path = get_url_path(node.id)\n try:\n res = self.connection.request('%s/power/action/poweroff' % node_path, method='POST')\n self._wait_for_task_completion(res.object.get('href'))\n except Exception:\n pass\n try:\n res = self.connection.request('%s/action/undeploy' % node_path, method='POST')\n self._wait_for_task_completion(res.object.get('href'))\n except ExpatError:\n pass\n except Exception:\n pass\n res = self.connection.request(node_path, method='DELETE')\n return res.status == httplib.ACCEPTED\n ", "context": "class VCloudNodeDriver(NodeDriver):\n def destroy_node(self, node): ...\n def __new__(cls, key, secret=None, secure=True, host=None, port=None, api_version=DEFAULT_API_VERSION, **kwargs): ...\n def vdcs(self): ...\n def _to_vdc(self, vdc_elm): ...\n def _get_vdc(self, vdc_name): ...\n def networks(self): ...\n def _to_image(self, image): ...\n def _to_node(self, elm): ...\n def _get_catalog_hrefs(self): ...\n def _wait_for_task_completion(self, task_href, timeout=DEFAULT_TASK_COMPLETION_TIMEOUT): ...\n def reboot_node(self, node): ...\n def list_nodes(self): ...\n def ex_list_nodes(self, vdcs=None): ...\n def _to_size(self, ram): ...\n def list_sizes(self, location=None): ...\n def _get_catalogitems_hrefs(self, catalog): ...\n def _get_catalogitem(self, catalog_item): ...\n def list_images(self, location=None): ...\n def _uniquer(self, seq, idfun=None): ...\n def create_node(self, **kwargs): ...\n\n type = Provider.VCLOUD\n name = 'vCloud'\n website = 'http://www.vmware.com/products/vcloud/'\n connectionCls = VCloudConnection\n org = None\n _vdcs = None\n NODE_STATE_MAP = {'0': NodeState.PENDING, '1': NodeState.PENDING, '2': NodeState.PENDING, '3': NodeState.PENDING, '4': NodeState.RUNNING}\n features = {'create_node': ['password']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_destroy_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000772.py"} {"focal_file": "libcloud/compute/drivers/vcloud.py", "focal_class": null, "focal_method": "_validate_vm_names", "tests": "import unittest\n\nclass Test_validate_vm_names(unittest.TestCase):\n def test_validate_vm_names(self):\n self.driver._validate_vm_names(['host-n-ame-name'])\n self.driver._validate_vm_names(['tc-mybuild-b1'])\n self.driver._validate_vm_names(None)\n self.assertRaises(ValueError, self.driver._validate_vm_names, ['invalid.host'])\n self.assertRaises(ValueError, self.driver._validate_vm_names, ['inv-alid.host'])\n self.assertRaises(ValueError, self.driver._validate_vm_names, ['hostnametoooolong'])\n self.assertRaises(ValueError, self.driver._validate_vm_names, ['host$name'])\n", "method_code": " def _validate_vm_names(names):\n if names is None:\n return\n hname_re = re.compile('^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9]*)[\\\\-])*([A-Za-z]|[A-Za-z][A-Za-z0-9]*[A-Za-z0-9])$')\n for name in names:\n if len(name) > 15:\n raise ValueError('The VM name \"' + name + '\" is too long for the computer name (max 15 chars allowed).')\n if not hname_re.match(name):\n raise ValueError('The VM name \"' + name + '\" can not be used. \"' + name + '\" is not a valid computer name for the VM.')\n ", "context": "class VCloud_1_5_NodeDriver(VCloudNodeDriver):\n @staticmethod\n def _validate_vm_names(names): ...\n def list_locations(self): ...\n def ex_find_node(self, node_name, vdcs=None): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def ex_deploy_node(self, node): ...\n def ex_undeploy_node(self, node): ...\n def ex_power_off_node(self, node): ...\n def ex_power_on_node(self, node): ...\n def ex_shutdown_node(self, node): ...\n def ex_suspend_node(self, node): ...\n def _perform_power_operation(self, node, operation): ...\n def ex_get_control_access(self, node): ...\n def ex_set_control_access(self, node, control_access): ...\n def ex_get_metadata(self, node): ...\n def ex_set_metadata_entry(self, node, key, value): ...\n def ex_query(self, type, filter=None, page=1, page_size=100, sort_asc=None, sort_desc=None): ...\n def create_node(self, **kwargs): ...\n def _instantiate_node(self, name, image, network_elem, vdc, vm_network, vm_fence): ...\n def _clone_node(self, name, sourceNode, vdc): ...\n def ex_set_vm_cpu(self, vapp_or_vm_id, vm_cpu): ...\n def ex_set_vm_memory(self, vapp_or_vm_id, vm_memory): ...\n def ex_add_vm_disk(self, vapp_or_vm_id, vm_disk_size): ...\n def _validate_vm_memory(vm_memory): ...\n def _validate_vm_cpu(vm_cpu): ...\n def _validate_vm_disk_size(vm_disk): ...\n def _validate_vm_script(vm_script): ...\n def _validate_vm_fence(vm_fence): ...\n def _validate_vm_ipmode(vm_ipmode): ...\n def _change_vm_names(self, vapp_or_vm_id, vm_names): ...\n def _change_vm_cpu(self, vapp_or_vm_id, vm_cpu): ...\n def _change_vm_memory(self, vapp_or_vm_id, vm_memory): ...\n def _add_vm_disk(self, vapp_or_vm_id, vm_disk): ...\n def _change_vm_script(self, vapp_or_vm_id, vm_script): ...\n def _change_vm_ipmode(self, vapp_or_vm_id, vm_ipmode): ...\n def _get_network_href(self, network_name): ...\n def _get_vm_elements(self, vapp_or_vm_id): ...\n def _is_node(self, node_or_image): ...\n def _to_node(self, node_elm): ...\n def _to_vdc(self, vdc_elm): ...\n\n connectionCls = VCloud_1_5_Connection\n NODE_STATE_MAP = {'-1': NodeState.UNKNOWN, '0': NodeState.PENDING, '1': NodeState.PENDING, '2': NodeState.PENDING, '3': NodeState.PENDING, '4': NodeState.RUNNING, '5': NodeState.RUNNING, '6': NodeState.UNKNOWN, '7': NodeState.UNKNOWN, '8': NodeState.TERMINATED, '9': NodeState.UNKNOWN, '10': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_validate_vm_names", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000773.py"} {"focal_file": "libcloud/compute/drivers/vcloud.py", "focal_class": null, "focal_method": "_change_vm_names", "tests": "import unittest\n\nclass Test_change_vm_names(unittest.TestCase):\n def test_change_vm_names(self):\n self.driver._change_vm_names('/api/vApp/vapp-8c57a5b6-e61b-48ca-8a78-3b70ee65ef6a', ['changed1', 'changed2'])\n", "method_code": " def _change_vm_names(self, vapp_or_vm_id, vm_names):\n if vm_names is None:\n return\n vms = self._get_vm_elements(vapp_or_vm_id)\n for i, vm in enumerate(vms):\n if len(vm_names) <= i:\n return\n res = self.connection.request('%s/guestCustomizationSection' % get_url_path(vm.get('href')))\n res.object.find(fixxpath(res.object, 'ComputerName')).text = vm_names[i]\n admin_pass = res.object.find(fixxpath(res.object, 'AdminPassword'))\n if admin_pass is not None:\n res.object.remove(admin_pass)\n res = self.connection.request('%s/guestCustomizationSection' % get_url_path(vm.get('href')), data=ET.tostring(res.object), method='PUT', headers={'Content-Type': 'application/vnd.vmware.vcloud.guestCustomizationSection+xml'})\n self._wait_for_task_completion(res.object.get('href'))\n req_xml = ET.Element('Vm', {'name': vm_names[i], 'xmlns': 'http://www.vmware.com/vcloud/v1.5'})\n res = self.connection.request(get_url_path(vm.get('href')), data=ET.tostring(req_xml), method='PUT', headers={'Content-Type': 'application/vnd.vmware.vcloud.vm+xml'})\n self._wait_for_task_completion(res.object.get('href'))\n ", "context": "class VCloud_1_5_NodeDriver(VCloudNodeDriver):\n def _change_vm_names(self, vapp_or_vm_id, vm_names): ...\n def list_locations(self): ...\n def ex_find_node(self, node_name, vdcs=None): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def ex_deploy_node(self, node): ...\n def ex_undeploy_node(self, node): ...\n def ex_power_off_node(self, node): ...\n def ex_power_on_node(self, node): ...\n def ex_shutdown_node(self, node): ...\n def ex_suspend_node(self, node): ...\n def _perform_power_operation(self, node, operation): ...\n def ex_get_control_access(self, node): ...\n def ex_set_control_access(self, node, control_access): ...\n def ex_get_metadata(self, node): ...\n def ex_set_metadata_entry(self, node, key, value): ...\n def ex_query(self, type, filter=None, page=1, page_size=100, sort_asc=None, sort_desc=None): ...\n def create_node(self, **kwargs): ...\n def _instantiate_node(self, name, image, network_elem, vdc, vm_network, vm_fence): ...\n def _clone_node(self, name, sourceNode, vdc): ...\n def ex_set_vm_cpu(self, vapp_or_vm_id, vm_cpu): ...\n def ex_set_vm_memory(self, vapp_or_vm_id, vm_memory): ...\n def ex_add_vm_disk(self, vapp_or_vm_id, vm_disk_size): ...\n def _validate_vm_names(names): ...\n def _validate_vm_memory(vm_memory): ...\n def _validate_vm_cpu(vm_cpu): ...\n def _validate_vm_disk_size(vm_disk): ...\n def _validate_vm_script(vm_script): ...\n def _validate_vm_fence(vm_fence): ...\n def _validate_vm_ipmode(vm_ipmode): ...\n def _change_vm_cpu(self, vapp_or_vm_id, vm_cpu): ...\n def _change_vm_memory(self, vapp_or_vm_id, vm_memory): ...\n def _add_vm_disk(self, vapp_or_vm_id, vm_disk): ...\n def _change_vm_script(self, vapp_or_vm_id, vm_script): ...\n def _change_vm_ipmode(self, vapp_or_vm_id, vm_ipmode): ...\n def _get_network_href(self, network_name): ...\n def _get_vm_elements(self, vapp_or_vm_id): ...\n def _is_node(self, node_or_image): ...\n def _to_node(self, node_elm): ...\n def _to_vdc(self, vdc_elm): ...\n\n connectionCls = VCloud_1_5_Connection\n NODE_STATE_MAP = {'-1': NodeState.UNKNOWN, '0': NodeState.PENDING, '1': NodeState.PENDING, '2': NodeState.PENDING, '3': NodeState.PENDING, '4': NodeState.RUNNING, '5': NodeState.RUNNING, '6': NodeState.UNKNOWN, '7': NodeState.UNKNOWN, '8': NodeState.TERMINATED, '9': NodeState.UNKNOWN, '10': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_change_vm_names", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/compute/drivers/vcloud.py", "focal_class": null, "focal_method": "_is_node", "tests": "import unittest\n\nclass Test_is_node(unittest.TestCase):\n def test_is_node(self):\n self.assertTrue(self.driver._is_node(Node('testId', 'testNode', state=0, public_ips=[], private_ips=[], driver=self.driver)))\n self.assertFalse(self.driver._is_node(NodeImage('testId', 'testNode', driver=self.driver)))\n", "method_code": " def _is_node(self, node_or_image):\n return isinstance(node_or_image, Node)\n ", "context": "class VCloud_1_5_NodeDriver(VCloudNodeDriver):\n def _is_node(self, node_or_image): ...\n def list_locations(self): ...\n def ex_find_node(self, node_name, vdcs=None): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def ex_deploy_node(self, node): ...\n def ex_undeploy_node(self, node): ...\n def ex_power_off_node(self, node): ...\n def ex_power_on_node(self, node): ...\n def ex_shutdown_node(self, node): ...\n def ex_suspend_node(self, node): ...\n def _perform_power_operation(self, node, operation): ...\n def ex_get_control_access(self, node): ...\n def ex_set_control_access(self, node, control_access): ...\n def ex_get_metadata(self, node): ...\n def ex_set_metadata_entry(self, node, key, value): ...\n def ex_query(self, type, filter=None, page=1, page_size=100, sort_asc=None, sort_desc=None): ...\n def create_node(self, **kwargs): ...\n def _instantiate_node(self, name, image, network_elem, vdc, vm_network, vm_fence): ...\n def _clone_node(self, name, sourceNode, vdc): ...\n def ex_set_vm_cpu(self, vapp_or_vm_id, vm_cpu): ...\n def ex_set_vm_memory(self, vapp_or_vm_id, vm_memory): ...\n def ex_add_vm_disk(self, vapp_or_vm_id, vm_disk_size): ...\n def _validate_vm_names(names): ...\n def _validate_vm_memory(vm_memory): ...\n def _validate_vm_cpu(vm_cpu): ...\n def _validate_vm_disk_size(vm_disk): ...\n def _validate_vm_script(vm_script): ...\n def _validate_vm_fence(vm_fence): ...\n def _validate_vm_ipmode(vm_ipmode): ...\n def _change_vm_names(self, vapp_or_vm_id, vm_names): ...\n def _change_vm_cpu(self, vapp_or_vm_id, vm_cpu): ...\n def _change_vm_memory(self, vapp_or_vm_id, vm_memory): ...\n def _add_vm_disk(self, vapp_or_vm_id, vm_disk): ...\n def _change_vm_script(self, vapp_or_vm_id, vm_script): ...\n def _change_vm_ipmode(self, vapp_or_vm_id, vm_ipmode): ...\n def _get_network_href(self, network_name): ...\n def _get_vm_elements(self, vapp_or_vm_id): ...\n def _to_node(self, node_elm): ...\n def _to_vdc(self, vdc_elm): ...\n\n connectionCls = VCloud_1_5_Connection\n NODE_STATE_MAP = {'-1': NodeState.UNKNOWN, '0': NodeState.PENDING, '1': NodeState.PENDING, '2': NodeState.PENDING, '3': NodeState.PENDING, '4': NodeState.RUNNING, '5': NodeState.RUNNING, '6': NodeState.UNKNOWN, '7': NodeState.UNKNOWN, '8': NodeState.TERMINATED, '9': NodeState.UNKNOWN, '10': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_is_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000775.py"} {"focal_file": "libcloud/compute/drivers/vcloud.py", "focal_class": null, "focal_method": "ex_undeploy_node", "tests": "import unittest\n\nclass Test_ex_undeploy_node(unittest.TestCase):\n def test_ex_undeploy(self):\n node = self.driver.ex_undeploy_node(Node('https://test/api/vApp/undeployTest', 'testNode', state=0, public_ips=[], private_ips=[], driver=self.driver))\n self.assertEqual(node.state, NodeState.TERMINATED)\n\n def test_ex_undeploy_with_error(self):\n node = self.driver.ex_undeploy_node(Node('https://test/api/vApp/undeployErrorTest', 'testNode', state=0, public_ips=[], private_ips=[], driver=self.driver))\n self.assertEqual(node.state, NodeState.TERMINATED)\n", "method_code": " def ex_undeploy_node(self, node):\n \"\"\"\n Undeploys existing node. Equal to vApp \"stop\" operation.\n \n @param node: The node to be deployed\n @type node: L{Node}\n \n @rtype: L{Node}\n \"\"\"\n undeploy_xml = ET.Element('UndeployVAppParams', {'xmlns': 'http://www.vmware.com/vcloud/v1.5'})\n undeploy_power_action_xml = ET.SubElement(undeploy_xml, 'UndeployPowerAction')\n undeploy_power_action_xml.text = 'shutdown'\n try:\n res = self.connection.request('%s/action/undeploy' % get_url_path(node.id), data=ET.tostring(undeploy_xml), method='POST', headers={'Content-Type': 'application/vnd.vmware.vcloud.undeployVAppParams+xml'})\n self._wait_for_task_completion(res.object.get('href'))\n except Exception:\n undeploy_power_action_xml.text = 'powerOff'\n res = self.connection.request('%s/action/undeploy' % get_url_path(node.id), data=ET.tostring(undeploy_xml), method='POST', headers={'Content-Type': 'application/vnd.vmware.vcloud.undeployVAppParams+xml'})\n self._wait_for_task_completion(res.object.get('href'))\n res = self.connection.request(get_url_path(node.id))\n return self._to_node(res.object)\n ", "context": "class VCloud_1_5_NodeDriver(VCloudNodeDriver):\n def ex_undeploy_node(self, node): ...\n def list_locations(self): ...\n def ex_find_node(self, node_name, vdcs=None): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def ex_deploy_node(self, node): ...\n def ex_power_off_node(self, node): ...\n def ex_power_on_node(self, node): ...\n def ex_shutdown_node(self, node): ...\n def ex_suspend_node(self, node): ...\n def _perform_power_operation(self, node, operation): ...\n def ex_get_control_access(self, node): ...\n def ex_set_control_access(self, node, control_access): ...\n def ex_get_metadata(self, node): ...\n def ex_set_metadata_entry(self, node, key, value): ...\n def ex_query(self, type, filter=None, page=1, page_size=100, sort_asc=None, sort_desc=None): ...\n def create_node(self, **kwargs): ...\n def _instantiate_node(self, name, image, network_elem, vdc, vm_network, vm_fence): ...\n def _clone_node(self, name, sourceNode, vdc): ...\n def ex_set_vm_cpu(self, vapp_or_vm_id, vm_cpu): ...\n def ex_set_vm_memory(self, vapp_or_vm_id, vm_memory): ...\n def ex_add_vm_disk(self, vapp_or_vm_id, vm_disk_size): ...\n def _validate_vm_names(names): ...\n def _validate_vm_memory(vm_memory): ...\n def _validate_vm_cpu(vm_cpu): ...\n def _validate_vm_disk_size(vm_disk): ...\n def _validate_vm_script(vm_script): ...\n def _validate_vm_fence(vm_fence): ...\n def _validate_vm_ipmode(vm_ipmode): ...\n def _change_vm_names(self, vapp_or_vm_id, vm_names): ...\n def _change_vm_cpu(self, vapp_or_vm_id, vm_cpu): ...\n def _change_vm_memory(self, vapp_or_vm_id, vm_memory): ...\n def _add_vm_disk(self, vapp_or_vm_id, vm_disk): ...\n def _change_vm_script(self, vapp_or_vm_id, vm_script): ...\n def _change_vm_ipmode(self, vapp_or_vm_id, vm_ipmode): ...\n def _get_network_href(self, network_name): ...\n def _get_vm_elements(self, vapp_or_vm_id): ...\n def _is_node(self, node_or_image): ...\n def _to_node(self, node_elm): ...\n def _to_vdc(self, vdc_elm): ...\n\n connectionCls = VCloud_1_5_Connection\n NODE_STATE_MAP = {'-1': NodeState.UNKNOWN, '0': NodeState.PENDING, '1': NodeState.PENDING, '2': NodeState.PENDING, '3': NodeState.PENDING, '4': NodeState.RUNNING, '5': NodeState.RUNNING, '6': NodeState.UNKNOWN, '7': NodeState.UNKNOWN, '8': NodeState.TERMINATED, '9': NodeState.UNKNOWN, '10': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_undeploy", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000776.py"} {"focal_file": "libcloud/compute/drivers/vcloud.py", "focal_class": null, "focal_method": "ex_find_node", "tests": "import unittest\n\nclass Test_ex_find_node(unittest.TestCase):\n def test_ex_find_node(self):\n node = self.driver.ex_find_node('testNode')\n self.assertEqual(node.name, 'testNode')\n node = self.driver.ex_find_node('testNode', self.driver.vdcs[0])\n self.assertEqual(node.name, 'testNode')\n node = self.driver.ex_find_node('testNonExisting', self.driver.vdcs[0])\n self.assertEqual(node, None)\n", "method_code": " def ex_find_node(self, node_name, vdcs=None):\n \"\"\"\n Searches for node across specified vDCs. This is more effective than querying all nodes to get a single\n instance.\n \n @param node_name: The name of the node to search for\n @type node_name: C{str}\n \n @param vdcs: None, vDC or a list of vDCs to search in. If None all vDCs will be searched.\n @type vdcs: L{Vdc}\n \n @return: node instance or None if not found\n @rtype: L{Node} or C{None}\n \"\"\"\n if not vdcs:\n vdcs = self.vdcs\n if not getattr(vdcs, '__iter__', False):\n vdcs = [vdcs]\n for vdc in vdcs:\n res = self.connection.request(get_url_path(vdc.id))\n entity_elems = res.object.findall(fixxpath(res.object, 'ResourceEntities/ResourceEntity'))\n for entity_elem in entity_elems:\n if entity_elem.get('type') == 'application/vnd.vmware.vcloud.vApp+xml' and entity_elem.get('name') == node_name:\n res = self.connection.request(get_url_path(entity_elem.get('href')), headers={'Content-Type': 'application/vnd.vmware.vcloud.vApp+xml'})\n return self._to_node(res.object)\n return None\n ", "context": "class VCloud_1_5_NodeDriver(VCloudNodeDriver):\n def ex_find_node(self, node_name, vdcs=None): ...\n def list_locations(self): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def ex_deploy_node(self, node): ...\n def ex_undeploy_node(self, node): ...\n def ex_power_off_node(self, node): ...\n def ex_power_on_node(self, node): ...\n def ex_shutdown_node(self, node): ...\n def ex_suspend_node(self, node): ...\n def _perform_power_operation(self, node, operation): ...\n def ex_get_control_access(self, node): ...\n def ex_set_control_access(self, node, control_access): ...\n def ex_get_metadata(self, node): ...\n def ex_set_metadata_entry(self, node, key, value): ...\n def ex_query(self, type, filter=None, page=1, page_size=100, sort_asc=None, sort_desc=None): ...\n def create_node(self, **kwargs): ...\n def _instantiate_node(self, name, image, network_elem, vdc, vm_network, vm_fence): ...\n def _clone_node(self, name, sourceNode, vdc): ...\n def ex_set_vm_cpu(self, vapp_or_vm_id, vm_cpu): ...\n def ex_set_vm_memory(self, vapp_or_vm_id, vm_memory): ...\n def ex_add_vm_disk(self, vapp_or_vm_id, vm_disk_size): ...\n def _validate_vm_names(names): ...\n def _validate_vm_memory(vm_memory): ...\n def _validate_vm_cpu(vm_cpu): ...\n def _validate_vm_disk_size(vm_disk): ...\n def _validate_vm_script(vm_script): ...\n def _validate_vm_fence(vm_fence): ...\n def _validate_vm_ipmode(vm_ipmode): ...\n def _change_vm_names(self, vapp_or_vm_id, vm_names): ...\n def _change_vm_cpu(self, vapp_or_vm_id, vm_cpu): ...\n def _change_vm_memory(self, vapp_or_vm_id, vm_memory): ...\n def _add_vm_disk(self, vapp_or_vm_id, vm_disk): ...\n def _change_vm_script(self, vapp_or_vm_id, vm_script): ...\n def _change_vm_ipmode(self, vapp_or_vm_id, vm_ipmode): ...\n def _get_network_href(self, network_name): ...\n def _get_vm_elements(self, vapp_or_vm_id): ...\n def _is_node(self, node_or_image): ...\n def _to_node(self, node_elm): ...\n def _to_vdc(self, vdc_elm): ...\n\n connectionCls = VCloud_1_5_Connection\n NODE_STATE_MAP = {'-1': NodeState.UNKNOWN, '0': NodeState.PENDING, '1': NodeState.PENDING, '2': NodeState.PENDING, '3': NodeState.PENDING, '4': NodeState.RUNNING, '5': NodeState.RUNNING, '6': NodeState.UNKNOWN, '7': NodeState.UNKNOWN, '8': NodeState.TERMINATED, '9': NodeState.UNKNOWN, '10': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_find_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000777.py"} {"focal_file": "libcloud/compute/drivers/vcloud.py", "focal_class": null, "focal_method": "ex_add_vm_disk", "tests": "import unittest\n\nclass Test_ex_add_vm_disk(unittest.TestCase):\n def test_ex_add_vm_disk(self):\n self.driver.ex_add_vm_disk('https://test/api/vApp/vm-test', '20')\n", "method_code": " def ex_add_vm_disk(self, vapp_or_vm_id, vm_disk_size):\n \"\"\"\n Adds a virtual disk to the specified VM or VMs under the vApp. If the vapp_or_vm_id param\n represents a link to an vApp all VMs that are attached to this vApp will be modified.\n \n @keyword vapp_or_vm_id: vApp or VM ID that will be modified. If a vApp ID is used here all attached VMs\n will be modified\n @type vapp_or_vm_id: C{str}\n \n @keyword vm_disk_size: the disk capacity in GB that will be added to the specified VM or VMs\n @type vm_disk_size: C{int}\n \n @rtype: C{None}\n \"\"\"\n self._validate_vm_disk_size(vm_disk_size)\n self._add_vm_disk(vapp_or_vm_id, vm_disk_size)\n ", "context": "class VCloud_1_5_NodeDriver(VCloudNodeDriver):\n def ex_add_vm_disk(self, vapp_or_vm_id, vm_disk_size): ...\n def list_locations(self): ...\n def ex_find_node(self, node_name, vdcs=None): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def ex_deploy_node(self, node): ...\n def ex_undeploy_node(self, node): ...\n def ex_power_off_node(self, node): ...\n def ex_power_on_node(self, node): ...\n def ex_shutdown_node(self, node): ...\n def ex_suspend_node(self, node): ...\n def _perform_power_operation(self, node, operation): ...\n def ex_get_control_access(self, node): ...\n def ex_set_control_access(self, node, control_access): ...\n def ex_get_metadata(self, node): ...\n def ex_set_metadata_entry(self, node, key, value): ...\n def ex_query(self, type, filter=None, page=1, page_size=100, sort_asc=None, sort_desc=None): ...\n def create_node(self, **kwargs): ...\n def _instantiate_node(self, name, image, network_elem, vdc, vm_network, vm_fence): ...\n def _clone_node(self, name, sourceNode, vdc): ...\n def ex_set_vm_cpu(self, vapp_or_vm_id, vm_cpu): ...\n def ex_set_vm_memory(self, vapp_or_vm_id, vm_memory): ...\n def _validate_vm_names(names): ...\n def _validate_vm_memory(vm_memory): ...\n def _validate_vm_cpu(vm_cpu): ...\n def _validate_vm_disk_size(vm_disk): ...\n def _validate_vm_script(vm_script): ...\n def _validate_vm_fence(vm_fence): ...\n def _validate_vm_ipmode(vm_ipmode): ...\n def _change_vm_names(self, vapp_or_vm_id, vm_names): ...\n def _change_vm_cpu(self, vapp_or_vm_id, vm_cpu): ...\n def _change_vm_memory(self, vapp_or_vm_id, vm_memory): ...\n def _add_vm_disk(self, vapp_or_vm_id, vm_disk): ...\n def _change_vm_script(self, vapp_or_vm_id, vm_script): ...\n def _change_vm_ipmode(self, vapp_or_vm_id, vm_ipmode): ...\n def _get_network_href(self, network_name): ...\n def _get_vm_elements(self, vapp_or_vm_id): ...\n def _is_node(self, node_or_image): ...\n def _to_node(self, node_elm): ...\n def _to_vdc(self, vdc_elm): ...\n\n connectionCls = VCloud_1_5_Connection\n NODE_STATE_MAP = {'-1': NodeState.UNKNOWN, '0': NodeState.PENDING, '1': NodeState.PENDING, '2': NodeState.PENDING, '3': NodeState.PENDING, '4': NodeState.RUNNING, '5': NodeState.RUNNING, '6': NodeState.UNKNOWN, '7': NodeState.UNKNOWN, '8': NodeState.TERMINATED, '9': NodeState.UNKNOWN, '10': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_add_vm_disk", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/compute/drivers/vcloud.py", "focal_class": null, "focal_method": "ex_set_vm_cpu", "tests": "import unittest\n\nclass Test_ex_set_vm_cpu(unittest.TestCase):\n def test_ex_set_vm_cpu(self):\n self.driver.ex_set_vm_cpu('https://test/api/vApp/vm-test', 4)\n", "method_code": " def ex_set_vm_cpu(self, vapp_or_vm_id, vm_cpu):\n \"\"\"\n Sets the number of virtual CPUs for the specified VM or VMs under the vApp. If the vapp_or_vm_id param\n represents a link to an vApp all VMs that are attached to this vApp will be modified.\n \n Please ensure that hot-adding a virtual CPU is enabled for the powered on virtual machines.\n Otherwise use this method on undeployed vApp.\n \n @keyword vapp_or_vm_id: vApp or VM ID that will be modified. If a vApp ID is used here all attached VMs\n will be modified\n @type vapp_or_vm_id: C{str}\n \n @keyword vm_cpu: number of virtual CPUs/cores to allocate for specified VMs\n @type vm_cpu: C{int}\n \n @rtype: C{None}\n \"\"\"\n self._validate_vm_cpu(vm_cpu)\n self._change_vm_cpu(vapp_or_vm_id, vm_cpu)\n ", "context": "class VCloud_1_5_NodeDriver(VCloudNodeDriver):\n def ex_set_vm_cpu(self, vapp_or_vm_id, vm_cpu): ...\n def list_locations(self): ...\n def ex_find_node(self, node_name, vdcs=None): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def ex_deploy_node(self, node): ...\n def ex_undeploy_node(self, node): ...\n def ex_power_off_node(self, node): ...\n def ex_power_on_node(self, node): ...\n def ex_shutdown_node(self, node): ...\n def ex_suspend_node(self, node): ...\n def _perform_power_operation(self, node, operation): ...\n def ex_get_control_access(self, node): ...\n def ex_set_control_access(self, node, control_access): ...\n def ex_get_metadata(self, node): ...\n def ex_set_metadata_entry(self, node, key, value): ...\n def ex_query(self, type, filter=None, page=1, page_size=100, sort_asc=None, sort_desc=None): ...\n def create_node(self, **kwargs): ...\n def _instantiate_node(self, name, image, network_elem, vdc, vm_network, vm_fence): ...\n def _clone_node(self, name, sourceNode, vdc): ...\n def ex_set_vm_memory(self, vapp_or_vm_id, vm_memory): ...\n def ex_add_vm_disk(self, vapp_or_vm_id, vm_disk_size): ...\n def _validate_vm_names(names): ...\n def _validate_vm_memory(vm_memory): ...\n def _validate_vm_cpu(vm_cpu): ...\n def _validate_vm_disk_size(vm_disk): ...\n def _validate_vm_script(vm_script): ...\n def _validate_vm_fence(vm_fence): ...\n def _validate_vm_ipmode(vm_ipmode): ...\n def _change_vm_names(self, vapp_or_vm_id, vm_names): ...\n def _change_vm_cpu(self, vapp_or_vm_id, vm_cpu): ...\n def _change_vm_memory(self, vapp_or_vm_id, vm_memory): ...\n def _add_vm_disk(self, vapp_or_vm_id, vm_disk): ...\n def _change_vm_script(self, vapp_or_vm_id, vm_script): ...\n def _change_vm_ipmode(self, vapp_or_vm_id, vm_ipmode): ...\n def _get_network_href(self, network_name): ...\n def _get_vm_elements(self, vapp_or_vm_id): ...\n def _is_node(self, node_or_image): ...\n def _to_node(self, node_elm): ...\n def _to_vdc(self, vdc_elm): ...\n\n connectionCls = VCloud_1_5_Connection\n NODE_STATE_MAP = {'-1': NodeState.UNKNOWN, '0': NodeState.PENDING, '1': NodeState.PENDING, '2': NodeState.PENDING, '3': NodeState.PENDING, '4': NodeState.RUNNING, '5': NodeState.RUNNING, '6': NodeState.UNKNOWN, '7': NodeState.UNKNOWN, '8': NodeState.TERMINATED, '9': NodeState.UNKNOWN, '10': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_set_vm_cpu", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000779.py"} {"focal_file": "libcloud/compute/drivers/vcloud.py", "focal_class": null, "focal_method": "ex_set_vm_memory", "tests": "import unittest\n\nclass Test_ex_set_vm_memory(unittest.TestCase):\n def test_ex_set_vm_memory(self):\n self.driver.ex_set_vm_memory('https://test/api/vApp/vm-test', 1024)\n", "method_code": " def ex_set_vm_memory(self, vapp_or_vm_id, vm_memory):\n \"\"\"\n Sets the virtual memory in MB to allocate for the specified VM or VMs under the vApp.\n If the vapp_or_vm_id param represents a link to an vApp all VMs that are attached to\n this vApp will be modified.\n \n Please ensure that hot-change of virtual memory is enabled for the powered on virtual machines.\n Otherwise use this method on undeployed vApp.\n \n @keyword vapp_or_vm_id: vApp or VM ID that will be modified. If a vApp ID is used here all attached VMs\n will be modified\n @type vapp_or_vm_id: C{str}\n \n @keyword vm_memory: virtual memory in MB to allocate for the specified VM or VMs\n @type vm_memory: C{int}\n \n @rtype: C{None}\n \"\"\"\n self._validate_vm_memory(vm_memory)\n self._change_vm_memory(vapp_or_vm_id, vm_memory)\n ", "context": "class VCloud_1_5_NodeDriver(VCloudNodeDriver):\n def ex_set_vm_memory(self, vapp_or_vm_id, vm_memory): ...\n def list_locations(self): ...\n def ex_find_node(self, node_name, vdcs=None): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def ex_deploy_node(self, node): ...\n def ex_undeploy_node(self, node): ...\n def ex_power_off_node(self, node): ...\n def ex_power_on_node(self, node): ...\n def ex_shutdown_node(self, node): ...\n def ex_suspend_node(self, node): ...\n def _perform_power_operation(self, node, operation): ...\n def ex_get_control_access(self, node): ...\n def ex_set_control_access(self, node, control_access): ...\n def ex_get_metadata(self, node): ...\n def ex_set_metadata_entry(self, node, key, value): ...\n def ex_query(self, type, filter=None, page=1, page_size=100, sort_asc=None, sort_desc=None): ...\n def create_node(self, **kwargs): ...\n def _instantiate_node(self, name, image, network_elem, vdc, vm_network, vm_fence): ...\n def _clone_node(self, name, sourceNode, vdc): ...\n def ex_set_vm_cpu(self, vapp_or_vm_id, vm_cpu): ...\n def ex_add_vm_disk(self, vapp_or_vm_id, vm_disk_size): ...\n def _validate_vm_names(names): ...\n def _validate_vm_memory(vm_memory): ...\n def _validate_vm_cpu(vm_cpu): ...\n def _validate_vm_disk_size(vm_disk): ...\n def _validate_vm_script(vm_script): ...\n def _validate_vm_fence(vm_fence): ...\n def _validate_vm_ipmode(vm_ipmode): ...\n def _change_vm_names(self, vapp_or_vm_id, vm_names): ...\n def _change_vm_cpu(self, vapp_or_vm_id, vm_cpu): ...\n def _change_vm_memory(self, vapp_or_vm_id, vm_memory): ...\n def _add_vm_disk(self, vapp_or_vm_id, vm_disk): ...\n def _change_vm_script(self, vapp_or_vm_id, vm_script): ...\n def _change_vm_ipmode(self, vapp_or_vm_id, vm_ipmode): ...\n def _get_network_href(self, network_name): ...\n def _get_vm_elements(self, vapp_or_vm_id): ...\n def _is_node(self, node_or_image): ...\n def _to_node(self, node_elm): ...\n def _to_vdc(self, vdc_elm): ...\n\n connectionCls = VCloud_1_5_Connection\n NODE_STATE_MAP = {'-1': NodeState.UNKNOWN, '0': NodeState.PENDING, '1': NodeState.PENDING, '2': NodeState.PENDING, '3': NodeState.PENDING, '4': NodeState.RUNNING, '5': NodeState.RUNNING, '6': NodeState.UNKNOWN, '7': NodeState.UNKNOWN, '8': NodeState.TERMINATED, '9': NodeState.UNKNOWN, '10': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_set_vm_memory", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/compute/drivers/vcloud.py", "focal_class": null, "focal_method": "ex_power_off_node", "tests": "import unittest\n\nclass Test_ex_power_off_node(unittest.TestCase):\n def test_ex_power_off(self):\n node = Node('https://vm-vcloud/api/vApp/vapp-8c57a5b6-e61b-48ca-8a78-3b70ee65ef6b', 'testNode', NodeState.RUNNING, [], [], self.driver)\n self.driver.ex_power_off_node(node)\n", "method_code": " def ex_power_off_node(self, node):\n \"\"\"\n Powers on all VMs under specified node. VMs need to be This operation\n is allowed only when the vApp/VM is powered on.\n \n @param node: The node to be powered off\n @type node: L{Node}\n \n @rtype: L{Node}\n \"\"\"\n return self._perform_power_operation(node, 'powerOff')\n ", "context": "class VCloud_1_5_NodeDriver(VCloudNodeDriver):\n def ex_power_off_node(self, node): ...\n def list_locations(self): ...\n def ex_find_node(self, node_name, vdcs=None): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def ex_deploy_node(self, node): ...\n def ex_undeploy_node(self, node): ...\n def ex_power_on_node(self, node): ...\n def ex_shutdown_node(self, node): ...\n def ex_suspend_node(self, node): ...\n def _perform_power_operation(self, node, operation): ...\n def ex_get_control_access(self, node): ...\n def ex_set_control_access(self, node, control_access): ...\n def ex_get_metadata(self, node): ...\n def ex_set_metadata_entry(self, node, key, value): ...\n def ex_query(self, type, filter=None, page=1, page_size=100, sort_asc=None, sort_desc=None): ...\n def create_node(self, **kwargs): ...\n def _instantiate_node(self, name, image, network_elem, vdc, vm_network, vm_fence): ...\n def _clone_node(self, name, sourceNode, vdc): ...\n def ex_set_vm_cpu(self, vapp_or_vm_id, vm_cpu): ...\n def ex_set_vm_memory(self, vapp_or_vm_id, vm_memory): ...\n def ex_add_vm_disk(self, vapp_or_vm_id, vm_disk_size): ...\n def _validate_vm_names(names): ...\n def _validate_vm_memory(vm_memory): ...\n def _validate_vm_cpu(vm_cpu): ...\n def _validate_vm_disk_size(vm_disk): ...\n def _validate_vm_script(vm_script): ...\n def _validate_vm_fence(vm_fence): ...\n def _validate_vm_ipmode(vm_ipmode): ...\n def _change_vm_names(self, vapp_or_vm_id, vm_names): ...\n def _change_vm_cpu(self, vapp_or_vm_id, vm_cpu): ...\n def _change_vm_memory(self, vapp_or_vm_id, vm_memory): ...\n def _add_vm_disk(self, vapp_or_vm_id, vm_disk): ...\n def _change_vm_script(self, vapp_or_vm_id, vm_script): ...\n def _change_vm_ipmode(self, vapp_or_vm_id, vm_ipmode): ...\n def _get_network_href(self, network_name): ...\n def _get_vm_elements(self, vapp_or_vm_id): ...\n def _is_node(self, node_or_image): ...\n def _to_node(self, node_elm): ...\n def _to_vdc(self, vdc_elm): ...\n\n connectionCls = VCloud_1_5_Connection\n NODE_STATE_MAP = {'-1': NodeState.UNKNOWN, '0': NodeState.PENDING, '1': NodeState.PENDING, '2': NodeState.PENDING, '3': NodeState.PENDING, '4': NodeState.RUNNING, '5': NodeState.RUNNING, '6': NodeState.UNKNOWN, '7': NodeState.UNKNOWN, '8': NodeState.TERMINATED, '9': NodeState.UNKNOWN, '10': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_power_off", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/compute/drivers/vcloud.py", "focal_class": null, "focal_method": "ex_query", "tests": "import unittest\n\nclass Test_ex_query(unittest.TestCase):\n def test_ex_query(self):\n results = self.driver.ex_query('user', filter='name==jrambo', page=2, page_size=30, sort_desc='startDate')\n self.assertEqual(len(results), 1)\n self.assertEqual(results[0]['type'], 'UserRecord')\n self.assertEqual(results[0]['name'], 'jrambo')\n self.assertEqual(results[0]['isLdapUser'], 'true')\n", "method_code": " def ex_query(self, type, filter=None, page=1, page_size=100, sort_asc=None, sort_desc=None):\n \"\"\"\n Queries vCloud for specified type. See http://www.vmware.com/pdf/vcd_15_api_guide.pdf\n for details. Each element of the returned list is a dictionary with all\n attributes from the record.\n \n @param type: type to query (r.g. user, group, vApp etc.)\n @type type: C{str}\n \n @param filter: filter expression (see documentation for syntax)\n @type filter: C{str}\n \n @param page: page number\n @type page: C{int}\n \n @param page_size: page size\n @type page_size: C{int}\n \n @param sort_asc: sort in ascending order by specified field\n @type sort_asc: C{str}\n \n @param sort_desc: sort in descending order by specified field\n @type sort_desc: C{str}\n \n @rtype: C{list} of dict\n \"\"\"\n params = {'type': type, 'pageSize': page_size, 'page': page}\n if sort_asc:\n params['sortAsc'] = sort_asc\n if sort_desc:\n params['sortDesc'] = sort_desc\n url = '/api/query?' + urlencode(params)\n if filter:\n if not filter.startswith('('):\n filter = '(' + filter + ')'\n url += '&filter=' + filter.replace(' ', '+')\n results = []\n res = self.connection.request(url)\n for elem in res.object:\n if not elem.tag.endswith('Link'):\n result = elem.attrib\n result['type'] = elem.tag.split('}')[1]\n results.append(result)\n return results\n ", "context": "class VCloud_1_5_NodeDriver(VCloudNodeDriver):\n def ex_query(self, type, filter=None, page=1, page_size=100, sort_asc=None, sort_desc=None): ...\n def list_locations(self): ...\n def ex_find_node(self, node_name, vdcs=None): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def ex_deploy_node(self, node): ...\n def ex_undeploy_node(self, node): ...\n def ex_power_off_node(self, node): ...\n def ex_power_on_node(self, node): ...\n def ex_shutdown_node(self, node): ...\n def ex_suspend_node(self, node): ...\n def _perform_power_operation(self, node, operation): ...\n def ex_get_control_access(self, node): ...\n def ex_set_control_access(self, node, control_access): ...\n def ex_get_metadata(self, node): ...\n def ex_set_metadata_entry(self, node, key, value): ...\n def create_node(self, **kwargs): ...\n def _instantiate_node(self, name, image, network_elem, vdc, vm_network, vm_fence): ...\n def _clone_node(self, name, sourceNode, vdc): ...\n def ex_set_vm_cpu(self, vapp_or_vm_id, vm_cpu): ...\n def ex_set_vm_memory(self, vapp_or_vm_id, vm_memory): ...\n def ex_add_vm_disk(self, vapp_or_vm_id, vm_disk_size): ...\n def _validate_vm_names(names): ...\n def _validate_vm_memory(vm_memory): ...\n def _validate_vm_cpu(vm_cpu): ...\n def _validate_vm_disk_size(vm_disk): ...\n def _validate_vm_script(vm_script): ...\n def _validate_vm_fence(vm_fence): ...\n def _validate_vm_ipmode(vm_ipmode): ...\n def _change_vm_names(self, vapp_or_vm_id, vm_names): ...\n def _change_vm_cpu(self, vapp_or_vm_id, vm_cpu): ...\n def _change_vm_memory(self, vapp_or_vm_id, vm_memory): ...\n def _add_vm_disk(self, vapp_or_vm_id, vm_disk): ...\n def _change_vm_script(self, vapp_or_vm_id, vm_script): ...\n def _change_vm_ipmode(self, vapp_or_vm_id, vm_ipmode): ...\n def _get_network_href(self, network_name): ...\n def _get_vm_elements(self, vapp_or_vm_id): ...\n def _is_node(self, node_or_image): ...\n def _to_node(self, node_elm): ...\n def _to_vdc(self, vdc_elm): ...\n\n connectionCls = VCloud_1_5_Connection\n NODE_STATE_MAP = {'-1': NodeState.UNKNOWN, '0': NodeState.PENDING, '1': NodeState.PENDING, '2': NodeState.PENDING, '3': NodeState.PENDING, '4': NodeState.RUNNING, '5': NodeState.RUNNING, '6': NodeState.UNKNOWN, '7': NodeState.UNKNOWN, '8': NodeState.TERMINATED, '9': NodeState.UNKNOWN, '10': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_query", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000782.py"} {"focal_file": "libcloud/compute/drivers/vcloud.py", "focal_class": null, "focal_method": "ex_get_control_access", "tests": "import unittest\n\nclass Test_ex_get_control_access(unittest.TestCase):\n def test_ex_get_control_access(self):\n node = Node('https://vm-vcloud/api/vApp/vapp-8c57a5b6-e61b-48ca-8a78-3b70ee65ef6b', 'testNode', NodeState.RUNNING, [], [], self.driver)\n control_access = self.driver.ex_get_control_access(node)\n self.assertEqual(control_access.everyone_access_level, ControlAccess.AccessLevel.READ_ONLY)\n self.assertEqual(len(control_access.subjects), 1)\n self.assertEqual(control_access.subjects[0].type, 'group')\n self.assertEqual(control_access.subjects[0].name, 'MyGroup')\n self.assertEqual(control_access.subjects[0].id, 'https://vm-vcloud/api/admin/group/b8202c48-7151-4e61-9a6c-155474c7d413')\n self.assertEqual(control_access.subjects[0].access_level, ControlAccess.AccessLevel.FULL_CONTROL)\n", "method_code": " def ex_get_control_access(self, node):\n \"\"\"\n Returns the control access settings for specified node.\n \n @param node: node to get the control access for\n @type node: L{Node}\n \n @rtype: L{ControlAccess}\n \"\"\"\n res = self.connection.request('%s/controlAccess' % get_url_path(node.id))\n everyone_access_level = None\n is_shared_elem = res.object.find(fixxpath(res.object, 'IsSharedToEveryone'))\n if is_shared_elem is not None and is_shared_elem.text == 'true':\n everyone_access_level = res.object.find(fixxpath(res.object, 'EveryoneAccessLevel')).text\n subjects = []\n for elem in res.object.findall(fixxpath(res.object, 'AccessSettings/AccessSetting')):\n access_level = elem.find(fixxpath(res.object, 'AccessLevel')).text\n subject_elem = elem.find(fixxpath(res.object, 'Subject'))\n if subject_elem.get('type') == 'application/vnd.vmware.admin.group+xml':\n subj_type = 'group'\n else:\n subj_type = 'user'\n res = self.connection.request(get_url_path(subject_elem.get('href')))\n name = res.object.get('name')\n subject = Subject(type=subj_type, name=name, access_level=access_level, id=subject_elem.get('href'))\n subjects.append(subject)\n return ControlAccess(node, everyone_access_level, subjects)\n ", "context": "class VCloud_1_5_NodeDriver(VCloudNodeDriver):\n def ex_get_control_access(self, node): ...\n def list_locations(self): ...\n def ex_find_node(self, node_name, vdcs=None): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def ex_deploy_node(self, node): ...\n def ex_undeploy_node(self, node): ...\n def ex_power_off_node(self, node): ...\n def ex_power_on_node(self, node): ...\n def ex_shutdown_node(self, node): ...\n def ex_suspend_node(self, node): ...\n def _perform_power_operation(self, node, operation): ...\n def ex_set_control_access(self, node, control_access): ...\n def ex_get_metadata(self, node): ...\n def ex_set_metadata_entry(self, node, key, value): ...\n def ex_query(self, type, filter=None, page=1, page_size=100, sort_asc=None, sort_desc=None): ...\n def create_node(self, **kwargs): ...\n def _instantiate_node(self, name, image, network_elem, vdc, vm_network, vm_fence): ...\n def _clone_node(self, name, sourceNode, vdc): ...\n def ex_set_vm_cpu(self, vapp_or_vm_id, vm_cpu): ...\n def ex_set_vm_memory(self, vapp_or_vm_id, vm_memory): ...\n def ex_add_vm_disk(self, vapp_or_vm_id, vm_disk_size): ...\n def _validate_vm_names(names): ...\n def _validate_vm_memory(vm_memory): ...\n def _validate_vm_cpu(vm_cpu): ...\n def _validate_vm_disk_size(vm_disk): ...\n def _validate_vm_script(vm_script): ...\n def _validate_vm_fence(vm_fence): ...\n def _validate_vm_ipmode(vm_ipmode): ...\n def _change_vm_names(self, vapp_or_vm_id, vm_names): ...\n def _change_vm_cpu(self, vapp_or_vm_id, vm_cpu): ...\n def _change_vm_memory(self, vapp_or_vm_id, vm_memory): ...\n def _add_vm_disk(self, vapp_or_vm_id, vm_disk): ...\n def _change_vm_script(self, vapp_or_vm_id, vm_script): ...\n def _change_vm_ipmode(self, vapp_or_vm_id, vm_ipmode): ...\n def _get_network_href(self, network_name): ...\n def _get_vm_elements(self, vapp_or_vm_id): ...\n def _is_node(self, node_or_image): ...\n def _to_node(self, node_elm): ...\n def _to_vdc(self, vdc_elm): ...\n\n connectionCls = VCloud_1_5_Connection\n NODE_STATE_MAP = {'-1': NodeState.UNKNOWN, '0': NodeState.PENDING, '1': NodeState.PENDING, '2': NodeState.PENDING, '3': NodeState.PENDING, '4': NodeState.RUNNING, '5': NodeState.RUNNING, '6': NodeState.UNKNOWN, '7': NodeState.UNKNOWN, '8': NodeState.TERMINATED, '9': NodeState.UNKNOWN, '10': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_get_control_access", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000783.py"} {"focal_file": "libcloud/compute/drivers/vcloud.py", "focal_class": "ControlAccess", "focal_method": "ex_set_control_access", "tests": "import unittest\n\nclass Test_ControlAccess_ex_set_control_access(unittest.TestCase):\n def test_ex_set_control_access(self):\n node = Node('https://vm-vcloud/api/vApp/vapp-8c57a5b6-e61b-48ca-8a78-3b70ee65ef6b', 'testNode', NodeState.RUNNING, [], [], self.driver)\n control_access = ControlAccess(node, None, [Subject(name='MyGroup', type='group', access_level=ControlAccess.AccessLevel.FULL_CONTROL)])\n self.driver.ex_set_control_access(node, control_access)\n", "method_code": " def ex_set_control_access(self, node, control_access):\n \"\"\"\n Sets control access for the specified node.\n \n @param node: node\n @type node: L{Node}\n \n @param control_access: control access settings\n @type control_access: L{ControlAccess}\n \n @rtype: C{None}\n \"\"\"\n xml = ET.Element('ControlAccessParams', {'xmlns': 'http://www.vmware.com/vcloud/v1.5'})\n shared_to_everyone = ET.SubElement(xml, 'IsSharedToEveryone')\n if control_access.everyone_access_level:\n shared_to_everyone.text = 'true'\n everyone_access_level = ET.SubElement(xml, 'EveryoneAccessLevel')\n everyone_access_level.text = control_access.everyone_access_level\n else:\n shared_to_everyone.text = 'false'\n if control_access.subjects:\n access_settings_elem = ET.SubElement(xml, 'AccessSettings')\n for subject in control_access.subjects:\n setting = ET.SubElement(access_settings_elem, 'AccessSetting')\n if subject.id:\n href = subject.id\n else:\n res = self.ex_query(type=subject.type, filter='name==' + subject.name)\n if not res:\n raise LibcloudError('Specified subject \"%s %s\" not found ' % (subject.type, subject.name))\n href = res[0]['href']\n ET.SubElement(setting, 'Subject', {'href': href})\n ET.SubElement(setting, 'AccessLevel').text = subject.access_level\n self.connection.request('%s/action/controlAccess' % get_url_path(node.id), data=ET.tostring(xml), headers={'Content-Type': 'application/vnd.vmware.vcloud.controlAccess+xml'}, method='POST')\n ", "context": "class VCloud_1_5_NodeDriver(VCloudNodeDriver):\n def ex_set_control_access(self, node, control_access): ...\n def list_locations(self): ...\n def ex_find_node(self, node_name, vdcs=None): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def ex_deploy_node(self, node): ...\n def ex_undeploy_node(self, node): ...\n def ex_power_off_node(self, node): ...\n def ex_power_on_node(self, node): ...\n def ex_shutdown_node(self, node): ...\n def ex_suspend_node(self, node): ...\n def _perform_power_operation(self, node, operation): ...\n def ex_get_control_access(self, node): ...\n def ex_get_metadata(self, node): ...\n def ex_set_metadata_entry(self, node, key, value): ...\n def ex_query(self, type, filter=None, page=1, page_size=100, sort_asc=None, sort_desc=None): ...\n def create_node(self, **kwargs): ...\n def _instantiate_node(self, name, image, network_elem, vdc, vm_network, vm_fence): ...\n def _clone_node(self, name, sourceNode, vdc): ...\n def ex_set_vm_cpu(self, vapp_or_vm_id, vm_cpu): ...\n def ex_set_vm_memory(self, vapp_or_vm_id, vm_memory): ...\n def ex_add_vm_disk(self, vapp_or_vm_id, vm_disk_size): ...\n def _validate_vm_names(names): ...\n def _validate_vm_memory(vm_memory): ...\n def _validate_vm_cpu(vm_cpu): ...\n def _validate_vm_disk_size(vm_disk): ...\n def _validate_vm_script(vm_script): ...\n def _validate_vm_fence(vm_fence): ...\n def _validate_vm_ipmode(vm_ipmode): ...\n def _change_vm_names(self, vapp_or_vm_id, vm_names): ...\n def _change_vm_cpu(self, vapp_or_vm_id, vm_cpu): ...\n def _change_vm_memory(self, vapp_or_vm_id, vm_memory): ...\n def _add_vm_disk(self, vapp_or_vm_id, vm_disk): ...\n def _change_vm_script(self, vapp_or_vm_id, vm_script): ...\n def _change_vm_ipmode(self, vapp_or_vm_id, vm_ipmode): ...\n def _get_network_href(self, network_name): ...\n def _get_vm_elements(self, vapp_or_vm_id): ...\n def _is_node(self, node_or_image): ...\n def _to_node(self, node_elm): ...\n def _to_vdc(self, vdc_elm): ...\n\n connectionCls = VCloud_1_5_Connection\n NODE_STATE_MAP = {'-1': NodeState.UNKNOWN, '0': NodeState.PENDING, '1': NodeState.PENDING, '2': NodeState.PENDING, '3': NodeState.PENDING, '4': NodeState.RUNNING, '5': NodeState.RUNNING, '6': NodeState.UNKNOWN, '7': NodeState.UNKNOWN, '8': NodeState.TERMINATED, '9': NodeState.UNKNOWN, '10': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_set_control_access", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/compute/drivers/vcloud.py", "focal_class": null, "focal_method": "ex_get_metadata", "tests": "import unittest\n\nclass Test_ex_get_metadata(unittest.TestCase):\n def test_ex_get_metadata(self):\n node = Node('https://vm-vcloud/api/vApp/vapp-8c57a5b6-e61b-48ca-8a78-3b70ee65ef6b', 'testNode', NodeState.RUNNING, [], [], self.driver)\n metadata = self.driver.ex_get_metadata(node)\n self.assertEqual(metadata, {'owners': 'msamia@netsuite.com'})\n", "method_code": " def ex_get_metadata(self, node):\n \"\"\"\n @param node: node\n @type node: L{Node}\n \n @return: dictionary mapping metadata keys to metadata values\n @rtype: dictionary mapping C{str} to C{str}\n \"\"\"\n res = self.connection.request('%s/metadata' % get_url_path(node.id))\n metadata_entries = res.object.findall(fixxpath(res.object, 'MetadataEntry'))\n res_dict = {}\n for entry in metadata_entries:\n key = entry.findtext(fixxpath(res.object, 'Key'))\n value = entry.findtext(fixxpath(res.object, 'Value'))\n res_dict[key] = value\n return res_dict\n ", "context": "class VCloud_1_5_NodeDriver(VCloudNodeDriver):\n def ex_get_metadata(self, node): ...\n def list_locations(self): ...\n def ex_find_node(self, node_name, vdcs=None): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def ex_deploy_node(self, node): ...\n def ex_undeploy_node(self, node): ...\n def ex_power_off_node(self, node): ...\n def ex_power_on_node(self, node): ...\n def ex_shutdown_node(self, node): ...\n def ex_suspend_node(self, node): ...\n def _perform_power_operation(self, node, operation): ...\n def ex_get_control_access(self, node): ...\n def ex_set_control_access(self, node, control_access): ...\n def ex_set_metadata_entry(self, node, key, value): ...\n def ex_query(self, type, filter=None, page=1, page_size=100, sort_asc=None, sort_desc=None): ...\n def create_node(self, **kwargs): ...\n def _instantiate_node(self, name, image, network_elem, vdc, vm_network, vm_fence): ...\n def _clone_node(self, name, sourceNode, vdc): ...\n def ex_set_vm_cpu(self, vapp_or_vm_id, vm_cpu): ...\n def ex_set_vm_memory(self, vapp_or_vm_id, vm_memory): ...\n def ex_add_vm_disk(self, vapp_or_vm_id, vm_disk_size): ...\n def _validate_vm_names(names): ...\n def _validate_vm_memory(vm_memory): ...\n def _validate_vm_cpu(vm_cpu): ...\n def _validate_vm_disk_size(vm_disk): ...\n def _validate_vm_script(vm_script): ...\n def _validate_vm_fence(vm_fence): ...\n def _validate_vm_ipmode(vm_ipmode): ...\n def _change_vm_names(self, vapp_or_vm_id, vm_names): ...\n def _change_vm_cpu(self, vapp_or_vm_id, vm_cpu): ...\n def _change_vm_memory(self, vapp_or_vm_id, vm_memory): ...\n def _add_vm_disk(self, vapp_or_vm_id, vm_disk): ...\n def _change_vm_script(self, vapp_or_vm_id, vm_script): ...\n def _change_vm_ipmode(self, vapp_or_vm_id, vm_ipmode): ...\n def _get_network_href(self, network_name): ...\n def _get_vm_elements(self, vapp_or_vm_id): ...\n def _is_node(self, node_or_image): ...\n def _to_node(self, node_elm): ...\n def _to_vdc(self, vdc_elm): ...\n\n connectionCls = VCloud_1_5_Connection\n NODE_STATE_MAP = {'-1': NodeState.UNKNOWN, '0': NodeState.PENDING, '1': NodeState.PENDING, '2': NodeState.PENDING, '3': NodeState.PENDING, '4': NodeState.RUNNING, '5': NodeState.RUNNING, '6': NodeState.UNKNOWN, '7': NodeState.UNKNOWN, '8': NodeState.TERMINATED, '9': NodeState.UNKNOWN, '10': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_get_metadata", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000785.py"} {"focal_file": "libcloud/compute/drivers/vcloud.py", "focal_class": null, "focal_method": "ex_set_metadata_entry", "tests": "import unittest\n\nclass Test_ex_set_metadata_entry(unittest.TestCase):\n def test_ex_set_metadata_entry(self):\n node = Node('https://vm-vcloud/api/vApp/vapp-8c57a5b6-e61b-48ca-8a78-3b70ee65ef6b', 'testNode', NodeState.RUNNING, [], [], self.driver)\n self.driver.ex_set_metadata_entry(node, 'foo', 'bar')\n", "method_code": " def ex_set_metadata_entry(self, node, key, value):\n \"\"\"\n @param node: node\n @type node: L{Node}\n \n @param key: metadata key to be set\n @type key: C{str}\n \n @param value: metadata value to be set\n @type value: C{str}\n \n @rtype: C{None}\n \"\"\"\n metadata_elem = ET.Element('Metadata', {'xmlns': 'http://www.vmware.com/vcloud/v1.5', 'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance'})\n entry = ET.SubElement(metadata_elem, 'MetadataEntry')\n key_elem = ET.SubElement(entry, 'Key')\n key_elem.text = key\n value_elem = ET.SubElement(entry, 'Value')\n value_elem.text = value\n res = self.connection.request('%s/metadata' % get_url_path(node.id), data=ET.tostring(metadata_elem), headers={'Content-Type': 'application/vnd.vmware.vcloud.metadata+xml'}, method='POST')\n self._wait_for_task_completion(res.object.get('href'))\n ", "context": "class VCloud_1_5_NodeDriver(VCloudNodeDriver):\n def ex_set_metadata_entry(self, node, key, value): ...\n def list_locations(self): ...\n def ex_find_node(self, node_name, vdcs=None): ...\n def destroy_node(self, node): ...\n def reboot_node(self, node): ...\n def ex_deploy_node(self, node): ...\n def ex_undeploy_node(self, node): ...\n def ex_power_off_node(self, node): ...\n def ex_power_on_node(self, node): ...\n def ex_shutdown_node(self, node): ...\n def ex_suspend_node(self, node): ...\n def _perform_power_operation(self, node, operation): ...\n def ex_get_control_access(self, node): ...\n def ex_set_control_access(self, node, control_access): ...\n def ex_get_metadata(self, node): ...\n def ex_query(self, type, filter=None, page=1, page_size=100, sort_asc=None, sort_desc=None): ...\n def create_node(self, **kwargs): ...\n def _instantiate_node(self, name, image, network_elem, vdc, vm_network, vm_fence): ...\n def _clone_node(self, name, sourceNode, vdc): ...\n def ex_set_vm_cpu(self, vapp_or_vm_id, vm_cpu): ...\n def ex_set_vm_memory(self, vapp_or_vm_id, vm_memory): ...\n def ex_add_vm_disk(self, vapp_or_vm_id, vm_disk_size): ...\n def _validate_vm_names(names): ...\n def _validate_vm_memory(vm_memory): ...\n def _validate_vm_cpu(vm_cpu): ...\n def _validate_vm_disk_size(vm_disk): ...\n def _validate_vm_script(vm_script): ...\n def _validate_vm_fence(vm_fence): ...\n def _validate_vm_ipmode(vm_ipmode): ...\n def _change_vm_names(self, vapp_or_vm_id, vm_names): ...\n def _change_vm_cpu(self, vapp_or_vm_id, vm_cpu): ...\n def _change_vm_memory(self, vapp_or_vm_id, vm_memory): ...\n def _add_vm_disk(self, vapp_or_vm_id, vm_disk): ...\n def _change_vm_script(self, vapp_or_vm_id, vm_script): ...\n def _change_vm_ipmode(self, vapp_or_vm_id, vm_ipmode): ...\n def _get_network_href(self, network_name): ...\n def _get_vm_elements(self, vapp_or_vm_id): ...\n def _is_node(self, node_or_image): ...\n def _to_node(self, node_elm): ...\n def _to_vdc(self, vdc_elm): ...\n\n connectionCls = VCloud_1_5_Connection\n NODE_STATE_MAP = {'-1': NodeState.UNKNOWN, '0': NodeState.PENDING, '1': NodeState.PENDING, '2': NodeState.PENDING, '3': NodeState.PENDING, '4': NodeState.RUNNING, '5': NodeState.RUNNING, '6': NodeState.UNKNOWN, '7': NodeState.UNKNOWN, '8': NodeState.TERMINATED, '9': NodeState.UNKNOWN, '10': NodeState.UNKNOWN}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_set_metadata_entry", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/compute/drivers/voxel.py", "focal_class": null, "focal_method": "list_nodes", "tests": "import unittest\n\nclass Test_list_nodes(unittest.TestCase):\n def test_list_nodes(self):\n VoxelMockHttp.type = 'LIST_NODES'\n nodes = self.driver.list_nodes()\n self.assertEqual(len(nodes), 1)\n self.assertEqual(nodes[0].name, 'www.voxel.net')\n", "method_code": " def list_nodes(self):\n params = {'method': 'voxel.devices.list'}\n result = self.connection.request('/', params=params).object\n return self._to_nodes(result)\n ", "context": "class VoxelNodeDriver(NodeDriver):\n def list_nodes(self): ...\n def _initialize_instance_types(): ...\n def list_sizes(self, location=None): ...\n def list_images(self, location=None): ...\n def create_node(self, **kwargs): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def list_locations(self): ...\n def _getstatus(self, element): ...\n def _to_locations(self, object): ...\n def _to_nodes(self, object): ...\n def _to_images(self, object): ...\n\n connectionCls = VoxelConnection\n type = Provider.VOXEL\n name = 'Voxel VoxCLOUD'\n website = 'http://www.voxel.net/'\n features = {'create_node': [], 'list_sizes': ['variable_disk']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_nodes", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000787.py"} {"focal_file": "libcloud/compute/drivers/voxel.py", "focal_class": null, "focal_method": "list_sizes", "tests": "import unittest\n\nclass Test_list_sizes(unittest.TestCase):\n def test_list_sizes(self):\n sizes = self.driver.list_sizes()\n self.assertEqual(len(sizes), 13)\n", "method_code": " def list_sizes(self, location=None):\n return [NodeSize(driver=self.connection.driver, **i) for i in list(VOXEL_INSTANCE_TYPES.values())]\n ", "context": "class VoxelNodeDriver(NodeDriver):\n def list_sizes(self, location=None): ...\n def _initialize_instance_types(): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def create_node(self, **kwargs): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def list_locations(self): ...\n def _getstatus(self, element): ...\n def _to_locations(self, object): ...\n def _to_nodes(self, object): ...\n def _to_images(self, object): ...\n\n connectionCls = VoxelConnection\n type = Provider.VOXEL\n name = 'Voxel VoxCLOUD'\n website = 'http://www.voxel.net/'\n features = {'create_node': [], 'list_sizes': ['variable_disk']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_sizes", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000788.py"} {"focal_file": "libcloud/compute/drivers/voxel.py", "focal_class": null, "focal_method": "list_images", "tests": "import unittest\n\nclass Test_list_images(unittest.TestCase):\n def test_list_images(self):\n VoxelMockHttp.type = 'LIST_IMAGES'\n images = self.driver.list_images()\n self.assertEqual(len(images), 1)\n", "method_code": " def list_images(self, location=None):\n params = {'method': 'voxel.images.list'}\n result = self.connection.request('/', params=params).object\n return self._to_images(result)\n ", "context": "class VoxelNodeDriver(NodeDriver):\n def list_images(self, location=None): ...\n def _initialize_instance_types(): ...\n def list_nodes(self): ...\n def list_sizes(self, location=None): ...\n def create_node(self, **kwargs): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def list_locations(self): ...\n def _getstatus(self, element): ...\n def _to_locations(self, object): ...\n def _to_nodes(self, object): ...\n def _to_images(self, object): ...\n\n connectionCls = VoxelConnection\n type = Provider.VOXEL\n name = 'Voxel VoxCLOUD'\n website = 'http://www.voxel.net/'\n features = {'create_node': [], 'list_sizes': ['variable_disk']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_images", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000789.py"} {"focal_file": "libcloud/compute/drivers/voxel.py", "focal_class": null, "focal_method": "list_locations", "tests": "import unittest\n\nclass Test_list_locations(unittest.TestCase):\n def test_list_locations(self):\n VoxelMockHttp.type = 'LIST_LOCATIONS'\n locations = self.driver.list_locations()\n self.assertEqual(len(locations), 2)\n self.assertEqual(locations[0].name, 'Amsterdam')\n", "method_code": " def list_locations(self):\n params = {'method': 'voxel.voxcloud.facilities.list'}\n result = self.connection.request('/', params=params).object\n nodes = self._to_locations(result)\n return nodes\n ", "context": "class VoxelNodeDriver(NodeDriver):\n def list_locations(self): ...\n def _initialize_instance_types(): ...\n def list_nodes(self): ...\n def list_sizes(self, location=None): ...\n def list_images(self, location=None): ...\n def create_node(self, **kwargs): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def _getstatus(self, element): ...\n def _to_locations(self, object): ...\n def _to_nodes(self, object): ...\n def _to_images(self, object): ...\n\n connectionCls = VoxelConnection\n type = Provider.VOXEL\n name = 'Voxel VoxCLOUD'\n website = 'http://www.voxel.net/'\n features = {'create_node': [], 'list_sizes': ['variable_disk']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_locations", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000790.py"} {"focal_file": "libcloud/compute/drivers/voxel.py", "focal_class": null, "focal_method": "create_node", "tests": "import unittest\n\nclass Test_create_node(unittest.TestCase):\n def test_create_node(self):\n VoxelMockHttp.type = 'CREATE_NODE'\n image = NodeImage(id=1, name='Ubuntu 8.10 (intrepid)', driver=self.driver)\n size = NodeSize(1, '256 slice', 1024, 500, None, None, driver=self.driver)\n location = NodeLocation(id=1, name='Europe', country='England', driver=self.driver)\n node = self.driver.create_node(name='foo', image=image, size=size, location=location)\n self.assertEqual(node.id, '1234')\n node = self.driver.create_node(name='foo', image=image, size=size, location=location, voxel_access=True)\n self.assertEqual(node.id, '1234')\n", "method_code": " def create_node(self, **kwargs):\n \"\"\"Create Voxel Node\n \n @keyword name: the name to assign the node (mandatory)\n @type name: C{str}\n \n @keyword image: distribution to deploy\n @type image: L{NodeImage}\n \n @keyword size: the plan size to create (mandatory)\n Requires size.disk (GB) to be set manually\n @type size: L{NodeSize}\n \n @keyword location: which datacenter to create the node in\n @type location: L{NodeLocation}\n \n @keyword ex_privateip: Backend IP address to assign to node;\n must be chosen from the customer's\n private VLAN assignment.\n @type ex_privateip: C{str}\n \n @keyword ex_publicip: Public-facing IP address to assign to node;\n must be chosen from the customer's\n public VLAN assignment.\n @type ex_publicip: C{str}\n \n @keyword ex_rootpass: Password for root access; generated if unset.\n @type ex_rootpass: C{str}\n \n @keyword ex_consolepass: Password for remote console;\n generated if unset.\n @type ex_consolepass: C{str}\n \n @keyword ex_sshuser: Username for SSH access\n @type ex_sshuser: C{str}\n \n @keyword ex_sshpass: Password for SSH access; generated if unset.\n @type ex_sshpass: C{str}\n \n @keyword ex_voxel_access: Allow access Voxel administrative access.\n Defaults to False.\n @type ex_voxel_access: C{bool}\n \n @rtype: L{Node} or C{None}\n \"\"\"\n if not kwargs['size'].disk:\n raise ValueError('size.disk must be non-zero')\n voxel_access = kwargs.get('ex_voxel_access', None)\n if voxel_access is not None:\n voxel_access = 'true' if voxel_access else 'false'\n params = {'method': 'voxel.voxcloud.create', 'hostname': kwargs['name'], 'disk_size': int(kwargs['size'].disk), 'facility': kwargs['location'].id, 'image_id': kwargs['image'].id, 'processing_cores': kwargs['size'].ram / RAM_PER_CPU, 'backend_ip': kwargs.get('ex_privateip', None), 'frontend_ip': kwargs.get('ex_publicip', None), 'admin_password': kwargs.get('ex_rootpass', None), 'console_password': kwargs.get('ex_consolepass', None), 'ssh_username': kwargs.get('ex_sshuser', None), 'ssh_password': kwargs.get('ex_sshpass', None), 'voxel_access': voxel_access}\n object = self.connection.request('/', params=params).object\n if self._getstatus(object):\n return Node(id=object.findtext('device/id'), name=kwargs['name'], state=NODE_STATE_MAP[object.findtext('device/status')], public_ips=kwargs.get('publicip', None), private_ips=kwargs.get('privateip', None), driver=self.connection.driver)\n else:\n return None\n ", "context": "class VoxelNodeDriver(NodeDriver):\n def create_node(self, **kwargs): ...\n def _initialize_instance_types(): ...\n def list_nodes(self): ...\n def list_sizes(self, location=None): ...\n def list_images(self, location=None): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def list_locations(self): ...\n def _getstatus(self, element): ...\n def _to_locations(self, object): ...\n def _to_nodes(self, object): ...\n def _to_images(self, object): ...\n\n connectionCls = VoxelConnection\n type = Provider.VOXEL\n name = 'Voxel VoxCLOUD'\n website = 'http://www.voxel.net/'\n features = {'create_node': [], 'list_sizes': ['variable_disk']}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000791.py"} {"focal_file": "libcloud/compute/drivers/vpsnet.py", "focal_class": null, "focal_method": "create_node", "tests": "import unittest\n\nclass Test_create_node(unittest.TestCase):\n def test_create_node(self):\n VPSNetMockHttp.type = 'create'\n image = self.driver.list_images()[0]\n size = self.driver.list_sizes()[0]\n node = self.driver.create_node('foo', image, size)\n self.assertEqual(node.name, 'foo')\n", "method_code": " def create_node(self, name, image, size, **kwargs):\n \"\"\"Create a new VPS.net node\n \n @inherits: L{NodeDriver.create_node}\n \n @keyword ex_backups_enabled: Enable automatic backups\n @type ex_backups_enabled: C{bool}\n \n @keyword ex_fqdn: Fully Qualified domain of the node\n @type ex_fqdn: C{str}\n \"\"\"\n headers = {'Content-Type': 'application/json'}\n request = {'virtual_machine': {'label': name, 'fqdn': kwargs.get('ex_fqdn', ''), 'system_template_id': image.id, 'backups_enabled': kwargs.get('ex_backups_enabled', 0), 'slices_required': size.id}}\n res = self.connection.request('/virtual_machines.%s' % (API_VERSION,), data=json.dumps(request), headers=headers, method='POST')\n node = self._to_node(res.object['virtual_machine'])\n return node\n ", "context": "class VPSNetNodeDriver(NodeDriver):\n def create_node(self, name, image, size, **kwargs): ...\n def _to_node(self, vm): ...\n def _to_image(self, image, cloud): ...\n def _to_size(self, num): ...\n def _get_price_per_node(self, num): ...\n def reboot_node(self, node): ...\n def list_sizes(self, location=None): ...\n def destroy_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def list_locations(self): ...\n\n type = Provider.VPSNET\n api_name = 'vps_net'\n name = 'vps.net'\n website = 'http://vps.net/'\n connectionCls = VPSNetConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000792.py"} {"focal_file": "libcloud/compute/drivers/vpsnet.py", "focal_class": null, "focal_method": "list_nodes", "tests": "import unittest\n\nclass Test_list_nodes(unittest.TestCase):\n def test_list_nodes(self):\n VPSNetMockHttp.type = 'virtual_machines'\n node = self.driver.list_nodes()[0]\n self.assertEqual(node.id, '1384')\n self.assertEqual(node.state, NodeState.RUNNING)\n", "method_code": " def list_nodes(self):\n res = self.connection.request('/virtual_machines.%s' % (API_VERSION,))\n return [self._to_node(i['virtual_machine']) for i in res.object]\n ", "context": "class VPSNetNodeDriver(NodeDriver):\n def list_nodes(self): ...\n def _to_node(self, vm): ...\n def _to_image(self, image, cloud): ...\n def _to_size(self, num): ...\n def _get_price_per_node(self, num): ...\n def create_node(self, name, image, size, **kwargs): ...\n def reboot_node(self, node): ...\n def list_sizes(self, location=None): ...\n def destroy_node(self, node): ...\n def list_images(self, location=None): ...\n def list_locations(self): ...\n\n type = Provider.VPSNET\n api_name = 'vps_net'\n name = 'vps.net'\n website = 'http://vps.net/'\n connectionCls = VPSNetConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_nodes", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000793.py"} {"focal_file": "libcloud/compute/drivers/vpsnet.py", "focal_class": null, "focal_method": "reboot_node", "tests": "import unittest\n\nclass Test_reboot_node(unittest.TestCase):\n def test_reboot_node(self):\n VPSNetMockHttp.type = 'virtual_machines'\n node = self.driver.list_nodes()[0]\n VPSNetMockHttp.type = 'reboot'\n ret = self.driver.reboot_node(node)\n self.assertEqual(ret, True)\n", "method_code": " def reboot_node(self, node):\n res = self.connection.request('/virtual_machines/%s/%s.%s' % (node.id, 'reboot', API_VERSION), method='POST')\n node = self._to_node(res.object['virtual_machine'])\n return True\n ", "context": "class VPSNetNodeDriver(NodeDriver):\n def reboot_node(self, node): ...\n def _to_node(self, vm): ...\n def _to_image(self, image, cloud): ...\n def _to_size(self, num): ...\n def _get_price_per_node(self, num): ...\n def create_node(self, name, image, size, **kwargs): ...\n def list_sizes(self, location=None): ...\n def destroy_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def list_locations(self): ...\n\n type = Provider.VPSNET\n api_name = 'vps_net'\n name = 'vps.net'\n website = 'http://vps.net/'\n connectionCls = VPSNetConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_reboot_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000794.py"} {"focal_file": "libcloud/compute/drivers/vpsnet.py", "focal_class": null, "focal_method": "destroy_node", "tests": "import unittest\n\nclass Test_destroy_node(unittest.TestCase):\n def test_destroy_node(self):\n VPSNetMockHttp.type = 'delete'\n node = Node('2222', None, None, None, None, self.driver)\n ret = self.driver.destroy_node(node)\n self.assertTrue(ret)\n VPSNetMockHttp.type = 'delete_fail'\n node = Node('2223', None, None, None, None, self.driver)\n self.assertRaises(Exception, self.driver.destroy_node, node)\n\n def test_destroy_node_response(self):\n node = Node('2222', None, None, None, None, self.driver)\n VPSNetMockHttp.type = 'delete'\n ret = self.driver.destroy_node(node)\n self.assertTrue(isinstance(ret, bool))\n", "method_code": " def destroy_node(self, node):\n res = self.connection.request('/virtual_machines/%s.%s' % (node.id, API_VERSION), method='DELETE')\n return res.status == 200\n ", "context": "class VPSNetNodeDriver(NodeDriver):\n def destroy_node(self, node): ...\n def _to_node(self, vm): ...\n def _to_image(self, image, cloud): ...\n def _to_size(self, num): ...\n def _get_price_per_node(self, num): ...\n def create_node(self, name, image, size, **kwargs): ...\n def reboot_node(self, node): ...\n def list_sizes(self, location=None): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def list_locations(self): ...\n\n type = Provider.VPSNET\n api_name = 'vps_net'\n name = 'vps.net'\n website = 'http://vps.net/'\n connectionCls = VPSNetConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_destroy_node", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000795.py"} {"focal_file": "libcloud/compute/drivers/vpsnet.py", "focal_class": null, "focal_method": "list_images", "tests": "import unittest\n\nclass Test_list_images(unittest.TestCase):\n def test_list_images(self):\n VPSNetMockHttp.type = 'templates'\n ret = self.driver.list_images()\n self.assertEqual(ret[0].id, '9')\n self.assertEqual(ret[-1].id, '160')\n", "method_code": " def list_images(self, location=None):\n res = self.connection.request('/available_clouds.%s' % (API_VERSION,))\n images = []\n for cloud in res.object:\n label = cloud['cloud']['label']\n templates = cloud['cloud']['system_templates']\n images.extend([self._to_image(image, label) for image in templates])\n return images\n ", "context": "class VPSNetNodeDriver(NodeDriver):\n def list_images(self, location=None): ...\n def _to_node(self, vm): ...\n def _to_image(self, image, cloud): ...\n def _to_size(self, num): ...\n def _get_price_per_node(self, num): ...\n def create_node(self, name, image, size, **kwargs): ...\n def reboot_node(self, node): ...\n def list_sizes(self, location=None): ...\n def destroy_node(self, node): ...\n def list_nodes(self): ...\n def list_locations(self): ...\n\n type = Provider.VPSNET\n api_name = 'vps_net'\n name = 'vps.net'\n website = 'http://vps.net/'\n connectionCls = VPSNetConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_images", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000796.py"} {"focal_file": "libcloud/compute/drivers/vpsnet.py", "focal_class": null, "focal_method": "list_sizes", "tests": "import unittest\n\nclass Test_list_sizes(unittest.TestCase):\n def test_list_sizes(self):\n VPSNetMockHttp.type = 'sizes'\n ret = self.driver.list_sizes()\n self.assertEqual(len(ret), 1)\n self.assertEqual(ret[0].id, '1')\n self.assertEqual(ret[0].name, '1 Node')\n", "method_code": " def list_sizes(self, location=None):\n res = self.connection.request('/nodes.%s' % (API_VERSION,))\n available_nodes = len([size for size in res.object if size['slice']['virtual_machine_id']])\n sizes = [self._to_size(i) for i in range(1, available_nodes + 1)]\n return sizes\n ", "context": "class VPSNetNodeDriver(NodeDriver):\n def list_sizes(self, location=None): ...\n def _to_node(self, vm): ...\n def _to_image(self, image, cloud): ...\n def _to_size(self, num): ...\n def _get_price_per_node(self, num): ...\n def create_node(self, name, image, size, **kwargs): ...\n def reboot_node(self, node): ...\n def destroy_node(self, node): ...\n def list_nodes(self): ...\n def list_images(self, location=None): ...\n def list_locations(self): ...\n\n type = Provider.VPSNET\n api_name = 'vps_net'\n name = 'vps.net'\n website = 'http://vps.net/'\n connectionCls = VPSNetConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_sizes", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000797.py"} {"focal_file": "libcloud/dns/drivers/gandi.py", "focal_class": null, "focal_method": "list_zones", "tests": "import unittest\n\nclass Test_list_zones(unittest.TestCase):\n def test_list_zones(self):\n zones = self.driver.list_zones()\n self.assertEqual(len(zones), 5)\n zone = zones[0]\n self.assertEqual(zone.id, '47234')\n self.assertEqual(zone.type, 'master')\n self.assertEqual(zone.domain, 't.com')\n", "method_code": " def list_zones(self):\n zones = self.connection.request('domain.zone.list')\n return self._to_zones(zones.object)\n ", "context": "class GandiDNSDriver(BaseGandiDriverDNSDriver):\n def list_zones(self): ...\n def _to_zone(self, zone): ...\n def _to_zones(self, zones): ...\n def get_zone(self, zone_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def delete_zone(self, zone): ...\n def _to_record(self, record, zone): ...\n def _to_records(self, records, zone): ...\n def list_records(self, zone): ...\n def get_record(self, zone_id, record_id): ...\n def _validate_record(self, record_id, name, record_type, data, extra): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name, type, data, extra): ...\n def delete_record(self, record): ...\n\n type = Provider.GANDI\n name = 'Gandi DNS'\n website = 'http://www.gandi.net/domain'\n connectionCls = GandiDNSConnection\n RECORD_TYPE_MAP = {RecordType.NS: 'NS', RecordType.MX: 'MX', RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV', RecordType.SPF: 'SPF', RecordType.WKS: 'WKS', RecordType.LOC: 'LOC'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_zones", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000798.py"} {"focal_file": "libcloud/dns/drivers/gandi.py", "focal_class": null, "focal_method": "list_records", "tests": "import unittest\n\nclass Test_list_records(unittest.TestCase):\n def test_list_records(self):\n zone = self.driver.list_zones()[0]\n records = self.driver.list_records(zone=zone)\n self.assertEqual(len(records), 3)\n record = records[1]\n self.assertEqual(record.name, 'www')\n self.assertEqual(record.id, 'A:www')\n self.assertEqual(record.type, RecordType.A)\n self.assertEqual(record.data, '208.111.35.173')\n", "method_code": " def list_records(self, zone):\n zid = int(zone.id)\n self.connection.set_context({'zone_id': zone.id})\n records = self.connection.request('domain.zone.record.list', zid, 0)\n return self._to_records(records.object, zone)\n ", "context": "class GandiDNSDriver(BaseGandiDriverDNSDriver):\n def list_records(self, zone): ...\n def _to_zone(self, zone): ...\n def _to_zones(self, zones): ...\n def list_zones(self): ...\n def get_zone(self, zone_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def delete_zone(self, zone): ...\n def _to_record(self, record, zone): ...\n def _to_records(self, records, zone): ...\n def get_record(self, zone_id, record_id): ...\n def _validate_record(self, record_id, name, record_type, data, extra): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name, type, data, extra): ...\n def delete_record(self, record): ...\n\n type = Provider.GANDI\n name = 'Gandi DNS'\n website = 'http://www.gandi.net/domain'\n connectionCls = GandiDNSConnection\n RECORD_TYPE_MAP = {RecordType.NS: 'NS', RecordType.MX: 'MX', RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV', RecordType.SPF: 'SPF', RecordType.WKS: 'WKS', RecordType.LOC: 'LOC'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_records", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000799.py"} {"focal_file": "libcloud/dns/drivers/gandi.py", "focal_class": null, "focal_method": "get_zone", "tests": "import unittest\n\nclass Test_get_zone(unittest.TestCase):\n def test_get_zone(self):\n zone = self.driver.get_zone(zone_id='47234')\n self.assertEqual(zone.id, '47234')\n self.assertEqual(zone.type, 'master')\n self.assertEqual(zone.domain, 't.com')\n", "method_code": " def get_zone(self, zone_id):\n zid = int(zone_id)\n self.connection.set_context({'zone_id': zone_id})\n zone = self.connection.request('domain.zone.info', zid)\n return self._to_zone(zone.object)\n ", "context": "class GandiDNSDriver(BaseGandiDriverDNSDriver):\n def get_zone(self, zone_id): ...\n def _to_zone(self, zone): ...\n def _to_zones(self, zones): ...\n def list_zones(self): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def delete_zone(self, zone): ...\n def _to_record(self, record, zone): ...\n def _to_records(self, records, zone): ...\n def list_records(self, zone): ...\n def get_record(self, zone_id, record_id): ...\n def _validate_record(self, record_id, name, record_type, data, extra): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name, type, data, extra): ...\n def delete_record(self, record): ...\n\n type = Provider.GANDI\n name = 'Gandi DNS'\n website = 'http://www.gandi.net/domain'\n connectionCls = GandiDNSConnection\n RECORD_TYPE_MAP = {RecordType.NS: 'NS', RecordType.MX: 'MX', RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV', RecordType.SPF: 'SPF', RecordType.WKS: 'WKS', RecordType.LOC: 'LOC'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_get_zone", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000800.py"} {"focal_file": "libcloud/dns/drivers/gandi.py", "focal_class": null, "focal_method": "get_record", "tests": "import unittest\n\nclass Test_get_record(unittest.TestCase):\n def test_get_record(self):\n record = self.driver.get_record(zone_id='47234', record_id='CNAME:t.com')\n self.assertEqual(record.name, 'wibble')\n self.assertEqual(record.type, RecordType.CNAME)\n self.assertEqual(record.data, 't.com')\n", "method_code": " def get_record(self, zone_id, record_id):\n zid = int(zone_id)\n record_type, name = record_id.split(':', 1)\n filter_opts = {'name': name, 'type': record_type}\n self.connection.set_context({'zone_id': zone_id})\n records = self.connection.request('domain.zone.record.list', zid, 0, filter_opts).object\n if len(records) == 0:\n raise RecordDoesNotExistError(value='', driver=self, record_id=record_id)\n return self._to_record(records[0], self.get_zone(zone_id))\n ", "context": "class GandiDNSDriver(BaseGandiDriverDNSDriver):\n def get_record(self, zone_id, record_id): ...\n def _to_zone(self, zone): ...\n def _to_zones(self, zones): ...\n def list_zones(self): ...\n def get_zone(self, zone_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def delete_zone(self, zone): ...\n def _to_record(self, record, zone): ...\n def _to_records(self, records, zone): ...\n def list_records(self, zone): ...\n def _validate_record(self, record_id, name, record_type, data, extra): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name, type, data, extra): ...\n def delete_record(self, record): ...\n\n type = Provider.GANDI\n name = 'Gandi DNS'\n website = 'http://www.gandi.net/domain'\n connectionCls = GandiDNSConnection\n RECORD_TYPE_MAP = {RecordType.NS: 'NS', RecordType.MX: 'MX', RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV', RecordType.SPF: 'SPF', RecordType.WKS: 'WKS', RecordType.LOC: 'LOC'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_get_record", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000801.py"} {"focal_file": "libcloud/dns/drivers/gandi.py", "focal_class": null, "focal_method": "create_zone", "tests": "import unittest\n\nclass Test_create_zone(unittest.TestCase):\n def test_create_zone(self):\n zone = self.driver.create_zone(domain='t.com', type='master', ttl=None, extra=None)\n self.assertEqual(zone.id, '47234')\n self.assertEqual(zone.domain, 't.com')\n", "method_code": " def create_zone(self, domain, type='master', ttl=None, extra=None):\n params = {'name': domain}\n info = self.connection.request('domain.zone.create', params)\n return self._to_zone(info.object)\n ", "context": "class GandiDNSDriver(BaseGandiDriverDNSDriver):\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def _to_zone(self, zone): ...\n def _to_zones(self, zones): ...\n def list_zones(self): ...\n def get_zone(self, zone_id): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def delete_zone(self, zone): ...\n def _to_record(self, record, zone): ...\n def _to_records(self, records, zone): ...\n def list_records(self, zone): ...\n def get_record(self, zone_id, record_id): ...\n def _validate_record(self, record_id, name, record_type, data, extra): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name, type, data, extra): ...\n def delete_record(self, record): ...\n\n type = Provider.GANDI\n name = 'Gandi DNS'\n website = 'http://www.gandi.net/domain'\n connectionCls = GandiDNSConnection\n RECORD_TYPE_MAP = {RecordType.NS: 'NS', RecordType.MX: 'MX', RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV', RecordType.SPF: 'SPF', RecordType.WKS: 'WKS', RecordType.LOC: 'LOC'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_zone", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000802.py"} {"focal_file": "libcloud/dns/drivers/gandi.py", "focal_class": null, "focal_method": "update_zone", "tests": "import unittest\n\nclass Test_update_zone(unittest.TestCase):\n def test_update_zone(self):\n zone = self.driver.get_zone(zone_id='47234')\n zone = self.driver.update_zone(zone, domain='t.com')\n self.assertEqual(zone.id, '47234')\n self.assertEqual(zone.type, 'master')\n self.assertEqual(zone.domain, 't.com')\n", "method_code": " def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None):\n zid = int(zone.id)\n params = {'name': domain}\n self.connection.set_context({'zone_id': zone.id})\n zone = self.connection.request('domain.zone.update', zid, params)\n return self._to_zone(zone.object)\n ", "context": "class GandiDNSDriver(BaseGandiDriverDNSDriver):\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def _to_zone(self, zone): ...\n def _to_zones(self, zones): ...\n def list_zones(self): ...\n def get_zone(self, zone_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def delete_zone(self, zone): ...\n def _to_record(self, record, zone): ...\n def _to_records(self, records, zone): ...\n def list_records(self, zone): ...\n def get_record(self, zone_id, record_id): ...\n def _validate_record(self, record_id, name, record_type, data, extra): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name, type, data, extra): ...\n def delete_record(self, record): ...\n\n type = Provider.GANDI\n name = 'Gandi DNS'\n website = 'http://www.gandi.net/domain'\n connectionCls = GandiDNSConnection\n RECORD_TYPE_MAP = {RecordType.NS: 'NS', RecordType.MX: 'MX', RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV', RecordType.SPF: 'SPF', RecordType.WKS: 'WKS', RecordType.LOC: 'LOC'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_update_zone", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000803.py"} {"focal_file": "libcloud/dns/drivers/gandi.py", "focal_class": null, "focal_method": "create_record", "tests": "import unittest\n\nclass Test_create_record(unittest.TestCase):\n def test_create_record(self):\n zone = self.driver.list_zones()[0]\n record = self.driver.create_record(name='www', zone=zone, type=RecordType.A, data='127.0.0.1', extra={'ttl': 30})\n self.assertEqual(record.id, 'A:www')\n self.assertEqual(record.name, 'www')\n self.assertEqual(record.zone, zone)\n self.assertEqual(record.type, RecordType.A)\n self.assertEqual(record.data, '127.0.0.1')\n", "method_code": " def create_record(self, name, zone, type, data, extra=None):\n self._validate_record(None, name, type, data, extra)\n zid = int(zone.id)\n create = {'name': name, 'type': self.RECORD_TYPE_MAP[type], 'value': data}\n if 'ttl' in extra:\n create['ttl'] = extra['ttl']\n with NewZoneVersion(self, zone) as vid:\n con = self.connection\n con.set_context({'zone_id': zone.id})\n rec = con.request('domain.zone.record.add', zid, vid, create).object\n return self._to_record(rec, zone)\n ", "context": "class GandiDNSDriver(BaseGandiDriverDNSDriver):\n def create_record(self, name, zone, type, data, extra=None): ...\n def _to_zone(self, zone): ...\n def _to_zones(self, zones): ...\n def list_zones(self): ...\n def get_zone(self, zone_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def delete_zone(self, zone): ...\n def _to_record(self, record, zone): ...\n def _to_records(self, records, zone): ...\n def list_records(self, zone): ...\n def get_record(self, zone_id, record_id): ...\n def _validate_record(self, record_id, name, record_type, data, extra): ...\n def update_record(self, record, name, type, data, extra): ...\n def delete_record(self, record): ...\n\n type = Provider.GANDI\n name = 'Gandi DNS'\n website = 'http://www.gandi.net/domain'\n connectionCls = GandiDNSConnection\n RECORD_TYPE_MAP = {RecordType.NS: 'NS', RecordType.MX: 'MX', RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV', RecordType.SPF: 'SPF', RecordType.WKS: 'WKS', RecordType.LOC: 'LOC'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_record", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000804.py"} {"focal_file": "libcloud/dns/drivers/gandi.py", "focal_class": null, "focal_method": "update_record", "tests": "import unittest\n\nclass Test_update_record(unittest.TestCase):\n def test_update_record(self):\n zone = self.driver.list_zones()[0]\n record = self.driver.list_records(zone=zone)[1]\n params = {'record': record, 'name': 'www', 'type': RecordType.A, 'data': '127.0.0.1', 'extra': {'ttl': 30}}\n updated_record = self.driver.update_record(**params)\n self.assertEqual(record.data, '208.111.35.173')\n self.assertEqual(updated_record.id, 'A:www')\n self.assertEqual(updated_record.name, 'www')\n self.assertEqual(updated_record.zone, record.zone)\n self.assertEqual(updated_record.type, RecordType.A)\n self.assertEqual(updated_record.data, '127.0.0.1')\n", "method_code": " def update_record(self, record, name, type, data, extra):\n self._validate_record(record.id, name, type, data, extra)\n filter_opts = {'name': record.name, 'type': self.RECORD_TYPE_MAP[record.type]}\n update = {'name': name, 'type': self.RECORD_TYPE_MAP[type], 'value': data}\n if 'ttl' in extra:\n update['ttl'] = extra['ttl']\n zid = int(record.zone.id)\n with NewZoneVersion(self, record.zone) as vid:\n con = self.connection\n con.set_context({'zone_id': record.zone.id})\n con.request('domain.zone.record.delete', zid, vid, filter_opts)\n res = con.request('domain.zone.record.add', zid, vid, update).object\n return self._to_record(res, record.zone)\n ", "context": "class GandiDNSDriver(BaseGandiDriverDNSDriver):\n def update_record(self, record, name, type, data, extra): ...\n def _to_zone(self, zone): ...\n def _to_zones(self, zones): ...\n def list_zones(self): ...\n def get_zone(self, zone_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def delete_zone(self, zone): ...\n def _to_record(self, record, zone): ...\n def _to_records(self, records, zone): ...\n def list_records(self, zone): ...\n def get_record(self, zone_id, record_id): ...\n def _validate_record(self, record_id, name, record_type, data, extra): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def delete_record(self, record): ...\n\n type = Provider.GANDI\n name = 'Gandi DNS'\n website = 'http://www.gandi.net/domain'\n connectionCls = GandiDNSConnection\n RECORD_TYPE_MAP = {RecordType.NS: 'NS', RecordType.MX: 'MX', RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV', RecordType.SPF: 'SPF', RecordType.WKS: 'WKS', RecordType.LOC: 'LOC'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_update_record", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000805.py"} {"focal_file": "libcloud/dns/drivers/gandi.py", "focal_class": null, "focal_method": "delete_zone", "tests": "import unittest\n\nclass Test_delete_zone(unittest.TestCase):\n def test_delete_zone(self):\n zone = self.driver.list_zones()[0]\n status = self.driver.delete_zone(zone=zone)\n self.assertTrue(status)\n", "method_code": " def delete_zone(self, zone):\n zid = int(zone.id)\n self.connection.set_context({'zone_id': zone.id})\n res = self.connection.request('domain.zone.delete', zid)\n return res.object\n ", "context": "class GandiDNSDriver(BaseGandiDriverDNSDriver):\n def delete_zone(self, zone): ...\n def _to_zone(self, zone): ...\n def _to_zones(self, zones): ...\n def list_zones(self): ...\n def get_zone(self, zone_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def _to_record(self, record, zone): ...\n def _to_records(self, records, zone): ...\n def list_records(self, zone): ...\n def get_record(self, zone_id, record_id): ...\n def _validate_record(self, record_id, name, record_type, data, extra): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name, type, data, extra): ...\n def delete_record(self, record): ...\n\n type = Provider.GANDI\n name = 'Gandi DNS'\n website = 'http://www.gandi.net/domain'\n connectionCls = GandiDNSConnection\n RECORD_TYPE_MAP = {RecordType.NS: 'NS', RecordType.MX: 'MX', RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV', RecordType.SPF: 'SPF', RecordType.WKS: 'WKS', RecordType.LOC: 'LOC'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_delete_zone", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/dns/drivers/gandi.py", "focal_class": null, "focal_method": "delete_record", "tests": "import unittest\n\nclass Test_delete_record(unittest.TestCase):\n def test_delete_record(self):\n zone = self.driver.list_zones()[0]\n record = self.driver.list_records(zone=zone)[0]\n status = self.driver.delete_record(record=record)\n self.assertTrue(status)\n", "method_code": " def delete_record(self, record):\n zid = int(record.zone.id)\n filter_opts = {'name': record.name, 'type': self.RECORD_TYPE_MAP[record.type]}\n with NewZoneVersion(self, record.zone) as vid:\n con = self.connection\n con.set_context({'zone_id': record.zone.id})\n count = con.request('domain.zone.record.delete', zid, vid, filter_opts).object\n if count == 1:\n return True\n raise RecordDoesNotExistError(value='No such record', driver=self, record_id=record.id)\n ", "context": "class GandiDNSDriver(BaseGandiDriverDNSDriver):\n def delete_record(self, record): ...\n def _to_zone(self, zone): ...\n def _to_zones(self, zones): ...\n def list_zones(self): ...\n def get_zone(self, zone_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def delete_zone(self, zone): ...\n def _to_record(self, record, zone): ...\n def _to_records(self, records, zone): ...\n def list_records(self, zone): ...\n def get_record(self, zone_id, record_id): ...\n def _validate_record(self, record_id, name, record_type, data, extra): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name, type, data, extra): ...\n\n type = Provider.GANDI\n name = 'Gandi DNS'\n website = 'http://www.gandi.net/domain'\n connectionCls = GandiDNSConnection\n RECORD_TYPE_MAP = {RecordType.NS: 'NS', RecordType.MX: 'MX', RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV', RecordType.SPF: 'SPF', RecordType.WKS: 'WKS', RecordType.LOC: 'LOC'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_delete_record", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/dns/drivers/hostvirtual.py", "focal_class": null, "focal_method": "list_zones", "tests": "import unittest\n\nclass Test_list_zones(unittest.TestCase):\n def test_list_zones(self):\n zones = self.driver.list_zones()\n self.assertEqual(len(zones), 5)\n zone = zones[0]\n self.assertEqual(zone.id, '47234')\n self.assertEqual(zone.type, 'master')\n self.assertEqual(zone.domain, 't.com')\n self.assertEqual(zone.ttl, '3600')\n", "method_code": " def list_zones(self):\n result = self.connection.request(API_ROOT + '/dns/zones/').object\n zones = self._to_zones(result)\n return zones\n ", "context": "class HostVirtualDNSDriver(DNSDriver):\n def list_zones(self): ...\n def _to_zones(self, items): ...\n def _to_zone(self, item): ...\n def _to_records(self, items, zone=None): ...\n def _to_record(self, item, zone=None): ...\n def list_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def delete_zone(self, zone): ...\n def delete_record(self, record): ...\n def create_zone(self, domain, type='NATIVE', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n\n type = Provider.HOSTVIRTUAL\n name = 'Host Virtual DNS'\n website = 'http://www.vr.org/'\n connectionCls = HostVirtualDNSConnection\n RECORD_TYPE_MAP = {RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.MX: 'MX', RecordType.TXT: 'TXT', RecordType.NS: 'SPF', RecordType.SRV: 'SRV'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_zones", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000808.py"} {"focal_file": "libcloud/dns/drivers/hostvirtual.py", "focal_class": null, "focal_method": "list_records", "tests": "import unittest\n\nclass Test_list_records(unittest.TestCase):\n def test_list_records(self):\n zone = self.driver.list_zones()[0]\n records = self.driver.list_records(zone=zone)\n self.assertEqual(len(records), 3)\n record = records[1]\n self.assertEqual(record.name, 'www.t.com')\n self.assertEqual(record.id, '300719')\n self.assertEqual(record.type, RecordType.A)\n self.assertEqual(record.data, '208.111.35.173')\n", "method_code": " def list_records(self, zone):\n params = {'zone_id': zone.id}\n self.connection.set_context({'resource': 'zone', 'id': zone.id})\n result = self.connection.request(API_ROOT + '/dns/records/', data=json.dumps(params)).object\n records = self._to_records(items=result, zone=zone)\n return records\n ", "context": "class HostVirtualDNSDriver(DNSDriver):\n def list_records(self, zone): ...\n def _to_zones(self, items): ...\n def _to_zone(self, item): ...\n def _to_records(self, items, zone=None): ...\n def _to_record(self, item, zone=None): ...\n def list_zones(self): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def delete_zone(self, zone): ...\n def delete_record(self, record): ...\n def create_zone(self, domain, type='NATIVE', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n\n type = Provider.HOSTVIRTUAL\n name = 'Host Virtual DNS'\n website = 'http://www.vr.org/'\n connectionCls = HostVirtualDNSConnection\n RECORD_TYPE_MAP = {RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.MX: 'MX', RecordType.TXT: 'TXT', RecordType.NS: 'SPF', RecordType.SRV: 'SRV'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_records", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000809.py"} {"focal_file": "libcloud/dns/drivers/hostvirtual.py", "focal_class": null, "focal_method": "get_zone", "tests": "import unittest\n\nclass Test_get_zone(unittest.TestCase):\n def test_get_zone(self):\n zone = self.driver.get_zone(zone_id='47234')\n self.assertEqual(zone.id, '47234')\n self.assertEqual(zone.type, 'master')\n self.assertEqual(zone.domain, 't.com')\n self.assertEqual(zone.ttl, '3600')\n", "method_code": " def get_zone(self, zone_id):\n params = {'id': zone_id}\n self.connection.set_context({'resource': 'zone', 'id': zone_id})\n result = self.connection.request(API_ROOT + '/dns/zone/', params=params).object\n if 'id' not in result:\n raise ZoneDoesNotExistError(value='', driver=self, zone_id=zone_id)\n zone = self._to_zone(result)\n return zone\n ", "context": "class HostVirtualDNSDriver(DNSDriver):\n def get_zone(self, zone_id): ...\n def _to_zones(self, items): ...\n def _to_zone(self, item): ...\n def _to_records(self, items, zone=None): ...\n def _to_record(self, item, zone=None): ...\n def list_zones(self): ...\n def list_records(self, zone): ...\n def get_record(self, zone_id, record_id): ...\n def delete_zone(self, zone): ...\n def delete_record(self, record): ...\n def create_zone(self, domain, type='NATIVE', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n\n type = Provider.HOSTVIRTUAL\n name = 'Host Virtual DNS'\n website = 'http://www.vr.org/'\n connectionCls = HostVirtualDNSConnection\n RECORD_TYPE_MAP = {RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.MX: 'MX', RecordType.TXT: 'TXT', RecordType.NS: 'SPF', RecordType.SRV: 'SRV'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_get_zone", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000810.py"} {"focal_file": "libcloud/dns/drivers/hostvirtual.py", "focal_class": null, "focal_method": "get_record", "tests": "import unittest\n\nclass Test_get_record(unittest.TestCase):\n def test_get_record(self):\n record = self.driver.get_record(zone_id='47234', record_id='300377')\n self.assertEqual(record.id, '300377')\n self.assertEqual(record.name, '*.t.com')\n self.assertEqual(record.type, RecordType.CNAME)\n self.assertEqual(record.data, 't.com')\n", "method_code": " def get_record(self, zone_id, record_id):\n zone = self.get_zone(zone_id=zone_id)\n params = {'id': record_id}\n self.connection.set_context({'resource': 'record', 'id': record_id})\n result = self.connection.request(API_ROOT + '/dns/record/', params=params).object\n if 'id' not in result:\n raise RecordDoesNotExistError(value='', driver=self, record_id=record_id)\n record = self._to_record(item=result, zone=zone)\n return record\n ", "context": "class HostVirtualDNSDriver(DNSDriver):\n def get_record(self, zone_id, record_id): ...\n def _to_zones(self, items): ...\n def _to_zone(self, item): ...\n def _to_records(self, items, zone=None): ...\n def _to_record(self, item, zone=None): ...\n def list_zones(self): ...\n def list_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def delete_zone(self, zone): ...\n def delete_record(self, record): ...\n def create_zone(self, domain, type='NATIVE', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n\n type = Provider.HOSTVIRTUAL\n name = 'Host Virtual DNS'\n website = 'http://www.vr.org/'\n connectionCls = HostVirtualDNSConnection\n RECORD_TYPE_MAP = {RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.MX: 'MX', RecordType.TXT: 'TXT', RecordType.NS: 'SPF', RecordType.SRV: 'SRV'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_get_record", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000811.py"} {"focal_file": "libcloud/dns/drivers/hostvirtual.py", "focal_class": null, "focal_method": "create_zone", "tests": "import unittest\n\nclass Test_create_zone(unittest.TestCase):\n def test_create_zone(self):\n zone = self.driver.create_zone(domain='t.com', type='master', ttl=None, extra=None)\n self.assertEqual(zone.id, '47234')\n self.assertEqual(zone.domain, 't.com')\n", "method_code": " def create_zone(self, domain, type='NATIVE', ttl=None, extra=None):\n if type == 'master':\n type = 'NATIVE'\n elif type == 'slave':\n type = 'SLAVE'\n params = {'name': domain, 'type': type, 'ttl': ttl}\n result = self.connection.request(API_ROOT + '/dns/zone/', data=json.dumps(params), method='POST').object\n extra = {'soa': result['soa'], 'ns': result['ns']}\n zone = Zone(id=result['id'], domain=domain, type=type, ttl=ttl, extra=extra, driver=self)\n return zone\n ", "context": "class HostVirtualDNSDriver(DNSDriver):\n def create_zone(self, domain, type='NATIVE', ttl=None, extra=None): ...\n def _to_zones(self, items): ...\n def _to_zone(self, item): ...\n def _to_records(self, items, zone=None): ...\n def _to_record(self, item, zone=None): ...\n def list_zones(self): ...\n def list_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def delete_zone(self, zone): ...\n def delete_record(self, record): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n\n type = Provider.HOSTVIRTUAL\n name = 'Host Virtual DNS'\n website = 'http://www.vr.org/'\n connectionCls = HostVirtualDNSConnection\n RECORD_TYPE_MAP = {RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.MX: 'MX', RecordType.TXT: 'TXT', RecordType.NS: 'SPF', RecordType.SRV: 'SRV'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_zone", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000812.py"} {"focal_file": "libcloud/dns/drivers/hostvirtual.py", "focal_class": null, "focal_method": "update_zone", "tests": "import unittest\n\nclass Test_update_zone(unittest.TestCase):\n def test_update_zone(self):\n zone = self.driver.list_zones()[0]\n updated_zone = self.driver.update_zone(zone=zone, domain='tt.com')\n self.assertEqual(updated_zone.id, zone.id)\n self.assertEqual(updated_zone.domain, 'tt.com')\n self.assertEqual(updated_zone.type, zone.type)\n self.assertEqual(updated_zone.ttl, '3600')\n", "method_code": " def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None):\n params = {'id': zone.id}\n if domain:\n params['name'] = domain\n if type:\n params['type'] = type\n self.connection.set_context({'resource': 'zone', 'id': zone.id})\n self.connection.request(API_ROOT + '/dns/zone/', data=json.dumps(params), method='PUT').object\n updated_zone = get_new_obj(obj=zone, klass=Zone, attributes={'domain': domain, 'type': type, 'ttl': ttl, 'extra': extra})\n return updated_zone\n ", "context": "class HostVirtualDNSDriver(DNSDriver):\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def _to_zones(self, items): ...\n def _to_zone(self, item): ...\n def _to_records(self, items, zone=None): ...\n def _to_record(self, item, zone=None): ...\n def list_zones(self): ...\n def list_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def delete_zone(self, zone): ...\n def delete_record(self, record): ...\n def create_zone(self, domain, type='NATIVE', ttl=None, extra=None): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n\n type = Provider.HOSTVIRTUAL\n name = 'Host Virtual DNS'\n website = 'http://www.vr.org/'\n connectionCls = HostVirtualDNSConnection\n RECORD_TYPE_MAP = {RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.MX: 'MX', RecordType.TXT: 'TXT', RecordType.NS: 'SPF', RecordType.SRV: 'SRV'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_update_zone", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000813.py"} {"focal_file": "libcloud/dns/drivers/hostvirtual.py", "focal_class": null, "focal_method": "create_record", "tests": "import unittest\n\nclass Test_create_record(unittest.TestCase):\n def test_create_record(self):\n zone = self.driver.list_zones()[0]\n record = self.driver.create_record(name='www', zone=zone, type=RecordType.A, data='127.0.0.1')\n self.assertEqual(record.id, '300377')\n self.assertEqual(record.name, 'www')\n self.assertEqual(record.zone, zone)\n self.assertEqual(record.type, RecordType.A)\n self.assertEqual(record.data, '127.0.0.1')\n", "method_code": " def create_record(self, name, zone, type, data, extra=None):\n params = {'name': name, 'type': self.RECORD_TYPE_MAP[type], 'domain_id': zone.id, 'content': data}\n merged = merge_valid_keys(params=params, valid_keys=VALID_RECORD_EXTRA_PARAMS, extra=extra)\n self.connection.set_context({'resource': 'zone', 'id': zone.id})\n result = self.connection.request(API_ROOT + '/dns/record/', data=json.dumps(params), method='POST').object\n record = Record(id=result['id'], name=name, type=type, data=data, extra=merged, zone=zone, driver=self)\n return record\n ", "context": "class HostVirtualDNSDriver(DNSDriver):\n def create_record(self, name, zone, type, data, extra=None): ...\n def _to_zones(self, items): ...\n def _to_zone(self, item): ...\n def _to_records(self, items, zone=None): ...\n def _to_record(self, item, zone=None): ...\n def list_zones(self): ...\n def list_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def delete_zone(self, zone): ...\n def delete_record(self, record): ...\n def create_zone(self, domain, type='NATIVE', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n\n type = Provider.HOSTVIRTUAL\n name = 'Host Virtual DNS'\n website = 'http://www.vr.org/'\n connectionCls = HostVirtualDNSConnection\n RECORD_TYPE_MAP = {RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.MX: 'MX', RecordType.TXT: 'TXT', RecordType.NS: 'SPF', RecordType.SRV: 'SRV'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_record", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000814.py"} {"focal_file": "libcloud/dns/drivers/hostvirtual.py", "focal_class": null, "focal_method": "update_record", "tests": "import unittest\n\nclass Test_update_record(unittest.TestCase):\n def test_update_record(self):\n zone = self.driver.list_zones()[0]\n record = self.driver.list_records(zone=zone)[1]\n updated_record = self.driver.update_record(record=record, name='www', type=RecordType.AAAA, data='::1')\n self.assertEqual(record.data, '208.111.35.173')\n self.assertEqual(updated_record.id, record.id)\n self.assertEqual(updated_record.name, 'www')\n self.assertEqual(updated_record.zone, record.zone)\n self.assertEqual(updated_record.type, RecordType.AAAA)\n self.assertEqual(updated_record.data, '::1')\n", "method_code": " def update_record(self, record, name=None, type=None, data=None, extra=None):\n params = {'domain_id': record.zone.id, 'record_id': record.id}\n if name:\n params['name'] = name\n if data:\n params['content'] = data\n if type is not None:\n params['type'] = self.RECORD_TYPE_MAP[type]\n merged = merge_valid_keys(params=params, valid_keys=VALID_RECORD_EXTRA_PARAMS, extra=extra)\n self.connection.set_context({'resource': 'record', 'id': record.id})\n self.connection.request(API_ROOT + '/dns/record/', data=json.dumps(params), method='PUT').object\n updated_record = get_new_obj(obj=record, klass=Record, attributes={'name': name, 'data': data, 'type': type, 'extra': merged})\n return updated_record\n ", "context": "class HostVirtualDNSDriver(DNSDriver):\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n def _to_zones(self, items): ...\n def _to_zone(self, item): ...\n def _to_records(self, items, zone=None): ...\n def _to_record(self, item, zone=None): ...\n def list_zones(self): ...\n def list_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def delete_zone(self, zone): ...\n def delete_record(self, record): ...\n def create_zone(self, domain, type='NATIVE', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n\n type = Provider.HOSTVIRTUAL\n name = 'Host Virtual DNS'\n website = 'http://www.vr.org/'\n connectionCls = HostVirtualDNSConnection\n RECORD_TYPE_MAP = {RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.MX: 'MX', RecordType.TXT: 'TXT', RecordType.NS: 'SPF', RecordType.SRV: 'SRV'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_update_record", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000815.py"} {"focal_file": "libcloud/dns/drivers/hostvirtual.py", "focal_class": null, "focal_method": "delete_zone", "tests": "import unittest\n\nclass Test_delete_zone(unittest.TestCase):\n def test_delete_zone(self):\n zone = self.driver.list_zones()[0]\n status = self.driver.delete_zone(zone=zone)\n self.assertTrue(status)\n", "method_code": " def delete_zone(self, zone):\n params = {'zone_id': zone.id}\n self.connection.set_context({'resource': 'zone', 'id': zone.id})\n result = self.connection.request(API_ROOT + '/dns/zone/', params=params, method='DELETE').object\n return bool(result)\n ", "context": "class HostVirtualDNSDriver(DNSDriver):\n def delete_zone(self, zone): ...\n def _to_zones(self, items): ...\n def _to_zone(self, item): ...\n def _to_records(self, items, zone=None): ...\n def _to_record(self, item, zone=None): ...\n def list_zones(self): ...\n def list_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def delete_record(self, record): ...\n def create_zone(self, domain, type='NATIVE', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n\n type = Provider.HOSTVIRTUAL\n name = 'Host Virtual DNS'\n website = 'http://www.vr.org/'\n connectionCls = HostVirtualDNSConnection\n RECORD_TYPE_MAP = {RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.MX: 'MX', RecordType.TXT: 'TXT', RecordType.NS: 'SPF', RecordType.SRV: 'SRV'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_delete_zone", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000816.py"} {"focal_file": "libcloud/dns/drivers/hostvirtual.py", "focal_class": null, "focal_method": "delete_record", "tests": "import unittest\n\nclass Test_delete_record(unittest.TestCase):\n def test_delete_record(self):\n zone = self.driver.list_zones()[0]\n record = self.driver.list_records(zone=zone)[0]\n status = self.driver.delete_record(record=record)\n self.assertTrue(status)\n", "method_code": " def delete_record(self, record):\n params = {'id': record.id}\n self.connection.set_context({'resource': 'record', 'id': record.id})\n result = self.connection.request(API_ROOT + '/dns/record/', params=params, method='DELETE').object\n return bool(result)\n ", "context": "class HostVirtualDNSDriver(DNSDriver):\n def delete_record(self, record): ...\n def _to_zones(self, items): ...\n def _to_zone(self, item): ...\n def _to_records(self, items, zone=None): ...\n def _to_record(self, item, zone=None): ...\n def list_zones(self): ...\n def list_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def delete_zone(self, zone): ...\n def create_zone(self, domain, type='NATIVE', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n\n type = Provider.HOSTVIRTUAL\n name = 'Host Virtual DNS'\n website = 'http://www.vr.org/'\n connectionCls = HostVirtualDNSConnection\n RECORD_TYPE_MAP = {RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.MX: 'MX', RecordType.TXT: 'TXT', RecordType.NS: 'SPF', RecordType.SRV: 'SRV'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_delete_record", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000817.py"} {"focal_file": "libcloud/dns/drivers/linode.py", "focal_class": null, "focal_method": "list_records", "tests": "import unittest\n\nclass Test_list_records(unittest.TestCase):\n def test_list_records_success(self):\n zone = self.driver.list_zones()[0]\n records = self.driver.list_records(zone=zone)\n self.assertEqual(len(records), 2)\n record = records[0]\n self.assertEqual(record.id, '28536')\n self.assertEqual(record.name, 'www')\n self.assertEqual(record.type, RecordType.A)\n self.assertEqual(record.data, '75.127.96.245')\n self.assertHasKeys(record.extra, ['protocol', 'ttl_sec', 'port', 'weight'])\n", "method_code": " def list_records(self, zone):\n params = {'api_action': 'domain.resource.list', 'DOMAINID': zone.id}\n self.connection.set_context(context={'resource': 'zone', 'id': zone.id})\n data = self.connection.request(API_ROOT, params=params).objects[0]\n records = self._to_records(items=data, zone=zone)\n return records\n ", "context": "class LinodeDNSDriver(DNSDriver):\n def list_records(self, zone): ...\n def list_zones(self): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n def delete_zone(self, zone): ...\n def delete_record(self, record): ...\n def _to_zones(self, items): ...\n def _to_zone(self, item): ...\n def _to_records(self, items, zone=None): ...\n def _to_record(self, item, zone=None): ...\n\n type = Provider.LINODE\n name = 'Linode DNS'\n website = 'http://www.linode.com/'\n connectionCls = LinodeDNSConnection\n RECORD_TYPE_MAP = {RecordType.NS: 'NS', RecordType.MX: 'MX', RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_records_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000818.py"} {"focal_file": "libcloud/dns/drivers/linode.py", "focal_class": null, "focal_method": "create_zone", "tests": "import unittest\n\nclass Test_create_zone(unittest.TestCase):\n def test_create_zone_success(self):\n zone = self.driver.create_zone(domain='foo.bar.com', type='master', ttl=None, extra=None)\n self.assertEqual(zone.id, '5123')\n self.assertEqual(zone.domain, 'foo.bar.com')\n", "method_code": " def create_zone(self, domain, type='master', ttl=None, extra=None):\n \"\"\"\n Create a new zone.\n \n API docs: http://www.linode.com/api/dns/domain.create\n \n @inherits: C{DNSDriver.create_zone}\n \"\"\"\n params = {'api_action': 'domain.create', 'Type': type, 'Domain': domain}\n if ttl:\n params['TTL_sec'] = ttl\n merged = merge_valid_keys(params=params, valid_keys=VALID_ZONE_EXTRA_PARAMS, extra=extra)\n data = self.connection.request(API_ROOT, params=params).objects[0]\n zone = Zone(id=data['DomainID'], domain=domain, type=type, ttl=ttl, extra=merged, driver=self)\n return zone\n ", "context": "class LinodeDNSDriver(DNSDriver):\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def list_zones(self): ...\n def list_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n def delete_zone(self, zone): ...\n def delete_record(self, record): ...\n def _to_zones(self, items): ...\n def _to_zone(self, item): ...\n def _to_records(self, items, zone=None): ...\n def _to_record(self, item, zone=None): ...\n\n type = Provider.LINODE\n name = 'Linode DNS'\n website = 'http://www.linode.com/'\n connectionCls = LinodeDNSConnection\n RECORD_TYPE_MAP = {RecordType.NS: 'NS', RecordType.MX: 'MX', RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_zone_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000819.py"} {"focal_file": "libcloud/dns/drivers/linode.py", "focal_class": null, "focal_method": "update_zone", "tests": "import unittest\n\nclass Test_update_zone(unittest.TestCase):\n def test_update_zone_success(self):\n zone = self.driver.list_zones()[0]\n updated_zone = self.driver.update_zone(zone=zone, domain='libcloud.org', ttl=10, extra={'SOA_Email': 'bar@libcloud.org'})\n self.assertEqual(zone.extra['SOA_Email'], 'dns@example.com')\n self.assertEqual(updated_zone.id, zone.id)\n self.assertEqual(updated_zone.domain, 'libcloud.org')\n self.assertEqual(updated_zone.type, zone.type)\n self.assertEqual(updated_zone.ttl, 10)\n self.assertEqual(updated_zone.extra['SOA_Email'], 'bar@libcloud.org')\n self.assertEqual(updated_zone.extra['status'], zone.extra['status'])\n self.assertEqual(updated_zone.extra['description'], zone.extra['description'])\n", "method_code": " def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None):\n \"\"\"\n Update an existing zone.\n \n API docs: http://www.linode.com/api/dns/domain.update\n \n @inherits: C{DNSDriver.update_zone}\n \"\"\"\n params = {'api_action': 'domain.update', 'DomainID': zone.id}\n if type:\n params['Type'] = type\n if domain:\n params['Domain'] = domain\n if ttl:\n params['TTL_sec'] = ttl\n merged = merge_valid_keys(params=params, valid_keys=VALID_ZONE_EXTRA_PARAMS, extra=extra)\n self.connection.request(API_ROOT, params=params).objects[0]\n updated_zone = get_new_obj(obj=zone, klass=Zone, attributes={'domain': domain, 'type': type, 'ttl': ttl, 'extra': merged})\n return updated_zone\n ", "context": "class LinodeDNSDriver(DNSDriver):\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def list_zones(self): ...\n def list_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n def delete_zone(self, zone): ...\n def delete_record(self, record): ...\n def _to_zones(self, items): ...\n def _to_zone(self, item): ...\n def _to_records(self, items, zone=None): ...\n def _to_record(self, item, zone=None): ...\n\n type = Provider.LINODE\n name = 'Linode DNS'\n website = 'http://www.linode.com/'\n connectionCls = LinodeDNSConnection\n RECORD_TYPE_MAP = {RecordType.NS: 'NS', RecordType.MX: 'MX', RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_update_zone_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000820.py"} {"focal_file": "libcloud/dns/drivers/linode.py", "focal_class": null, "focal_method": "create_record", "tests": "import unittest\n\nclass Test_create_record(unittest.TestCase):\n def test_create_record_success(self):\n zone = self.driver.list_zones()[0]\n record = self.driver.create_record(name='www', zone=zone, type=RecordType.A, data='127.0.0.1')\n self.assertEqual(record.id, '28537')\n self.assertEqual(record.name, 'www')\n self.assertEqual(record.zone, zone)\n self.assertEqual(record.type, RecordType.A)\n self.assertEqual(record.data, '127.0.0.1')\n", "method_code": " def create_record(self, name, zone, type, data, extra=None):\n \"\"\"\n Create a new record.\n \n API docs: http://www.linode.com/api/dns/domain.resource.create\n \n @inherits: C{DNSDriver.create_record}\n \"\"\"\n params = {'api_action': 'domain.resource.create', 'DomainID': zone.id, 'Name': name, 'Target': data, 'Type': self.RECORD_TYPE_MAP[type]}\n merged = merge_valid_keys(params=params, valid_keys=VALID_RECORD_EXTRA_PARAMS, extra=extra)\n result = self.connection.request(API_ROOT, params=params).objects[0]\n record = Record(id=result['ResourceID'], name=name, type=type, data=data, extra=merged, zone=zone, driver=self)\n return record\n ", "context": "class LinodeDNSDriver(DNSDriver):\n def create_record(self, name, zone, type, data, extra=None): ...\n def list_zones(self): ...\n def list_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n def delete_zone(self, zone): ...\n def delete_record(self, record): ...\n def _to_zones(self, items): ...\n def _to_zone(self, item): ...\n def _to_records(self, items, zone=None): ...\n def _to_record(self, item, zone=None): ...\n\n type = Provider.LINODE\n name = 'Linode DNS'\n website = 'http://www.linode.com/'\n connectionCls = LinodeDNSConnection\n RECORD_TYPE_MAP = {RecordType.NS: 'NS', RecordType.MX: 'MX', RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_record_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000821.py"} {"focal_file": "libcloud/dns/drivers/linode.py", "focal_class": null, "focal_method": "update_record", "tests": "import unittest\n\nclass Test_update_record(unittest.TestCase):\n def test_update_record_success(self):\n zone = self.driver.list_zones()[0]\n record = self.driver.list_records(zone=zone)[0]\n updated_record = self.driver.update_record(record=record, name='www', type=RecordType.AAAA, data='::1')\n self.assertEqual(record.data, '75.127.96.245')\n self.assertEqual(updated_record.id, record.id)\n self.assertEqual(updated_record.name, 'www')\n self.assertEqual(updated_record.zone, record.zone)\n self.assertEqual(updated_record.type, RecordType.AAAA)\n self.assertEqual(updated_record.data, '::1')\n", "method_code": " def update_record(self, record, name=None, type=None, data=None, extra=None):\n \"\"\"\n Update an existing record.\n \n API docs: http://www.linode.com/api/dns/domain.resource.update\n \n @inherits: C{DNSDriver.update_record}\n \"\"\"\n params = {'api_action': 'domain.resource.update', 'ResourceID': record.id, 'DomainID': record.zone.id}\n if name:\n params['Name'] = name\n if data:\n params['Target'] = data\n if type is not None:\n params['Type'] = self.RECORD_TYPE_MAP[type]\n merged = merge_valid_keys(params=params, valid_keys=VALID_RECORD_EXTRA_PARAMS, extra=extra)\n self.connection.request(API_ROOT, params=params).objects[0]\n updated_record = get_new_obj(obj=record, klass=Record, attributes={'name': name, 'data': data, 'type': type, 'extra': merged})\n return updated_record\n ", "context": "class LinodeDNSDriver(DNSDriver):\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n def list_zones(self): ...\n def list_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def delete_zone(self, zone): ...\n def delete_record(self, record): ...\n def _to_zones(self, items): ...\n def _to_zone(self, item): ...\n def _to_records(self, items, zone=None): ...\n def _to_record(self, item, zone=None): ...\n\n type = Provider.LINODE\n name = 'Linode DNS'\n website = 'http://www.linode.com/'\n connectionCls = LinodeDNSConnection\n RECORD_TYPE_MAP = {RecordType.NS: 'NS', RecordType.MX: 'MX', RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_update_record_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000822.py"} {"focal_file": "libcloud/dns/drivers/linode.py", "focal_class": null, "focal_method": "delete_zone", "tests": "import unittest\n\nclass Test_delete_zone(unittest.TestCase):\n def test_delete_zone_success(self):\n zone = self.driver.list_zones()[0]\n status = self.driver.delete_zone(zone=zone)\n self.assertTrue(status)\n", "method_code": " def delete_zone(self, zone):\n params = {'api_action': 'domain.delete', 'DomainID': zone.id}\n self.connection.set_context(context={'resource': 'zone', 'id': zone.id})\n data = self.connection.request(API_ROOT, params=params).objects[0]\n return 'DomainID' in data\n ", "context": "class LinodeDNSDriver(DNSDriver):\n def delete_zone(self, zone): ...\n def list_zones(self): ...\n def list_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n def delete_record(self, record): ...\n def _to_zones(self, items): ...\n def _to_zone(self, item): ...\n def _to_records(self, items, zone=None): ...\n def _to_record(self, item, zone=None): ...\n\n type = Provider.LINODE\n name = 'Linode DNS'\n website = 'http://www.linode.com/'\n connectionCls = LinodeDNSConnection\n RECORD_TYPE_MAP = {RecordType.NS: 'NS', RecordType.MX: 'MX', RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_delete_zone_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/dns/drivers/linode.py", "focal_class": null, "focal_method": "delete_record", "tests": "import unittest\n\nclass Test_delete_record(unittest.TestCase):\n def test_delete_record_success(self):\n zone = self.driver.list_zones()[0]\n record = self.driver.list_records(zone=zone)[0]\n status = self.driver.delete_record(record=record)\n self.assertTrue(status)\n", "method_code": " def delete_record(self, record):\n params = {'api_action': 'domain.resource.delete', 'DomainID': record.zone.id, 'ResourceID': record.id}\n self.connection.set_context(context={'resource': 'record', 'id': record.id})\n data = self.connection.request(API_ROOT, params=params).objects[0]\n return 'ResourceID' in data\n ", "context": "class LinodeDNSDriver(DNSDriver):\n def delete_record(self, record): ...\n def list_zones(self): ...\n def list_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n def delete_zone(self, zone): ...\n def _to_zones(self, items): ...\n def _to_zone(self, item): ...\n def _to_records(self, items, zone=None): ...\n def _to_record(self, item, zone=None): ...\n\n type = Provider.LINODE\n name = 'Linode DNS'\n website = 'http://www.linode.com/'\n connectionCls = LinodeDNSConnection\n RECORD_TYPE_MAP = {RecordType.NS: 'NS', RecordType.MX: 'MX', RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_delete_record_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000824.py"} {"focal_file": "libcloud/dns/drivers/rackspace.py", "focal_class": null, "focal_method": "list_records", "tests": "import unittest\n\nclass Test_list_records(unittest.TestCase):\n def test_list_records_success(self):\n zone = self.driver.list_zones()[0]\n records = self.driver.list_records(zone=zone)\n self.assertEqual(len(records), 3)\n self.assertEqual(records[0].name, 'test3')\n self.assertEqual(records[0].type, RecordType.A)\n self.assertEqual(records[0].data, '127.7.7.7')\n self.assertEqual(records[0].extra['ttl'], 777)\n self.assertEqual(records[0].extra['comment'], 'lulz')\n self.assertEqual(records[0].extra['fqdn'], 'test3.%s' % records[0].zone.domain)\n", "method_code": " def list_records(self, zone):\n self.connection.set_context({'resource': 'zone', 'id': zone.id})\n response = self.connection.request(action='/domains/%s' % zone.id, params={'showRecord': True}).object\n records = self._to_records(data=response['recordsList']['records'], zone=zone)\n return records\n ", "context": "class RackspaceDNSDriver(DNSDriverOpenStackDriverMixin):\n def list_records(self, zone): ...\n def __init__(self, *args, **kwargs): ...\n def _ex_connection_class_kwargs(self): ...\n def list_zones(self): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n def delete_zone(self, zone): ...\n def delete_record(self, record): ...\n def _to_zones(self, data): ...\n def _to_zone(self, data): ...\n def _to_records(self, data, zone): ...\n def _to_record(self, data, zone): ...\n def _to_full_record_name(self, domain, name): ...\n def _to_partial_record_name(self, domain, name): ...\n\n website = 'http://www.rackspace.com/'\n RECORD_TYPE_MAP = {RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.MX: 'MX', RecordType.NS: 'NS', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_records_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000825.py"} {"focal_file": "libcloud/dns/drivers/rackspace.py", "focal_class": null, "focal_method": "create_zone", "tests": "import unittest\n\nclass Test_create_zone(unittest.TestCase):\n def test_create_zone_success(self):\n RackspaceMockHttp.type = 'CREATE_ZONE'\n zone = self.driver.create_zone(domain='bar.foo1.com', type='master', ttl=None, extra={'email': 'test@test.com'})\n self.assertEqual(zone.id, '2946173')\n self.assertEqual(zone.domain, 'bar.foo1.com')\n self.assertEqual(zone.type, 'master')\n self.assertEqual(zone.extra['email'], 'test@test.com')\n", "method_code": " def create_zone(self, domain, type='master', ttl=None, extra=None):\n extra = extra if extra else {}\n if not 'email' in extra:\n raise ValueError('\"email\" key must be present in extra dictionary')\n payload = {'name': domain, 'emailAddress': extra['email'], 'recordsList': {'records': []}}\n if ttl:\n payload['ttl'] = ttl\n if 'comment' in extra:\n payload['comment'] = extra['comment']\n data = {'domains': [payload]}\n response = self.connection.async_request(action='/domains', method='POST', data=data)\n zone = self._to_zone(data=response.object['response']['domains'][0])\n return zone\n ", "context": "class RackspaceDNSDriver(DNSDriverOpenStackDriverMixin):\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def __init__(self, *args, **kwargs): ...\n def _ex_connection_class_kwargs(self): ...\n def list_zones(self): ...\n def list_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n def delete_zone(self, zone): ...\n def delete_record(self, record): ...\n def _to_zones(self, data): ...\n def _to_zone(self, data): ...\n def _to_records(self, data, zone): ...\n def _to_record(self, data, zone): ...\n def _to_full_record_name(self, domain, name): ...\n def _to_partial_record_name(self, domain, name): ...\n\n website = 'http://www.rackspace.com/'\n RECORD_TYPE_MAP = {RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.MX: 'MX', RecordType.NS: 'NS', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_zone_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000826.py"} {"focal_file": "libcloud/dns/drivers/rackspace.py", "focal_class": null, "focal_method": "update_zone", "tests": "import unittest\n\nclass Test_update_zone(unittest.TestCase):\n def test_update_zone_success(self):\n zone = self.driver.list_zones()[0]\n updated_zone = self.driver.update_zone(zone=zone, extra={'comment': 'bar foo'})\n self.assertEqual(zone.extra['comment'], 'wazaaa')\n self.assertEqual(updated_zone.id, zone.id)\n self.assertEqual(updated_zone.domain, 'foo4.bar.com')\n self.assertEqual(updated_zone.type, zone.type)\n self.assertEqual(updated_zone.ttl, zone.ttl)\n self.assertEqual(updated_zone.extra['comment'], 'bar foo')\n", "method_code": " def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None):\n extra = extra if extra else {}\n if domain:\n raise LibcloudError('Domain cannot be changed', driver=self)\n data = {}\n if ttl:\n data['ttl'] = int(ttl)\n if 'email' in extra:\n data['emailAddress'] = extra['email']\n if 'comment' in extra:\n data['comment'] = extra['comment']\n type = type if type else zone.type\n ttl = ttl if ttl else zone.ttl\n self.connection.set_context({'resource': 'zone', 'id': zone.id})\n self.connection.async_request(action='/domains/%s' % zone.id, method='PUT', data=data)\n merged = merge_valid_keys(params=copy.deepcopy(zone.extra), valid_keys=VALID_ZONE_EXTRA_PARAMS, extra=extra)\n updated_zone = get_new_obj(obj=zone, klass=Zone, attributes={'type': type, 'ttl': ttl, 'extra': merged})\n return updated_zone\n ", "context": "class RackspaceDNSDriver(DNSDriverOpenStackDriverMixin):\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def __init__(self, *args, **kwargs): ...\n def _ex_connection_class_kwargs(self): ...\n def list_zones(self): ...\n def list_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n def delete_zone(self, zone): ...\n def delete_record(self, record): ...\n def _to_zones(self, data): ...\n def _to_zone(self, data): ...\n def _to_records(self, data, zone): ...\n def _to_record(self, data, zone): ...\n def _to_full_record_name(self, domain, name): ...\n def _to_partial_record_name(self, domain, name): ...\n\n website = 'http://www.rackspace.com/'\n RECORD_TYPE_MAP = {RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.MX: 'MX', RecordType.NS: 'NS', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_update_zone_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000827.py"} {"focal_file": "libcloud/dns/drivers/rackspace.py", "focal_class": null, "focal_method": "create_record", "tests": "import unittest\n\nclass Test_create_record(unittest.TestCase):\n def test_create_record_success(self):\n zone = self.driver.list_zones()[0]\n RackspaceMockHttp.type = 'CREATE_RECORD'\n record = self.driver.create_record(name='www', zone=zone, type=RecordType.A, data='127.1.1.1')\n self.assertEqual(record.id, 'A-7423317')\n self.assertEqual(record.name, 'www')\n self.assertEqual(record.zone, zone)\n self.assertEqual(record.type, RecordType.A)\n self.assertEqual(record.data, '127.1.1.1')\n self.assertEqual(record.extra['fqdn'], 'www.%s' % zone.domain)\n", "method_code": " def create_record(self, name, zone, type, data, extra=None):\n extra = extra if extra else {}\n name = self._to_full_record_name(domain=zone.domain, name=name)\n data = {'name': name, 'type': self.RECORD_TYPE_MAP[type], 'data': data}\n if 'ttl' in extra:\n data['ttl'] = int(extra['ttl'])\n if 'priority' in extra:\n data['priority'] = int(extra['priority'])\n payload = {'records': [data]}\n self.connection.set_context({'resource': 'zone', 'id': zone.id})\n response = self.connection.async_request(action='/domains/%s/records' % zone.id, data=payload, method='POST').object\n record = self._to_record(data=response['response']['records'][0], zone=zone)\n return record\n ", "context": "class RackspaceDNSDriver(DNSDriverOpenStackDriverMixin):\n def create_record(self, name, zone, type, data, extra=None): ...\n def __init__(self, *args, **kwargs): ...\n def _ex_connection_class_kwargs(self): ...\n def list_zones(self): ...\n def list_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n def delete_zone(self, zone): ...\n def delete_record(self, record): ...\n def _to_zones(self, data): ...\n def _to_zone(self, data): ...\n def _to_records(self, data, zone): ...\n def _to_record(self, data, zone): ...\n def _to_full_record_name(self, domain, name): ...\n def _to_partial_record_name(self, domain, name): ...\n\n website = 'http://www.rackspace.com/'\n RECORD_TYPE_MAP = {RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.MX: 'MX', RecordType.NS: 'NS', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_record_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000828.py"} {"focal_file": "libcloud/dns/drivers/rackspace.py", "focal_class": null, "focal_method": "update_record", "tests": "import unittest\n\nclass Test_update_record(unittest.TestCase):\n def test_update_record_success(self):\n zone = self.driver.list_zones()[0]\n record = self.driver.list_records(zone=zone)[0]\n updated_record = self.driver.update_record(record=record, data='127.3.3.3')\n self.assertEqual(record.name, 'test3')\n self.assertEqual(record.data, '127.7.7.7')\n self.assertEqual(updated_record.id, record.id)\n self.assertEqual(updated_record.name, record.name)\n self.assertEqual(updated_record.zone, record.zone)\n self.assertEqual(updated_record.type, record.type)\n self.assertEqual(updated_record.data, '127.3.3.3')\n", "method_code": " def update_record(self, record, name=None, type=None, data=None, extra=None):\n extra = extra if extra else {}\n name = self._to_full_record_name(domain=record.zone.domain, name=record.name)\n payload = {'name': name}\n if data:\n payload['data'] = data\n if 'ttl' in extra:\n payload['ttl'] = extra['ttl']\n if 'comment' in extra:\n payload['comment'] = extra['comment']\n type = type if type is not None else record.type\n data = data if data else record.data\n self.connection.set_context({'resource': 'record', 'id': record.id})\n self.connection.async_request(action='/domains/%s/records/%s' % (record.zone.id, record.id), method='PUT', data=payload)\n merged = merge_valid_keys(params=copy.deepcopy(record.extra), valid_keys=VALID_RECORD_EXTRA_PARAMS, extra=extra)\n updated_record = get_new_obj(obj=record, klass=Record, attributes={'type': type, 'data': data, 'extra': merged})\n return updated_record\n ", "context": "class RackspaceDNSDriver(DNSDriverOpenStackDriverMixin):\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n def __init__(self, *args, **kwargs): ...\n def _ex_connection_class_kwargs(self): ...\n def list_zones(self): ...\n def list_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def delete_zone(self, zone): ...\n def delete_record(self, record): ...\n def _to_zones(self, data): ...\n def _to_zone(self, data): ...\n def _to_records(self, data, zone): ...\n def _to_record(self, data, zone): ...\n def _to_full_record_name(self, domain, name): ...\n def _to_partial_record_name(self, domain, name): ...\n\n website = 'http://www.rackspace.com/'\n RECORD_TYPE_MAP = {RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.MX: 'MX', RecordType.NS: 'NS', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_update_record_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000829.py"} {"focal_file": "libcloud/dns/drivers/rackspace.py", "focal_class": null, "focal_method": "delete_zone", "tests": "import unittest\n\nclass Test_delete_zone(unittest.TestCase):\n def test_delete_zone_success(self):\n zone = self.driver.list_zones()[0]\n status = self.driver.delete_zone(zone=zone)\n self.assertTrue(status)\n", "method_code": " def delete_zone(self, zone):\n self.connection.set_context({'resource': 'zone', 'id': zone.id})\n self.connection.async_request(action='/domains/%s' % zone.id, method='DELETE')\n return True\n ", "context": "class RackspaceDNSDriver(DNSDriverOpenStackDriverMixin):\n def delete_zone(self, zone): ...\n def __init__(self, *args, **kwargs): ...\n def _ex_connection_class_kwargs(self): ...\n def list_zones(self): ...\n def list_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n def delete_record(self, record): ...\n def _to_zones(self, data): ...\n def _to_zone(self, data): ...\n def _to_records(self, data, zone): ...\n def _to_record(self, data, zone): ...\n def _to_full_record_name(self, domain, name): ...\n def _to_partial_record_name(self, domain, name): ...\n\n website = 'http://www.rackspace.com/'\n RECORD_TYPE_MAP = {RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.MX: 'MX', RecordType.NS: 'NS', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_delete_zone_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000830.py"} {"focal_file": "libcloud/dns/drivers/rackspace.py", "focal_class": null, "focal_method": "delete_record", "tests": "import unittest\n\nclass Test_delete_record(unittest.TestCase):\n def test_delete_record_success(self):\n zone = self.driver.list_zones()[0]\n record = self.driver.list_records(zone=zone)[0]\n status = self.driver.delete_record(record=record)\n self.assertTrue(status)\n", "method_code": " def delete_record(self, record):\n self.connection.set_context({'resource': 'record', 'id': record.id})\n self.connection.async_request(action='/domains/%s/records/%s' % (record.zone.id, record.id), method='DELETE')\n return True\n ", "context": "class RackspaceDNSDriver(DNSDriverOpenStackDriverMixin):\n def delete_record(self, record): ...\n def __init__(self, *args, **kwargs): ...\n def _ex_connection_class_kwargs(self): ...\n def list_zones(self): ...\n def list_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n def delete_zone(self, zone): ...\n def _to_zones(self, data): ...\n def _to_zone(self, data): ...\n def _to_records(self, data, zone): ...\n def _to_record(self, data, zone): ...\n def _to_full_record_name(self, domain, name): ...\n def _to_partial_record_name(self, domain, name): ...\n\n website = 'http://www.rackspace.com/'\n RECORD_TYPE_MAP = {RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.MX: 'MX', RecordType.NS: 'NS', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_delete_record_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000831.py"} {"focal_file": "libcloud/dns/drivers/rackspace.py", "focal_class": null, "focal_method": "_to_full_record_name", "tests": "import unittest\n\nclass Test_to_full_record_name(unittest.TestCase):\n def test_to_full_record_name_name_provided(self):\n domain = 'foo.bar'\n name = 'test'\n self.assertEquals(self.driver._to_full_record_name(domain, name), 'test.foo.bar')\n\n def test_to_full_record_name_name_not_provided(self):\n domain = 'foo.bar'\n name = None\n self.assertEquals(self.driver._to_full_record_name(domain, name), 'foo.bar')\n", "method_code": " def _to_full_record_name(self, domain, name):\n \"\"\"\n Build a FQDN from a domain and record name.\n \n @param domain: Domain name.\n @type domain: C{str}\n \n @param name: Record name.\n @type name: C{str}\n \"\"\"\n if name:\n name = '%s.%s' % (name, domain)\n else:\n name = domain\n return name\n ", "context": "class RackspaceDNSDriver(DNSDriverOpenStackDriverMixin):\n def _to_full_record_name(self, domain, name): ...\n def __init__(self, *args, **kwargs): ...\n def _ex_connection_class_kwargs(self): ...\n def list_zones(self): ...\n def list_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n def delete_zone(self, zone): ...\n def delete_record(self, record): ...\n def _to_zones(self, data): ...\n def _to_zone(self, data): ...\n def _to_records(self, data, zone): ...\n def _to_record(self, data, zone): ...\n def _to_partial_record_name(self, domain, name): ...\n\n website = 'http://www.rackspace.com/'\n RECORD_TYPE_MAP = {RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.MX: 'MX', RecordType.NS: 'NS', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_to_full_record_name_name_provided", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000832.py"} {"focal_file": "libcloud/dns/drivers/route53.py", "focal_class": null, "focal_method": "list_zones", "tests": "import unittest\n\nclass Test_list_zones(unittest.TestCase):\n def test_list_zones(self):\n zones = self.driver.list_zones()\n self.assertEqual(len(zones), 5)\n zone = zones[0]\n self.assertEqual(zone.id, '47234')\n self.assertEqual(zone.type, 'master')\n self.assertEqual(zone.domain, 't.com')\n", "method_code": " def list_zones(self):\n data = self.connection.request(API_ROOT + 'hostedzone').object\n zones = self._to_zones(data=data)\n return zones\n ", "context": "class Route53DNSDriver(DNSDriver):\n def list_zones(self): ...\n def list_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def delete_zone(self, zone, ex_delete_records=False): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name, type, data, extra): ...\n def delete_record(self, record): ...\n def ex_delete_all_records(self, zone): ...\n def _post_changeset(self, zone, changes_list): ...\n def _to_zones(self, data): ...\n def _to_zone(self, elem): ...\n def _to_records(self, data, zone): ...\n def _to_record(self, elem, zone): ...\n\n type = Provider.ROUTE53\n name = 'Route53 DNS'\n website = 'http://aws.amazon.com/route53/'\n connectionCls = Route53Connection\n RECORD_TYPE_MAP = {RecordType.NS: 'NS', RecordType.MX: 'MX', RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV', RecordType.PTR: 'PTR', RecordType.SOA: 'SOA', RecordType.SPF: 'SPF', RecordType.TXT: 'TXT'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_zones", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000833.py"} {"focal_file": "libcloud/dns/drivers/route53.py", "focal_class": null, "focal_method": "list_records", "tests": "import unittest\n\nclass Test_list_records(unittest.TestCase):\n def test_list_records(self):\n zone = self.driver.list_zones()[0]\n records = self.driver.list_records(zone=zone)\n self.assertEqual(len(records), 3)\n record = records[1]\n self.assertEqual(record.name, 'www')\n self.assertEqual(record.id, 'A:www')\n self.assertEqual(record.type, RecordType.A)\n self.assertEqual(record.data, '208.111.35.173')\n", "method_code": " def list_records(self, zone):\n self.connection.set_context({'zone_id': zone.id})\n uri = API_ROOT + 'hostedzone/' + zone.id + '/rrset'\n data = self.connection.request(uri).object\n records = self._to_records(data=data, zone=zone)\n return records\n ", "context": "class Route53DNSDriver(DNSDriver):\n def list_records(self, zone): ...\n def list_zones(self): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def delete_zone(self, zone, ex_delete_records=False): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name, type, data, extra): ...\n def delete_record(self, record): ...\n def ex_delete_all_records(self, zone): ...\n def _post_changeset(self, zone, changes_list): ...\n def _to_zones(self, data): ...\n def _to_zone(self, elem): ...\n def _to_records(self, data, zone): ...\n def _to_record(self, elem, zone): ...\n\n type = Provider.ROUTE53\n name = 'Route53 DNS'\n website = 'http://aws.amazon.com/route53/'\n connectionCls = Route53Connection\n RECORD_TYPE_MAP = {RecordType.NS: 'NS', RecordType.MX: 'MX', RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV', RecordType.PTR: 'PTR', RecordType.SOA: 'SOA', RecordType.SPF: 'SPF', RecordType.TXT: 'TXT'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_records", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000834.py"} {"focal_file": "libcloud/dns/drivers/route53.py", "focal_class": null, "focal_method": "get_zone", "tests": "import unittest\n\nclass Test_get_zone(unittest.TestCase):\n def test_get_zone(self):\n zone = self.driver.get_zone(zone_id='47234')\n self.assertEqual(zone.id, '47234')\n self.assertEqual(zone.type, 'master')\n self.assertEqual(zone.domain, 't.com')\n", "method_code": " def get_zone(self, zone_id):\n self.connection.set_context({'zone_id': zone_id})\n uri = API_ROOT + 'hostedzone/' + zone_id\n data = self.connection.request(uri).object\n elem = findall(element=data, xpath='HostedZone', namespace=NAMESPACE)[0]\n return self._to_zone(elem)\n ", "context": "class Route53DNSDriver(DNSDriver):\n def get_zone(self, zone_id): ...\n def list_zones(self): ...\n def list_records(self, zone): ...\n def get_record(self, zone_id, record_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def delete_zone(self, zone, ex_delete_records=False): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name, type, data, extra): ...\n def delete_record(self, record): ...\n def ex_delete_all_records(self, zone): ...\n def _post_changeset(self, zone, changes_list): ...\n def _to_zones(self, data): ...\n def _to_zone(self, elem): ...\n def _to_records(self, data, zone): ...\n def _to_record(self, elem, zone): ...\n\n type = Provider.ROUTE53\n name = 'Route53 DNS'\n website = 'http://aws.amazon.com/route53/'\n connectionCls = Route53Connection\n RECORD_TYPE_MAP = {RecordType.NS: 'NS', RecordType.MX: 'MX', RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV', RecordType.PTR: 'PTR', RecordType.SOA: 'SOA', RecordType.SPF: 'SPF', RecordType.TXT: 'TXT'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_get_zone", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000835.py"} {"focal_file": "libcloud/dns/drivers/route53.py", "focal_class": null, "focal_method": "get_record", "tests": "import unittest\n\nclass Test_get_record(unittest.TestCase):\n def test_get_record(self):\n record = self.driver.get_record(zone_id='47234', record_id='CNAME:wibble')\n self.assertEqual(record.name, 'wibble')\n self.assertEqual(record.type, RecordType.CNAME)\n self.assertEqual(record.data, 't.com')\n", "method_code": " def get_record(self, zone_id, record_id):\n zone = self.get_zone(zone_id=zone_id)\n record_type, name = record_id.split(':', 1)\n if name:\n full_name = '.'.join((name, zone.domain))\n else:\n full_name = zone.domain\n self.connection.set_context({'zone_id': zone_id})\n params = urlencode({'name': full_name, 'type': record_type, 'maxitems': '1'})\n uri = API_ROOT + 'hostedzone/' + zone_id + '/rrset?' + params\n data = self.connection.request(uri).object\n record = self._to_records(data=data, zone=zone)[0]\n record_type_num = self._string_to_record_type(record_type)\n if record.name != name or record.type != record_type_num:\n raise RecordDoesNotExistError(value='', driver=self, record_id=record_id)\n return record\n ", "context": "class Route53DNSDriver(DNSDriver):\n def get_record(self, zone_id, record_id): ...\n def list_zones(self): ...\n def list_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def delete_zone(self, zone, ex_delete_records=False): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name, type, data, extra): ...\n def delete_record(self, record): ...\n def ex_delete_all_records(self, zone): ...\n def _post_changeset(self, zone, changes_list): ...\n def _to_zones(self, data): ...\n def _to_zone(self, elem): ...\n def _to_records(self, data, zone): ...\n def _to_record(self, elem, zone): ...\n\n type = Provider.ROUTE53\n name = 'Route53 DNS'\n website = 'http://aws.amazon.com/route53/'\n connectionCls = Route53Connection\n RECORD_TYPE_MAP = {RecordType.NS: 'NS', RecordType.MX: 'MX', RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV', RecordType.PTR: 'PTR', RecordType.SOA: 'SOA', RecordType.SPF: 'SPF', RecordType.TXT: 'TXT'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_get_record", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000836.py"} {"focal_file": "libcloud/dns/drivers/route53.py", "focal_class": null, "focal_method": "create_zone", "tests": "import unittest\n\nclass Test_create_zone(unittest.TestCase):\n def test_create_zone(self):\n zone = self.driver.create_zone(domain='t.com', type='master', ttl=None, extra=None)\n self.assertEqual(zone.id, '47234')\n self.assertEqual(zone.domain, 't.com')\n", "method_code": " def create_zone(self, domain, type='master', ttl=None, extra=None):\n zone = ET.Element('CreateHostedZoneRequest', {'xmlns': NAMESPACE})\n ET.SubElement(zone, 'Name').text = domain\n ET.SubElement(zone, 'CallerReference').text = str(uuid.uuid4())\n if extra and 'Comment' in extra:\n hzg = ET.SubElement(zone, 'HostedZoneConfig')\n ET.SubElement(hzg, 'Comment').text = extra['Comment']\n uri = API_ROOT + 'hostedzone'\n data = ET.tostring(zone)\n rsp = self.connection.request(uri, method='POST', data=data).object\n elem = findall(element=rsp, xpath='HostedZone', namespace=NAMESPACE)[0]\n return self._to_zone(elem=elem)\n ", "context": "class Route53DNSDriver(DNSDriver):\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def list_zones(self): ...\n def list_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def delete_zone(self, zone, ex_delete_records=False): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name, type, data, extra): ...\n def delete_record(self, record): ...\n def ex_delete_all_records(self, zone): ...\n def _post_changeset(self, zone, changes_list): ...\n def _to_zones(self, data): ...\n def _to_zone(self, elem): ...\n def _to_records(self, data, zone): ...\n def _to_record(self, elem, zone): ...\n\n type = Provider.ROUTE53\n name = 'Route53 DNS'\n website = 'http://aws.amazon.com/route53/'\n connectionCls = Route53Connection\n RECORD_TYPE_MAP = {RecordType.NS: 'NS', RecordType.MX: 'MX', RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV', RecordType.PTR: 'PTR', RecordType.SOA: 'SOA', RecordType.SPF: 'SPF', RecordType.TXT: 'TXT'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_zone", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000837.py"} {"focal_file": "libcloud/dns/drivers/route53.py", "focal_class": null, "focal_method": "create_record", "tests": "import unittest\n\nclass Test_create_record(unittest.TestCase):\n def test_create_record(self):\n zone = self.driver.list_zones()[0]\n record = self.driver.create_record(name='www', zone=zone, type=RecordType.A, data='127.0.0.1', extra={'ttl': 0})\n self.assertEqual(record.id, 'A:www')\n self.assertEqual(record.name, 'www')\n self.assertEqual(record.zone, zone)\n self.assertEqual(record.type, RecordType.A)\n self.assertEqual(record.data, '127.0.0.1')\n", "method_code": " def create_record(self, name, zone, type, data, extra=None):\n batch = [('CREATE', name, type, data, extra)]\n self._post_changeset(zone, batch)\n id = ':'.join((self.RECORD_TYPE_MAP[type], name))\n return Record(id=id, name=name, type=type, data=data, zone=zone, driver=self, extra=extra)\n ", "context": "class Route53DNSDriver(DNSDriver):\n def create_record(self, name, zone, type, data, extra=None): ...\n def list_zones(self): ...\n def list_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def delete_zone(self, zone, ex_delete_records=False): ...\n def update_record(self, record, name, type, data, extra): ...\n def delete_record(self, record): ...\n def ex_delete_all_records(self, zone): ...\n def _post_changeset(self, zone, changes_list): ...\n def _to_zones(self, data): ...\n def _to_zone(self, elem): ...\n def _to_records(self, data, zone): ...\n def _to_record(self, elem, zone): ...\n\n type = Provider.ROUTE53\n name = 'Route53 DNS'\n website = 'http://aws.amazon.com/route53/'\n connectionCls = Route53Connection\n RECORD_TYPE_MAP = {RecordType.NS: 'NS', RecordType.MX: 'MX', RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV', RecordType.PTR: 'PTR', RecordType.SOA: 'SOA', RecordType.SPF: 'SPF', RecordType.TXT: 'TXT'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_record", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000838.py"} {"focal_file": "libcloud/dns/drivers/route53.py", "focal_class": null, "focal_method": "update_record", "tests": "import unittest\n\nclass Test_update_record(unittest.TestCase):\n def test_update_record(self):\n zone = self.driver.list_zones()[0]\n record = self.driver.list_records(zone=zone)[1]\n params = {'record': record, 'name': 'www', 'type': RecordType.A, 'data': '::1', 'extra': {'ttle': 0}}\n updated_record = self.driver.update_record(**params)\n self.assertEqual(record.data, '208.111.35.173')\n self.assertEqual(updated_record.id, 'A:www')\n self.assertEqual(updated_record.name, 'www')\n self.assertEqual(updated_record.zone, record.zone)\n self.assertEqual(updated_record.type, RecordType.A)\n self.assertEqual(updated_record.data, '::1')\n", "method_code": " def update_record(self, record, name, type, data, extra):\n batch = [('DELETE', record.name, record.type, record.data, record.extra), ('CREATE', name, type, data, extra)]\n self._post_changeset(record.zone, batch)\n id = ':'.join((self.RECORD_TYPE_MAP[type], name))\n return Record(id=id, name=name, type=type, data=data, zone=record.zone, driver=self, extra=extra)\n ", "context": "class Route53DNSDriver(DNSDriver):\n def update_record(self, record, name, type, data, extra): ...\n def list_zones(self): ...\n def list_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def delete_zone(self, zone, ex_delete_records=False): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def delete_record(self, record): ...\n def ex_delete_all_records(self, zone): ...\n def _post_changeset(self, zone, changes_list): ...\n def _to_zones(self, data): ...\n def _to_zone(self, elem): ...\n def _to_records(self, data, zone): ...\n def _to_record(self, elem, zone): ...\n\n type = Provider.ROUTE53\n name = 'Route53 DNS'\n website = 'http://aws.amazon.com/route53/'\n connectionCls = Route53Connection\n RECORD_TYPE_MAP = {RecordType.NS: 'NS', RecordType.MX: 'MX', RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV', RecordType.PTR: 'PTR', RecordType.SOA: 'SOA', RecordType.SPF: 'SPF', RecordType.TXT: 'TXT'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_update_record", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000839.py"} {"focal_file": "libcloud/dns/drivers/route53.py", "focal_class": null, "focal_method": "delete_zone", "tests": "import unittest\n\nclass Test_delete_zone(unittest.TestCase):\n def test_delete_zone(self):\n zone = self.driver.list_zones()[0]\n status = self.driver.delete_zone(zone=zone)\n self.assertTrue(status)\n", "method_code": " def delete_zone(self, zone, ex_delete_records=False):\n self.connection.set_context({'zone_id': zone.id})\n if ex_delete_records:\n self.ex_delete_all_records(zone=zone)\n uri = API_ROOT + 'hostedzone/%s' % zone.id\n response = self.connection.request(uri, method='DELETE')\n return response.status in [httplib.OK]\n ", "context": "class Route53DNSDriver(DNSDriver):\n def delete_zone(self, zone, ex_delete_records=False): ...\n def list_zones(self): ...\n def list_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name, type, data, extra): ...\n def delete_record(self, record): ...\n def ex_delete_all_records(self, zone): ...\n def _post_changeset(self, zone, changes_list): ...\n def _to_zones(self, data): ...\n def _to_zone(self, elem): ...\n def _to_records(self, data, zone): ...\n def _to_record(self, elem, zone): ...\n\n type = Provider.ROUTE53\n name = 'Route53 DNS'\n website = 'http://aws.amazon.com/route53/'\n connectionCls = Route53Connection\n RECORD_TYPE_MAP = {RecordType.NS: 'NS', RecordType.MX: 'MX', RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV', RecordType.PTR: 'PTR', RecordType.SOA: 'SOA', RecordType.SPF: 'SPF', RecordType.TXT: 'TXT'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_delete_zone", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 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": "libcloud/dns/drivers/route53.py", "focal_class": null, "focal_method": "delete_record", "tests": "import unittest\n\nclass Test_delete_record(unittest.TestCase):\n def test_delete_record(self):\n zone = self.driver.list_zones()[0]\n record = self.driver.list_records(zone=zone)[0]\n status = self.driver.delete_record(record=record)\n self.assertTrue(status)\n", "method_code": " def delete_record(self, record):\n try:\n r = record\n batch = [('DELETE', r.name, r.type, r.data, r.extra)]\n self._post_changeset(record.zone, batch)\n except InvalidChangeBatch:\n raise RecordDoesNotExistError(value='', driver=self, record_id=r.id)\n return True\n ", "context": "class Route53DNSDriver(DNSDriver):\n def delete_record(self, record): ...\n def list_zones(self): ...\n def list_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def delete_zone(self, zone, ex_delete_records=False): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name, type, data, extra): ...\n def ex_delete_all_records(self, zone): ...\n def _post_changeset(self, zone, changes_list): ...\n def _to_zones(self, data): ...\n def _to_zone(self, elem): ...\n def _to_records(self, data, zone): ...\n def _to_record(self, elem, zone): ...\n\n type = Provider.ROUTE53\n name = 'Route53 DNS'\n website = 'http://aws.amazon.com/route53/'\n connectionCls = Route53Connection\n RECORD_TYPE_MAP = {RecordType.NS: 'NS', RecordType.MX: 'MX', RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV', RecordType.PTR: 'PTR', RecordType.SOA: 'SOA', RecordType.SPF: 'SPF', RecordType.TXT: 'TXT'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_delete_record", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 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": "libcloud/dns/drivers/zerigo.py", "focal_class": null, "focal_method": "create_zone", "tests": "import unittest\n\nclass Test_create_zone(unittest.TestCase):\n def test_create_zone_success(self):\n ZerigoMockHttp.type = 'CREATE_ZONE'\n zone = self.driver.create_zone(domain='foo.bar.com', type='master', ttl=None, extra=None)\n self.assertEqual(zone.id, '12345679')\n self.assertEqual(zone.domain, 'foo.bar.com')\n", "method_code": " def create_zone(self, domain, type='master', ttl=None, extra=None):\n \"\"\"\n Create a new zone.\n \n Provider API docs:\n https://www.zerigo.com/docs/apis/dns/1.1/zones/create\n \n @inherits: L{DNSDriver.create_zone}\n \"\"\"\n path = API_ROOT + 'zones.xml'\n zone_elem = self._to_zone_elem(domain=domain, type=type, ttl=ttl, extra=extra)\n data = self.connection.request(action=path, data=ET.tostring(zone_elem), method='POST').object\n zone = self._to_zone(elem=data)\n return zone\n ", "context": "class ZerigoDNSDriver(DNSDriver):\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def iterate_zones(self): ...\n def iterate_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n def delete_zone(self, zone): ...\n def delete_record(self, record): ...\n def ex_get_zone_by_domain(self, domain): ...\n def ex_force_slave_axfr(self, zone): ...\n def _to_zone_elem(self, domain=None, type=None, ttl=None, extra=None): ...\n def _to_record_elem(self, name=None, type=None, data=None, extra=None): ...\n def _to_zones(self, elem): ...\n def _to_zone(self, elem): ...\n def _to_records(self, elem, zone): ...\n def _to_record(self, elem, zone): ...\n def _get_more(self, rtype, **kwargs): ...\n def _get_data(self, rtype, last_key, **kwargs): ...\n\n type = Provider.ZERIGO\n name = 'Zerigo DNS'\n website = 'http://www.zerigo.com/'\n connectionCls = ZerigoDNSConnection\n RECORD_TYPE_MAP = {RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.MX: 'MX', RecordType.REDIRECT: 'REDIRECT', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV', RecordType.NAPTR: 'NAPTR', RecordType.NS: 'NS', RecordType.PTR: 'PTR', RecordType.SPF: 'SPF', RecordType.GEO: 'GEO', RecordType.URL: 'URL'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_zone_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000842.py"} {"focal_file": "libcloud/dns/drivers/zerigo.py", "focal_class": null, "focal_method": "update_zone", "tests": "import unittest\n\nclass Test_update_zone(unittest.TestCase):\n def test_update_zone_success(self):\n zone = self.driver.list_zones()[0]\n updated_zone = self.driver.update_zone(zone=zone, ttl=10, extra={'notes': 'bar foo'})\n self.assertEqual(zone.extra['notes'], 'test foo bar')\n self.assertEqual(updated_zone.id, zone.id)\n self.assertEqual(updated_zone.domain, 'example.com')\n self.assertEqual(updated_zone.type, zone.type)\n self.assertEqual(updated_zone.ttl, 10)\n self.assertEqual(updated_zone.extra['notes'], 'bar foo')\n", "method_code": " def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None):\n \"\"\"\n Update an existing zone.\n \n Provider API docs:\n https://www.zerigo.com/docs/apis/dns/1.1/zones/update\n \n @inherits: L{DNSDriver.update_zone}\n \"\"\"\n if domain:\n raise LibcloudError('Domain cannot be changed', driver=self)\n path = API_ROOT + 'zones/%s.xml' % zone.id\n zone_elem = self._to_zone_elem(domain=domain, type=type, ttl=ttl, extra=extra)\n response = self.connection.request(action=path, data=ET.tostring(zone_elem), method='PUT')\n assert response.status == httplib.OK\n merged = merge_valid_keys(params=copy.deepcopy(zone.extra), valid_keys=VALID_ZONE_EXTRA_PARAMS, extra=extra)\n updated_zone = get_new_obj(obj=zone, klass=Zone, attributes={'type': type, 'ttl': ttl, 'extra': merged})\n return updated_zone\n ", "context": "class ZerigoDNSDriver(DNSDriver):\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def iterate_zones(self): ...\n def iterate_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n def delete_zone(self, zone): ...\n def delete_record(self, record): ...\n def ex_get_zone_by_domain(self, domain): ...\n def ex_force_slave_axfr(self, zone): ...\n def _to_zone_elem(self, domain=None, type=None, ttl=None, extra=None): ...\n def _to_record_elem(self, name=None, type=None, data=None, extra=None): ...\n def _to_zones(self, elem): ...\n def _to_zone(self, elem): ...\n def _to_records(self, elem, zone): ...\n def _to_record(self, elem, zone): ...\n def _get_more(self, rtype, **kwargs): ...\n def _get_data(self, rtype, last_key, **kwargs): ...\n\n type = Provider.ZERIGO\n name = 'Zerigo DNS'\n website = 'http://www.zerigo.com/'\n connectionCls = ZerigoDNSConnection\n RECORD_TYPE_MAP = {RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.MX: 'MX', RecordType.REDIRECT: 'REDIRECT', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV', RecordType.NAPTR: 'NAPTR', RecordType.NS: 'NS', RecordType.PTR: 'PTR', RecordType.SPF: 'SPF', RecordType.GEO: 'GEO', RecordType.URL: 'URL'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_update_zone_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000843.py"} {"focal_file": "libcloud/dns/drivers/zerigo.py", "focal_class": null, "focal_method": "create_record", "tests": "import unittest\n\nclass Test_create_record(unittest.TestCase):\n def test_create_record_success(self):\n zone = self.driver.list_zones()[0]\n ZerigoMockHttp.type = 'CREATE_RECORD'\n record = self.driver.create_record(name='www', zone=zone, type=RecordType.A, data='127.0.0.1')\n self.assertEqual(record.id, '23456780')\n self.assertEqual(record.name, 'www')\n self.assertEqual(record.zone, zone)\n self.assertEqual(record.type, RecordType.A)\n self.assertEqual(record.data, '127.0.0.1')\n", "method_code": " def create_record(self, name, zone, type, data, extra=None):\n \"\"\"\n Create a new record.\n \n Provider API docs:\n https://www.zerigo.com/docs/apis/dns/1.1/hosts/create\n \n @inherits: L{DNSDriver.create_record}\n \"\"\"\n path = API_ROOT + 'zones/%s/hosts.xml' % zone.id\n record_elem = self._to_record_elem(name=name, type=type, data=data, extra=extra)\n response = self.connection.request(action=path, data=ET.tostring(record_elem), method='POST')\n assert response.status == httplib.CREATED\n record = self._to_record(elem=response.object, zone=zone)\n return record\n ", "context": "class ZerigoDNSDriver(DNSDriver):\n def create_record(self, name, zone, type, data, extra=None): ...\n def iterate_zones(self): ...\n def iterate_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n def delete_zone(self, zone): ...\n def delete_record(self, record): ...\n def ex_get_zone_by_domain(self, domain): ...\n def ex_force_slave_axfr(self, zone): ...\n def _to_zone_elem(self, domain=None, type=None, ttl=None, extra=None): ...\n def _to_record_elem(self, name=None, type=None, data=None, extra=None): ...\n def _to_zones(self, elem): ...\n def _to_zone(self, elem): ...\n def _to_records(self, elem, zone): ...\n def _to_record(self, elem, zone): ...\n def _get_more(self, rtype, **kwargs): ...\n def _get_data(self, rtype, last_key, **kwargs): ...\n\n type = Provider.ZERIGO\n name = 'Zerigo DNS'\n website = 'http://www.zerigo.com/'\n connectionCls = ZerigoDNSConnection\n RECORD_TYPE_MAP = {RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.MX: 'MX', RecordType.REDIRECT: 'REDIRECT', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV', RecordType.NAPTR: 'NAPTR', RecordType.NS: 'NS', RecordType.PTR: 'PTR', RecordType.SPF: 'SPF', RecordType.GEO: 'GEO', RecordType.URL: 'URL'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_record_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000844.py"} {"focal_file": "libcloud/dns/drivers/zerigo.py", "focal_class": null, "focal_method": "update_record", "tests": "import unittest\n\nclass Test_update_record(unittest.TestCase):\n def test_update_record_success(self):\n zone = self.driver.list_zones()[0]\n record = self.driver.list_records(zone=zone)[0]\n updated_record = self.driver.update_record(record=record, name='www', type=RecordType.AAAA, data='::1')\n self.assertEqual(record.data, '172.16.16.1')\n self.assertEqual(updated_record.id, record.id)\n self.assertEqual(updated_record.name, 'www')\n self.assertEqual(updated_record.zone, record.zone)\n self.assertEqual(updated_record.type, RecordType.AAAA)\n self.assertEqual(updated_record.data, '::1')\n", "method_code": " def update_record(self, record, name=None, type=None, data=None, extra=None):\n path = API_ROOT + 'hosts/%s.xml' % record.id\n record_elem = self._to_record_elem(name=name, type=type, data=data, extra=extra)\n response = self.connection.request(action=path, data=ET.tostring(record_elem), method='PUT')\n assert response.status == httplib.OK\n merged = merge_valid_keys(params=copy.deepcopy(record.extra), valid_keys=VALID_RECORD_EXTRA_PARAMS, extra=extra)\n updated_record = get_new_obj(obj=record, klass=Record, attributes={'type': type, 'data': data, 'extra': merged})\n return updated_record\n ", "context": "class ZerigoDNSDriver(DNSDriver):\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n def iterate_zones(self): ...\n def iterate_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def delete_zone(self, zone): ...\n def delete_record(self, record): ...\n def ex_get_zone_by_domain(self, domain): ...\n def ex_force_slave_axfr(self, zone): ...\n def _to_zone_elem(self, domain=None, type=None, ttl=None, extra=None): ...\n def _to_record_elem(self, name=None, type=None, data=None, extra=None): ...\n def _to_zones(self, elem): ...\n def _to_zone(self, elem): ...\n def _to_records(self, elem, zone): ...\n def _to_record(self, elem, zone): ...\n def _get_more(self, rtype, **kwargs): ...\n def _get_data(self, rtype, last_key, **kwargs): ...\n\n type = Provider.ZERIGO\n name = 'Zerigo DNS'\n website = 'http://www.zerigo.com/'\n connectionCls = ZerigoDNSConnection\n RECORD_TYPE_MAP = {RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.MX: 'MX', RecordType.REDIRECT: 'REDIRECT', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV', RecordType.NAPTR: 'NAPTR', RecordType.NS: 'NS', RecordType.PTR: 'PTR', RecordType.SPF: 'SPF', RecordType.GEO: 'GEO', RecordType.URL: 'URL'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_update_record_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000845.py"} {"focal_file": "libcloud/dns/drivers/zerigo.py", "focal_class": null, "focal_method": "delete_zone", "tests": "import unittest\n\nclass Test_delete_zone(unittest.TestCase):\n def test_delete_zone_success(self):\n zone = self.driver.list_zones()[0]\n status = self.driver.delete_zone(zone=zone)\n self.assertTrue(status)\n", "method_code": " def delete_zone(self, zone):\n path = API_ROOT + 'zones/%s.xml' % zone.id\n self.connection.set_context({'resource': 'zone', 'id': zone.id})\n response = self.connection.request(action=path, method='DELETE')\n return response.status == httplib.OK\n ", "context": "class ZerigoDNSDriver(DNSDriver):\n def delete_zone(self, zone): ...\n def iterate_zones(self): ...\n def iterate_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n def delete_record(self, record): ...\n def ex_get_zone_by_domain(self, domain): ...\n def ex_force_slave_axfr(self, zone): ...\n def _to_zone_elem(self, domain=None, type=None, ttl=None, extra=None): ...\n def _to_record_elem(self, name=None, type=None, data=None, extra=None): ...\n def _to_zones(self, elem): ...\n def _to_zone(self, elem): ...\n def _to_records(self, elem, zone): ...\n def _to_record(self, elem, zone): ...\n def _get_more(self, rtype, **kwargs): ...\n def _get_data(self, rtype, last_key, **kwargs): ...\n\n type = Provider.ZERIGO\n name = 'Zerigo DNS'\n website = 'http://www.zerigo.com/'\n connectionCls = ZerigoDNSConnection\n RECORD_TYPE_MAP = {RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.MX: 'MX', RecordType.REDIRECT: 'REDIRECT', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV', RecordType.NAPTR: 'NAPTR', RecordType.NS: 'NS', RecordType.PTR: 'PTR', RecordType.SPF: 'SPF', RecordType.GEO: 'GEO', RecordType.URL: 'URL'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_delete_zone_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000846.py"} {"focal_file": "libcloud/dns/drivers/zerigo.py", "focal_class": null, "focal_method": "delete_record", "tests": "import unittest\n\nclass Test_delete_record(unittest.TestCase):\n def test_delete_record_success(self):\n zone = self.driver.list_zones()[0]\n record = self.driver.list_records(zone=zone)[0]\n status = self.driver.delete_record(record=record)\n self.assertTrue(status)\n", "method_code": " def delete_record(self, record):\n path = API_ROOT + 'hosts/%s.xml' % record.id\n self.connection.set_context({'resource': 'record', 'id': record.id})\n response = self.connection.request(action=path, method='DELETE')\n return response.status == httplib.OK\n ", "context": "class ZerigoDNSDriver(DNSDriver):\n def delete_record(self, record): ...\n def iterate_zones(self): ...\n def iterate_records(self, zone): ...\n def get_zone(self, zone_id): ...\n def get_record(self, zone_id, record_id): ...\n def create_zone(self, domain, type='master', ttl=None, extra=None): ...\n def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): ...\n def create_record(self, name, zone, type, data, extra=None): ...\n def update_record(self, record, name=None, type=None, data=None, extra=None): ...\n def delete_zone(self, zone): ...\n def ex_get_zone_by_domain(self, domain): ...\n def ex_force_slave_axfr(self, zone): ...\n def _to_zone_elem(self, domain=None, type=None, ttl=None, extra=None): ...\n def _to_record_elem(self, name=None, type=None, data=None, extra=None): ...\n def _to_zones(self, elem): ...\n def _to_zone(self, elem): ...\n def _to_records(self, elem, zone): ...\n def _to_record(self, elem, zone): ...\n def _get_more(self, rtype, **kwargs): ...\n def _get_data(self, rtype, last_key, **kwargs): ...\n\n type = Provider.ZERIGO\n name = 'Zerigo DNS'\n website = 'http://www.zerigo.com/'\n connectionCls = ZerigoDNSConnection\n RECORD_TYPE_MAP = {RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.MX: 'MX', RecordType.REDIRECT: 'REDIRECT', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV', RecordType.NAPTR: 'NAPTR', RecordType.NS: 'NS', RecordType.PTR: 'PTR', RecordType.SPF: 'SPF', RecordType.GEO: 'GEO', RecordType.URL: 'URL'}\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_delete_record_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000847.py"} {"focal_file": "libcloud/loadbalancer/drivers/brightbox.py", "focal_class": null, "focal_method": "list_protocols", "tests": "import unittest\n\nclass Test_list_protocols(unittest.TestCase):\n def test_list_protocols(self):\n protocols = self.driver.list_protocols()\n self.assertEqual(len(protocols), 2)\n self.assertTrue('tcp' in protocols)\n self.assertTrue('http' in protocols)\n", "method_code": " def list_protocols(self):\n return ['tcp', 'http']\n ", "context": "class BrightboxLBDriver(Driver):\n def list_protocols(self): ...\n def list_balancers(self): ...\n def create_balancer(self, name, port, protocol, algorithm, members): ...\n def destroy_balancer(self, balancer): ...\n def get_balancer(self, balancer_id): ...\n def balancer_attach_compute_node(self, balancer, node): ...\n def balancer_attach_member(self, balancer, member): ...\n def balancer_detach_member(self, balancer, member): ...\n def balancer_list_members(self, balancer): ...\n def _post(self, path, data={}): ...\n def _to_balancer(self, data): ...\n def _member_to_node(self, member): ...\n def _node_to_member(self, data, balancer): ...\n def _public_ip(self, data): ...\n\n connectionCls = BrightboxConnection\n name = 'Brightbox'\n website = 'http://www.brightbox.co.uk/'\n LB_STATE_MAP = {'creating': State.PENDING, 'active': State.RUNNING, 'deleting': State.UNKNOWN, 'deleted': State.UNKNOWN, 'failing': State.UNKNOWN, 'failed': State.UNKNOWN}\n _VALUE_TO_ALGORITHM_MAP = {'round-robin': Algorithm.ROUND_ROBIN, 'least-connections': Algorithm.LEAST_CONNECTIONS}\n _ALGORITHM_TO_VALUE_MAP = reverse_dict(_VALUE_TO_ALGORITHM_MAP)\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_protocols", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000848.py"} {"focal_file": "libcloud/loadbalancer/drivers/brightbox.py", "focal_class": null, "focal_method": "list_balancers", "tests": "import unittest\n\nclass Test_list_balancers(unittest.TestCase):\n def test_list_balancers(self):\n balancers = self.driver.list_balancers()\n self.assertEquals(len(balancers), 1)\n self.assertEquals(balancers[0].id, 'lba-1235f')\n self.assertEquals(balancers[0].name, 'lb1')\n", "method_code": " def list_balancers(self):\n data = self.connection.request('/%s/load_balancers' % API_VERSION).object\n return list(map(self._to_balancer, data))\n ", "context": "class BrightboxLBDriver(Driver):\n def list_balancers(self): ...\n def list_protocols(self): ...\n def create_balancer(self, name, port, protocol, algorithm, members): ...\n def destroy_balancer(self, balancer): ...\n def get_balancer(self, balancer_id): ...\n def balancer_attach_compute_node(self, balancer, node): ...\n def balancer_attach_member(self, balancer, member): ...\n def balancer_detach_member(self, balancer, member): ...\n def balancer_list_members(self, balancer): ...\n def _post(self, path, data={}): ...\n def _to_balancer(self, data): ...\n def _member_to_node(self, member): ...\n def _node_to_member(self, data, balancer): ...\n def _public_ip(self, data): ...\n\n connectionCls = BrightboxConnection\n name = 'Brightbox'\n website = 'http://www.brightbox.co.uk/'\n LB_STATE_MAP = {'creating': State.PENDING, 'active': State.RUNNING, 'deleting': State.UNKNOWN, 'deleted': State.UNKNOWN, 'failing': State.UNKNOWN, 'failed': State.UNKNOWN}\n _VALUE_TO_ALGORITHM_MAP = {'round-robin': Algorithm.ROUND_ROBIN, 'least-connections': Algorithm.LEAST_CONNECTIONS}\n _ALGORITHM_TO_VALUE_MAP = reverse_dict(_VALUE_TO_ALGORITHM_MAP)\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_balancers", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000849.py"} {"focal_file": "libcloud/loadbalancer/drivers/brightbox.py", "focal_class": null, "focal_method": "get_balancer", "tests": "import unittest\n\nclass Test_get_balancer(unittest.TestCase):\n def test_get_balancer(self):\n balancer = self.driver.get_balancer(balancer_id='lba-1235f')\n self.assertEquals(balancer.id, 'lba-1235f')\n self.assertEquals(balancer.name, 'lb1')\n self.assertEquals(balancer.state, State.RUNNING)\n", "method_code": " def get_balancer(self, balancer_id):\n data = self.connection.request('/%s/load_balancers/%s' % (API_VERSION, balancer_id)).object\n return self._to_balancer(data)\n ", "context": "class BrightboxLBDriver(Driver):\n def get_balancer(self, balancer_id): ...\n def list_protocols(self): ...\n def list_balancers(self): ...\n def create_balancer(self, name, port, protocol, algorithm, members): ...\n def destroy_balancer(self, balancer): ...\n def balancer_attach_compute_node(self, balancer, node): ...\n def balancer_attach_member(self, balancer, member): ...\n def balancer_detach_member(self, balancer, member): ...\n def balancer_list_members(self, balancer): ...\n def _post(self, path, data={}): ...\n def _to_balancer(self, data): ...\n def _member_to_node(self, member): ...\n def _node_to_member(self, data, balancer): ...\n def _public_ip(self, data): ...\n\n connectionCls = BrightboxConnection\n name = 'Brightbox'\n website = 'http://www.brightbox.co.uk/'\n LB_STATE_MAP = {'creating': State.PENDING, 'active': State.RUNNING, 'deleting': State.UNKNOWN, 'deleted': State.UNKNOWN, 'failing': State.UNKNOWN, 'failed': State.UNKNOWN}\n _VALUE_TO_ALGORITHM_MAP = {'round-robin': Algorithm.ROUND_ROBIN, 'least-connections': Algorithm.LEAST_CONNECTIONS}\n _ALGORITHM_TO_VALUE_MAP = reverse_dict(_VALUE_TO_ALGORITHM_MAP)\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_get_balancer", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000850.py"} {"focal_file": "libcloud/loadbalancer/drivers/brightbox.py", "focal_class": null, "focal_method": "destroy_balancer", "tests": "import unittest\n\nclass Test_destroy_balancer(unittest.TestCase):\n def test_destroy_balancer(self):\n balancer = self.driver.get_balancer(balancer_id='lba-1235f')\n self.assertTrue(self.driver.destroy_balancer(balancer))\n", "method_code": " def destroy_balancer(self, balancer):\n response = self.connection.request('/%s/load_balancers/%s' % (API_VERSION, balancer.id), method='DELETE')\n return response.status == httplib.ACCEPTED\n ", "context": "class BrightboxLBDriver(Driver):\n def destroy_balancer(self, balancer): ...\n def list_protocols(self): ...\n def list_balancers(self): ...\n def create_balancer(self, name, port, protocol, algorithm, members): ...\n def get_balancer(self, balancer_id): ...\n def balancer_attach_compute_node(self, balancer, node): ...\n def balancer_attach_member(self, balancer, member): ...\n def balancer_detach_member(self, balancer, member): ...\n def balancer_list_members(self, balancer): ...\n def _post(self, path, data={}): ...\n def _to_balancer(self, data): ...\n def _member_to_node(self, member): ...\n def _node_to_member(self, data, balancer): ...\n def _public_ip(self, data): ...\n\n connectionCls = BrightboxConnection\n name = 'Brightbox'\n website = 'http://www.brightbox.co.uk/'\n LB_STATE_MAP = {'creating': State.PENDING, 'active': State.RUNNING, 'deleting': State.UNKNOWN, 'deleted': State.UNKNOWN, 'failing': State.UNKNOWN, 'failed': State.UNKNOWN}\n _VALUE_TO_ALGORITHM_MAP = {'round-robin': Algorithm.ROUND_ROBIN, 'least-connections': Algorithm.LEAST_CONNECTIONS}\n _ALGORITHM_TO_VALUE_MAP = reverse_dict(_VALUE_TO_ALGORITHM_MAP)\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_destroy_balancer", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000851.py"} {"focal_file": "libcloud/loadbalancer/drivers/brightbox.py", "focal_class": null, "focal_method": "create_balancer", "tests": "import unittest\n\nclass Test_create_balancer(unittest.TestCase):\n def test_create_balancer(self):\n members = [Member('srv-lv426', None, None)]\n balancer = self.driver.create_balancer(name='lb2', port=80, protocol='http', algorithm=Algorithm.ROUND_ROBIN, members=members)\n self.assertEquals(balancer.name, 'lb2')\n self.assertEquals(balancer.port, 80)\n self.assertEquals(balancer.state, State.PENDING)\n", "method_code": " def create_balancer(self, name, port, protocol, algorithm, members):\n response = self._post('/%s/load_balancers' % API_VERSION, {'name': name, 'nodes': list(map(self._member_to_node, members)), 'policy': self._algorithm_to_value(algorithm), 'listeners': [{'in': port, 'out': port, 'protocol': protocol}], 'healthcheck': {'type': protocol, 'port': port}})\n return self._to_balancer(response.object)\n ", "context": "class BrightboxLBDriver(Driver):\n def create_balancer(self, name, port, protocol, algorithm, members): ...\n def list_protocols(self): ...\n def list_balancers(self): ...\n def destroy_balancer(self, balancer): ...\n def get_balancer(self, balancer_id): ...\n def balancer_attach_compute_node(self, balancer, node): ...\n def balancer_attach_member(self, balancer, member): ...\n def balancer_detach_member(self, balancer, member): ...\n def balancer_list_members(self, balancer): ...\n def _post(self, path, data={}): ...\n def _to_balancer(self, data): ...\n def _member_to_node(self, member): ...\n def _node_to_member(self, data, balancer): ...\n def _public_ip(self, data): ...\n\n connectionCls = BrightboxConnection\n name = 'Brightbox'\n website = 'http://www.brightbox.co.uk/'\n LB_STATE_MAP = {'creating': State.PENDING, 'active': State.RUNNING, 'deleting': State.UNKNOWN, 'deleted': State.UNKNOWN, 'failing': State.UNKNOWN, 'failed': State.UNKNOWN}\n _VALUE_TO_ALGORITHM_MAP = {'round-robin': Algorithm.ROUND_ROBIN, 'least-connections': Algorithm.LEAST_CONNECTIONS}\n _ALGORITHM_TO_VALUE_MAP = reverse_dict(_VALUE_TO_ALGORITHM_MAP)\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_balancer", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000852.py"} {"focal_file": "libcloud/loadbalancer/drivers/elb.py", "focal_class": null, "focal_method": "list_protocols", "tests": "import unittest\n\nclass Test_list_protocols(unittest.TestCase):\n def test_list_protocols(self):\n protocols = self.driver.list_protocols()\n self.assertEqual(len(protocols), 4)\n self.assertTrue('tcp' in protocols)\n self.assertTrue('http' in protocols)\n", "method_code": " def list_protocols(self):\n return ['tcp', 'ssl', 'http', 'https']\n ", "context": "class ElasticLBDriver(Driver):\n def list_protocols(self): ...\n def __init__(self, access_id, secret, region): ...\n def list_balancers(self): ...\n def create_balancer(self, name, port, protocol, algorithm, members, ex_members_availability_zones=None): ...\n def destroy_balancer(self, balancer): ...\n def get_balancer(self, balancer_id): ...\n def balancer_attach_compute_node(self, balancer, node): ...\n def balancer_detach_member(self, balancer, member): ...\n def balancer_list_members(self, balancer): ...\n def _to_balancers(self, data): ...\n def _to_balancer(self, el): ...\n\n self.region = region\n self.connection.host = HOST % region\n\n name = 'ELB'\n website = 'http://aws.amazon.com/elasticloadbalancing/'\n connectionCls = ELBConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_protocols", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000853.py"} {"focal_file": "libcloud/loadbalancer/drivers/elb.py", "focal_class": null, "focal_method": "list_balancers", "tests": "import unittest\n\nclass Test_list_balancers(unittest.TestCase):\n def test_list_balancers(self):\n balancers = self.driver.list_balancers()\n self.assertEquals(len(balancers), 1)\n self.assertEquals(balancers[0].id, 'tests')\n self.assertEquals(balancers[0].name, 'tests')\n", "method_code": " def list_balancers(self):\n params = {'Action': 'DescribeLoadBalancers'}\n data = self.connection.request(ROOT, params=params).object\n return self._to_balancers(data)\n ", "context": "class ElasticLBDriver(Driver):\n def list_balancers(self): ...\n def __init__(self, access_id, secret, region): ...\n def list_protocols(self): ...\n def create_balancer(self, name, port, protocol, algorithm, members, ex_members_availability_zones=None): ...\n def destroy_balancer(self, balancer): ...\n def get_balancer(self, balancer_id): ...\n def balancer_attach_compute_node(self, balancer, node): ...\n def balancer_detach_member(self, balancer, member): ...\n def balancer_list_members(self, balancer): ...\n def _to_balancers(self, data): ...\n def _to_balancer(self, el): ...\n\n self.region = region\n self.connection.host = HOST % region\n\n name = 'ELB'\n website = 'http://aws.amazon.com/elasticloadbalancing/'\n connectionCls = ELBConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_balancers", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000854.py"} {"focal_file": "libcloud/loadbalancer/drivers/elb.py", "focal_class": null, "focal_method": "get_balancer", "tests": "import unittest\n\nclass Test_get_balancer(unittest.TestCase):\n def test_get_balancer(self):\n balancer = self.driver.get_balancer(balancer_id='tests')\n self.assertEquals(balancer.id, 'tests')\n self.assertEquals(balancer.name, 'tests')\n self.assertEquals(balancer.state, State.UNKNOWN)\n", "method_code": " def get_balancer(self, balancer_id):\n params = {'Action': 'DescribeLoadBalancers', 'LoadBalancerNames.member.1': balancer_id}\n data = self.connection.request(ROOT, params=params).object\n return self._to_balancers(data)[0]\n ", "context": "class ElasticLBDriver(Driver):\n def get_balancer(self, balancer_id): ...\n def __init__(self, access_id, secret, region): ...\n def list_protocols(self): ...\n def list_balancers(self): ...\n def create_balancer(self, name, port, protocol, algorithm, members, ex_members_availability_zones=None): ...\n def destroy_balancer(self, balancer): ...\n def balancer_attach_compute_node(self, balancer, node): ...\n def balancer_detach_member(self, balancer, member): ...\n def balancer_list_members(self, balancer): ...\n def _to_balancers(self, data): ...\n def _to_balancer(self, el): ...\n\n self.region = region\n self.connection.host = HOST % region\n\n name = 'ELB'\n website = 'http://aws.amazon.com/elasticloadbalancing/'\n connectionCls = ELBConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_get_balancer", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000855.py"} {"focal_file": "libcloud/loadbalancer/drivers/elb.py", "focal_class": null, "focal_method": "destroy_balancer", "tests": "import unittest\n\nclass Test_destroy_balancer(unittest.TestCase):\n def test_destroy_balancer(self):\n balancer = self.driver.get_balancer(balancer_id='tests')\n self.assertTrue(self.driver.destroy_balancer(balancer))\n", "method_code": " def destroy_balancer(self, balancer):\n params = {'Action': 'DeleteLoadBalancer', 'LoadBalancerName': balancer.id}\n self.connection.request(ROOT, params=params)\n return True\n ", "context": "class ElasticLBDriver(Driver):\n def destroy_balancer(self, balancer): ...\n def __init__(self, access_id, secret, region): ...\n def list_protocols(self): ...\n def list_balancers(self): ...\n def create_balancer(self, name, port, protocol, algorithm, members, ex_members_availability_zones=None): ...\n def get_balancer(self, balancer_id): ...\n def balancer_attach_compute_node(self, balancer, node): ...\n def balancer_detach_member(self, balancer, member): ...\n def balancer_list_members(self, balancer): ...\n def _to_balancers(self, data): ...\n def _to_balancer(self, el): ...\n\n self.region = region\n self.connection.host = HOST % region\n\n name = 'ELB'\n website = 'http://aws.amazon.com/elasticloadbalancing/'\n connectionCls = ELBConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_destroy_balancer", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000856.py"} {"focal_file": "libcloud/loadbalancer/drivers/elb.py", "focal_class": null, "focal_method": "create_balancer", "tests": "import unittest\n\nclass Test_create_balancer(unittest.TestCase):\n def test_create_balancer(self):\n members = [Member('srv-lv426', None, None)]\n balancer = self.driver.create_balancer(name='lb2', port=80, protocol='http', algorithm=Algorithm.ROUND_ROBIN, members=members)\n self.assertEquals(balancer.name, 'lb2')\n self.assertEquals(balancer.port, 80)\n self.assertEquals(balancer.state, State.PENDING)\n", "method_code": " def create_balancer(self, name, port, protocol, algorithm, members, ex_members_availability_zones=None):\n if ex_members_availability_zones is None:\n ex_members_availability_zones = ['a']\n params = {'Action': 'CreateLoadBalancer', 'LoadBalancerName': name, 'Listeners.member.1.InstancePort': str(port), 'Listeners.member.1.InstanceProtocol': protocol.upper(), 'Listeners.member.1.LoadBalancerPort': str(port), 'Listeners.member.1.Protocol': protocol.upper()}\n for i, z in enumerate(ex_members_availability_zones):\n zone = ''.join((self.region, z))\n params['AvailabilityZones.member.%d' % (i + 1)] = zone\n data = self.connection.request(ROOT, params=params).object\n balancer = LoadBalancer(id=name, name=name, state=State.PENDING, ip=findtext(element=data, xpath='DNSName', namespace=NS), port=port, driver=self.connection.driver)\n balancer._members = []\n return balancer\n ", "context": "class ElasticLBDriver(Driver):\n def create_balancer(self, name, port, protocol, algorithm, members, ex_members_availability_zones=None): ...\n def __init__(self, access_id, secret, region): ...\n def list_protocols(self): ...\n def list_balancers(self): ...\n def destroy_balancer(self, balancer): ...\n def get_balancer(self, balancer_id): ...\n def balancer_attach_compute_node(self, balancer, node): ...\n def balancer_detach_member(self, balancer, member): ...\n def balancer_list_members(self, balancer): ...\n def _to_balancers(self, data): ...\n def _to_balancer(self, el): ...\n\n self.region = region\n self.connection.host = HOST % region\n\n name = 'ELB'\n website = 'http://aws.amazon.com/elasticloadbalancing/'\n connectionCls = ELBConnection\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_balancer", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000857.py"} {"focal_file": "libcloud/loadbalancer/drivers/gogrid.py", "focal_class": null, "focal_method": "list_protocols", "tests": "import unittest\n\nclass Test_list_protocols(unittest.TestCase):\n def test_list_protocols(self):\n protocols = self.driver.list_protocols()\n self.assertEqual(len(protocols), 1)\n self.assertEqual(protocols[0], 'http')\n", "method_code": " def list_protocols(self):\n return ['http']\n ", "context": "class GoGridLBDriver(BaseGoGridDriverDriver):\n def list_protocols(self): ...\n def __init__(self, *args, **kwargs): ...\n def list_balancers(self): ...\n def ex_create_balancer_nowait(self, name, members, protocol='http', port=80, algorithm=DEFAULT_ALGORITHM): ...\n def create_balancer(self, name, members, protocol='http', port=80, algorithm=DEFAULT_ALGORITHM): ...\n def destroy_balancer(self, balancer): ...\n def get_balancer(self, **kwargs): ...\n def balancer_attach_member(self, balancer, member): ...\n def balancer_detach_member(self, balancer, member): ...\n def balancer_list_members(self, balancer): ...\n def _update_balancer(self, params): ...\n def _members_to_params(self, members): ...\n def _to_balancers(self, object): ...\n def _to_balancer(self, el): ...\n def _to_members(self, object, balancer=None): ...\n def _to_member(self, el, balancer=None): ...\n\n connectionCls = GoGridLBConnection\n api_name = 'gogrid_lb'\n name = 'GoGrid LB'\n website = 'http://www.gogrid.com/'\n LB_STATE_MAP = {'On': State.RUNNING, 'Unknown': State.UNKNOWN}\n _VALUE_TO_ALGORITHM_MAP = {'round robin': Algorithm.ROUND_ROBIN, 'least connect': Algorithm.LEAST_CONNECTIONS}\n _ALGORITHM_TO_VALUE_MAP = reverse_dict(_VALUE_TO_ALGORITHM_MAP)\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_protocols", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000858.py"} {"focal_file": "libcloud/loadbalancer/drivers/gogrid.py", "focal_class": null, "focal_method": "list_balancers", "tests": "import unittest\n\nclass Test_list_balancers(unittest.TestCase):\n def test_list_balancers(self):\n balancers = self.driver.list_balancers()\n self.assertEquals(len(balancers), 2)\n self.assertEquals(balancers[0].name, 'foo')\n self.assertEquals(balancers[0].id, '23517')\n self.assertEquals(balancers[1].name, 'bar')\n self.assertEquals(balancers[1].id, '23526')\n", "method_code": " def list_balancers(self):\n return self._to_balancers(self.connection.request('/api/grid/loadbalancer/list').object)\n ", "context": "class GoGridLBDriver(BaseGoGridDriverDriver):\n def list_balancers(self): ...\n def __init__(self, *args, **kwargs): ...\n def list_protocols(self): ...\n def ex_create_balancer_nowait(self, name, members, protocol='http', port=80, algorithm=DEFAULT_ALGORITHM): ...\n def create_balancer(self, name, members, protocol='http', port=80, algorithm=DEFAULT_ALGORITHM): ...\n def destroy_balancer(self, balancer): ...\n def get_balancer(self, **kwargs): ...\n def balancer_attach_member(self, balancer, member): ...\n def balancer_detach_member(self, balancer, member): ...\n def balancer_list_members(self, balancer): ...\n def _update_balancer(self, params): ...\n def _members_to_params(self, members): ...\n def _to_balancers(self, object): ...\n def _to_balancer(self, el): ...\n def _to_members(self, object, balancer=None): ...\n def _to_member(self, el, balancer=None): ...\n\n connectionCls = GoGridLBConnection\n api_name = 'gogrid_lb'\n name = 'GoGrid LB'\n website = 'http://www.gogrid.com/'\n LB_STATE_MAP = {'On': State.RUNNING, 'Unknown': State.UNKNOWN}\n _VALUE_TO_ALGORITHM_MAP = {'round robin': Algorithm.ROUND_ROBIN, 'least connect': Algorithm.LEAST_CONNECTIONS}\n _ALGORITHM_TO_VALUE_MAP = reverse_dict(_VALUE_TO_ALGORITHM_MAP)\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_balancers", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000859.py"} {"focal_file": "libcloud/loadbalancer/drivers/gogrid.py", "focal_class": null, "focal_method": "create_balancer", "tests": "import unittest\n\nclass Test_create_balancer(unittest.TestCase):\n def test_create_balancer(self):\n balancer = self.driver.create_balancer(name='test2', port=80, protocol='http', algorithm=Algorithm.ROUND_ROBIN, members=(Member(None, '10.1.0.10', 80), Member(None, '10.1.0.11', 80)))\n self.assertEquals(balancer.name, 'test2')\n self.assertEquals(balancer.id, '123')\n", "method_code": " def create_balancer(self, name, members, protocol='http', port=80, algorithm=DEFAULT_ALGORITHM):\n balancer = self.ex_create_balancer_nowait(name, members, protocol, port, algorithm)\n timeout = 60 * 20\n waittime = 0\n interval = 2 * 15\n if balancer.id is not None:\n return balancer\n else:\n while waittime < timeout:\n balancers = self.list_balancers()\n for i in balancers:\n if i.name == balancer.name and i.id is not None:\n return i\n waittime += interval\n time.sleep(interval)\n raise Exception('Failed to get id')\n ", "context": "class GoGridLBDriver(BaseGoGridDriverDriver):\n def create_balancer(self, name, members, protocol='http', port=80, algorithm=DEFAULT_ALGORITHM): ...\n def __init__(self, *args, **kwargs): ...\n def list_protocols(self): ...\n def list_balancers(self): ...\n def ex_create_balancer_nowait(self, name, members, protocol='http', port=80, algorithm=DEFAULT_ALGORITHM): ...\n def destroy_balancer(self, balancer): ...\n def get_balancer(self, **kwargs): ...\n def balancer_attach_member(self, balancer, member): ...\n def balancer_detach_member(self, balancer, member): ...\n def balancer_list_members(self, balancer): ...\n def _update_balancer(self, params): ...\n def _members_to_params(self, members): ...\n def _to_balancers(self, object): ...\n def _to_balancer(self, el): ...\n def _to_members(self, object, balancer=None): ...\n def _to_member(self, el, balancer=None): ...\n\n connectionCls = GoGridLBConnection\n api_name = 'gogrid_lb'\n name = 'GoGrid LB'\n website = 'http://www.gogrid.com/'\n LB_STATE_MAP = {'On': State.RUNNING, 'Unknown': State.UNKNOWN}\n _VALUE_TO_ALGORITHM_MAP = {'round robin': Algorithm.ROUND_ROBIN, 'least connect': Algorithm.LEAST_CONNECTIONS}\n _ALGORITHM_TO_VALUE_MAP = reverse_dict(_VALUE_TO_ALGORITHM_MAP)\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_balancer", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000860.py"} {"focal_file": "libcloud/loadbalancer/drivers/gogrid.py", "focal_class": null, "focal_method": "destroy_balancer", "tests": "import unittest\n\nclass Test_destroy_balancer(unittest.TestCase):\n def test_destroy_balancer(self):\n balancer = self.driver.list_balancers()[0]\n ret1 = self.driver.destroy_balancer(balancer)\n ret2 = balancer.destroy()\n self.assertTrue(ret1)\n self.assertTrue(ret2)\n", "method_code": " def destroy_balancer(self, balancer):\n try:\n resp = self.connection.request('/api/grid/loadbalancer/delete', method='POST', params={'id': balancer.id})\n except Exception:\n e = sys.exc_info()[1]\n if 'Update request for LoadBalancer' in str(e):\n raise LibcloudLBImmutableError('Cannot delete immutable object', GoGridLBDriver)\n else:\n raise\n return resp.status == 200\n ", "context": "class GoGridLBDriver(BaseGoGridDriverDriver):\n def destroy_balancer(self, balancer): ...\n def __init__(self, *args, **kwargs): ...\n def list_protocols(self): ...\n def list_balancers(self): ...\n def ex_create_balancer_nowait(self, name, members, protocol='http', port=80, algorithm=DEFAULT_ALGORITHM): ...\n def create_balancer(self, name, members, protocol='http', port=80, algorithm=DEFAULT_ALGORITHM): ...\n def get_balancer(self, **kwargs): ...\n def balancer_attach_member(self, balancer, member): ...\n def balancer_detach_member(self, balancer, member): ...\n def balancer_list_members(self, balancer): ...\n def _update_balancer(self, params): ...\n def _members_to_params(self, members): ...\n def _to_balancers(self, object): ...\n def _to_balancer(self, el): ...\n def _to_members(self, object, balancer=None): ...\n def _to_member(self, el, balancer=None): ...\n\n connectionCls = GoGridLBConnection\n api_name = 'gogrid_lb'\n name = 'GoGrid LB'\n website = 'http://www.gogrid.com/'\n LB_STATE_MAP = {'On': State.RUNNING, 'Unknown': State.UNKNOWN}\n _VALUE_TO_ALGORITHM_MAP = {'round robin': Algorithm.ROUND_ROBIN, 'least connect': Algorithm.LEAST_CONNECTIONS}\n _ALGORITHM_TO_VALUE_MAP = reverse_dict(_VALUE_TO_ALGORITHM_MAP)\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_destroy_balancer", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000861.py"} {"focal_file": "libcloud/loadbalancer/drivers/gogrid.py", "focal_class": null, "focal_method": "get_balancer", "tests": "import unittest\n\nclass Test_get_balancer(unittest.TestCase):\n def test_get_balancer(self):\n balancer = self.driver.get_balancer(balancer_id='23530')\n self.assertEquals(balancer.name, 'test2')\n self.assertEquals(balancer.id, '23530')\n", "method_code": " def get_balancer(self, **kwargs):\n params = {}\n try:\n params['name'] = kwargs['ex_balancer_name']\n except KeyError:\n balancer_id = kwargs['balancer_id']\n params['id'] = balancer_id\n resp = self.connection.request('/api/grid/loadbalancer/get', params=params)\n return self._to_balancers(resp.object)[0]\n ", "context": "class GoGridLBDriver(BaseGoGridDriverDriver):\n def get_balancer(self, **kwargs): ...\n def __init__(self, *args, **kwargs): ...\n def list_protocols(self): ...\n def list_balancers(self): ...\n def ex_create_balancer_nowait(self, name, members, protocol='http', port=80, algorithm=DEFAULT_ALGORITHM): ...\n def create_balancer(self, name, members, protocol='http', port=80, algorithm=DEFAULT_ALGORITHM): ...\n def destroy_balancer(self, balancer): ...\n def balancer_attach_member(self, balancer, member): ...\n def balancer_detach_member(self, balancer, member): ...\n def balancer_list_members(self, balancer): ...\n def _update_balancer(self, params): ...\n def _members_to_params(self, members): ...\n def _to_balancers(self, object): ...\n def _to_balancer(self, el): ...\n def _to_members(self, object, balancer=None): ...\n def _to_member(self, el, balancer=None): ...\n\n connectionCls = GoGridLBConnection\n api_name = 'gogrid_lb'\n name = 'GoGrid LB'\n website = 'http://www.gogrid.com/'\n LB_STATE_MAP = {'On': State.RUNNING, 'Unknown': State.UNKNOWN}\n _VALUE_TO_ALGORITHM_MAP = {'round robin': Algorithm.ROUND_ROBIN, 'least connect': Algorithm.LEAST_CONNECTIONS}\n _ALGORITHM_TO_VALUE_MAP = reverse_dict(_VALUE_TO_ALGORITHM_MAP)\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_get_balancer", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000862.py"} {"focal_file": "libcloud/storage/drivers/atmos.py", "focal_class": null, "focal_method": "get_container", "tests": "import unittest\n\nclass Test_get_container(unittest.TestCase):\n def test_get_container(self):\n container = self.driver.get_container(container_name='test_container')\n self.assertEqual(container.name, 'test_container')\n self.assertEqual(container.extra['object_id'], 'b21cb59a2ba339d1afdd4810010b0a5aba2ab6b9')\n\n def test_get_container_escaped(self):\n container = self.driver.get_container(container_name='test & container')\n self.assertEqual(container.name, 'test & container')\n self.assertEqual(container.extra['object_id'], 'b21cb59a2ba339d1afdd4810010b0a5aba2ab6b9')\n\n def test_get_container_not_found(self):\n try:\n self.driver.get_container(container_name='not_found')\n except ContainerDoesNotExistError:\n pass\n else:\n self.fail('Exception was not thrown')\n", "method_code": " def get_container(self, container_name):\n path = self._namespace_path(container_name) + '/?metadata/system'\n try:\n result = self.connection.request(path)\n except AtmosError:\n e = sys.exc_info()[1]\n if e.code != 1003:\n raise\n raise ContainerDoesNotExistError(e, self, container_name)\n meta = self._emc_meta(result)\n extra = {'object_id': meta['objectid']}\n return Container(container_name, extra, self)\n ", "context": "class AtmosDriver(StorageDriver):\n def get_container(self, container_name): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None): ...\n def iterate_containers(self): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def get_object(self, container_name, object_name): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def delete_object(self, obj): ...\n def enable_object_cdn(self, obj): ...\n def get_object_cdn_url(self, obj, expiry=None, use_object=False): ...\n def _cdn_signature(self, path, params, expiry): ...\n def _list_objects(self, tree, object_type=None): ...\n def _clean_object_name(self, name): ...\n def _namespace_path(self, path): ...\n def _object_path(self, object_id): ...\n def _emc_tag(tag): ...\n def _emc_meta(self, response): ...\n def iterate_container_objects(self, container): ...\n\n connectionCls = AtmosConnection\n host = None\n path = None\n api_name = 'atmos'\n supports_chunked_encoding = True\n website = 'http://atmosonline.com/'\n name = 'atmos'\n DEFAULT_CDN_TTL = 60 * 60 * 24 * 7\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_get_container", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000863.py"} {"focal_file": "libcloud/storage/drivers/atmos.py", "focal_class": null, "focal_method": "create_container", "tests": "import unittest\n\nclass Test_create_container(unittest.TestCase):\n def test_create_container_success(self):\n container = self.driver.create_container(container_name='test_create_container')\n self.assertTrue(isinstance(container, Container))\n self.assertEqual(container.name, 'test_create_container')\n self.assertEqual(container.extra['object_id'], '31a27b593629a3fe59f887fd973fd953e80062ce')\n\n def test_create_container_already_exists(self):\n AtmosMockHttp.type = 'ALREADY_EXISTS'\n try:\n self.driver.create_container(container_name='test_create_container')\n except ContainerAlreadyExistsError:\n pass\n else:\n self.fail('Container already exists but an exception was not thrown')\n", "method_code": " def create_container(self, container_name):\n path = self._namespace_path(container_name) + '/'\n try:\n self.connection.request(path, method='POST')\n except AtmosError:\n e = sys.exc_info()[1]\n if e.code != 1016:\n raise\n raise ContainerAlreadyExistsError(e, self, container_name)\n return self.get_container(container_name)\n ", "context": "class AtmosDriver(StorageDriver):\n def create_container(self, container_name): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None): ...\n def iterate_containers(self): ...\n def get_container(self, container_name): ...\n def delete_container(self, container): ...\n def get_object(self, container_name, object_name): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def delete_object(self, obj): ...\n def enable_object_cdn(self, obj): ...\n def get_object_cdn_url(self, obj, expiry=None, use_object=False): ...\n def _cdn_signature(self, path, params, expiry): ...\n def _list_objects(self, tree, object_type=None): ...\n def _clean_object_name(self, name): ...\n def _namespace_path(self, path): ...\n def _object_path(self, object_id): ...\n def _emc_tag(tag): ...\n def _emc_meta(self, response): ...\n def iterate_container_objects(self, container): ...\n\n connectionCls = AtmosConnection\n host = None\n path = None\n api_name = 'atmos'\n supports_chunked_encoding = True\n website = 'http://atmosonline.com/'\n name = 'atmos'\n DEFAULT_CDN_TTL = 60 * 60 * 24 * 7\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_container_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000864.py"} {"focal_file": "libcloud/storage/drivers/atmos.py", "focal_class": null, "focal_method": "delete_container", "tests": "import unittest\n\nclass Test_delete_container(unittest.TestCase):\n def test_delete_container_success(self):\n container = Container(name='foo_bar_container', extra={}, driver=self)\n result = self.driver.delete_container(container=container)\n self.assertTrue(result)\n\n def test_delete_container_not_found(self):\n AtmosMockHttp.type = 'NOT_FOUND'\n container = Container(name='foo_bar_container', extra={}, driver=self)\n try:\n self.driver.delete_container(container=container)\n except ContainerDoesNotExistError:\n pass\n else:\n self.fail('Container does not exist but an exception was not thrown')\n\n def test_delete_container_not_empty(self):\n AtmosMockHttp.type = 'NOT_EMPTY'\n container = Container(name='foo_bar_container', extra={}, driver=self)\n try:\n self.driver.delete_container(container=container)\n except ContainerIsNotEmptyError:\n pass\n else:\n self.fail('Container is not empty but an exception was not thrown')\n", "method_code": " def delete_container(self, container):\n try:\n self.connection.request(self._namespace_path(container.name) + '/', method='DELETE')\n except AtmosError:\n e = sys.exc_info()[1]\n if e.code == 1003:\n raise ContainerDoesNotExistError(e, self, container.name)\n elif e.code == 1023:\n raise ContainerIsNotEmptyError(e, self, container.name)\n return True\n ", "context": "class AtmosDriver(StorageDriver):\n def delete_container(self, container): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None): ...\n def iterate_containers(self): ...\n def get_container(self, container_name): ...\n def create_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def delete_object(self, obj): ...\n def enable_object_cdn(self, obj): ...\n def get_object_cdn_url(self, obj, expiry=None, use_object=False): ...\n def _cdn_signature(self, path, params, expiry): ...\n def _list_objects(self, tree, object_type=None): ...\n def _clean_object_name(self, name): ...\n def _namespace_path(self, path): ...\n def _object_path(self, object_id): ...\n def _emc_tag(tag): ...\n def _emc_meta(self, response): ...\n def iterate_container_objects(self, container): ...\n\n connectionCls = AtmosConnection\n host = None\n path = None\n api_name = 'atmos'\n supports_chunked_encoding = True\n website = 'http://atmosonline.com/'\n name = 'atmos'\n DEFAULT_CDN_TTL = 60 * 60 * 24 * 7\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_delete_container_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000865.py"} {"focal_file": "libcloud/storage/drivers/atmos.py", "focal_class": null, "focal_method": "delete_object", "tests": "import unittest\n\nclass Test_delete_object(unittest.TestCase):\n def test_delete_object_success(self):\n container = Container(name='foo_bar_container', extra={}, driver=self.driver)\n obj = Object(name='foo_bar_object', size=1000, hash=None, extra={}, container=container, meta_data=None, driver=self.driver)\n status = self.driver.delete_object(obj=obj)\n self.assertTrue(status)\n\n def test_delete_object_not_found(self):\n AtmosMockHttp.type = 'NOT_FOUND'\n container = Container(name='foo_bar_container', extra={}, driver=self.driver)\n obj = Object(name='foo_bar_object', size=1000, hash=None, extra={}, container=container, meta_data=None, driver=self.driver)\n try:\n self.driver.delete_object(obj=obj)\n except ObjectDoesNotExistError:\n pass\n else:\n self.fail('Object does not exist but an exception was not thrown')\n", "method_code": " def delete_object(self, obj):\n path = self._namespace_path(obj.container.name) + '/' + self._clean_object_name(obj.name)\n try:\n self.connection.request(path, method='DELETE')\n except AtmosError:\n e = sys.exc_info()[1]\n if e.code != 1003:\n raise\n raise ObjectDoesNotExistError(e, self, obj.name)\n return True\n ", "context": "class AtmosDriver(StorageDriver):\n def delete_object(self, obj): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None): ...\n def iterate_containers(self): ...\n def get_container(self, container_name): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def get_object(self, container_name, object_name): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def enable_object_cdn(self, obj): ...\n def get_object_cdn_url(self, obj, expiry=None, use_object=False): ...\n def _cdn_signature(self, path, params, expiry): ...\n def _list_objects(self, tree, object_type=None): ...\n def _clean_object_name(self, name): ...\n def _namespace_path(self, path): ...\n def _object_path(self, object_id): ...\n def _emc_tag(tag): ...\n def _emc_meta(self, response): ...\n def iterate_container_objects(self, container): ...\n\n connectionCls = AtmosConnection\n host = None\n path = None\n api_name = 'atmos'\n supports_chunked_encoding = True\n website = 'http://atmosonline.com/'\n name = 'atmos'\n DEFAULT_CDN_TTL = 60 * 60 * 24 * 7\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_delete_object_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000866.py"} {"focal_file": "libcloud/storage/drivers/atmos.py", "focal_class": null, "focal_method": "download_object", "tests": "import unittest\n\nclass Test_download_object(unittest.TestCase):\n def test_download_object_success(self):\n container = Container(name='foo_bar_container', extra={}, driver=self.driver)\n obj = Object(name='foo_bar_object', size=1000, hash=None, extra={}, container=container, meta_data=None, driver=self.driver)\n destination_path = os.path.abspath(__file__) + '.temp'\n result = self.driver.download_object(obj=obj, destination_path=destination_path, overwrite_existing=False, delete_on_failure=True)\n self.assertTrue(result)\n\n def test_download_object_escaped_success(self):\n container = Container(name='foo & bar_container', extra={}, driver=self.driver)\n obj = Object(name='foo & bar_object', size=1000, hash=None, extra={}, container=container, meta_data=None, driver=self.driver)\n destination_path = os.path.abspath(__file__) + '.temp'\n result = self.driver.download_object(obj=obj, destination_path=destination_path, overwrite_existing=False, delete_on_failure=True)\n self.assertTrue(result)\n", "method_code": " def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True):\n path = self._namespace_path(obj.container.name + '/' + obj.name)\n response = self.connection.request(path, method='GET', raw=True)\n return self._get_object(obj=obj, callback=self._save_object, response=response, callback_kwargs={'obj': obj, 'response': response.response, 'destination_path': destination_path, 'overwrite_existing': overwrite_existing, 'delete_on_failure': delete_on_failure}, success_status_code=httplib.OK)\n ", "context": "class AtmosDriver(StorageDriver):\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None): ...\n def iterate_containers(self): ...\n def get_container(self, container_name): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def get_object(self, container_name, object_name): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def delete_object(self, obj): ...\n def enable_object_cdn(self, obj): ...\n def get_object_cdn_url(self, obj, expiry=None, use_object=False): ...\n def _cdn_signature(self, path, params, expiry): ...\n def _list_objects(self, tree, object_type=None): ...\n def _clean_object_name(self, name): ...\n def _namespace_path(self, path): ...\n def _object_path(self, object_id): ...\n def _emc_tag(tag): ...\n def _emc_meta(self, response): ...\n def iterate_container_objects(self, container): ...\n\n connectionCls = AtmosConnection\n host = None\n path = None\n api_name = 'atmos'\n supports_chunked_encoding = True\n website = 'http://atmosonline.com/'\n name = 'atmos'\n DEFAULT_CDN_TTL = 60 * 60 * 24 * 7\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_download_object_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000867.py"} {"focal_file": "libcloud/storage/drivers/atmos.py", "focal_class": null, "focal_method": "download_object_as_stream", "tests": "import unittest\n\nclass Test_download_object_as_stream(unittest.TestCase):\n def test_download_object_as_stream(self):\n container = Container(name='foo_bar_container', extra={}, driver=self.driver)\n obj = Object(name='foo_bar_object', size=1000, hash=None, extra={}, container=container, meta_data=None, driver=self.driver)\n stream = self.driver.download_object_as_stream(obj=obj, chunk_size=None)\n self.assertTrue(hasattr(stream, '__iter__'))\n\n def test_download_object_as_stream_escaped(self):\n container = Container(name='foo & bar_container', extra={}, driver=self.driver)\n obj = Object(name='foo & bar_object', size=1000, hash=None, extra={}, container=container, meta_data=None, driver=self.driver)\n stream = self.driver.download_object_as_stream(obj=obj, chunk_size=None)\n self.assertTrue(hasattr(stream, '__iter__'))\n", "method_code": " def download_object_as_stream(self, obj, chunk_size=None):\n path = self._namespace_path(obj.container.name + '/' + obj.name)\n response = self.connection.request(path, method='GET', raw=True)\n return self._get_object(obj=obj, callback=read_in_chunks, response=response, callback_kwargs={'iterator': response.response, 'chunk_size': chunk_size}, success_status_code=httplib.OK)\n ", "context": "class AtmosDriver(StorageDriver):\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None): ...\n def iterate_containers(self): ...\n def get_container(self, container_name): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def get_object(self, container_name, object_name): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def delete_object(self, obj): ...\n def enable_object_cdn(self, obj): ...\n def get_object_cdn_url(self, obj, expiry=None, use_object=False): ...\n def _cdn_signature(self, path, params, expiry): ...\n def _list_objects(self, tree, object_type=None): ...\n def _clean_object_name(self, name): ...\n def _namespace_path(self, path): ...\n def _object_path(self, object_id): ...\n def _emc_tag(tag): ...\n def _emc_meta(self, response): ...\n def iterate_container_objects(self, container): ...\n\n connectionCls = AtmosConnection\n host = None\n path = None\n api_name = 'atmos'\n supports_chunked_encoding = True\n website = 'http://atmosonline.com/'\n name = 'atmos'\n DEFAULT_CDN_TTL = 60 * 60 * 24 * 7\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_download_object_as_stream", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/storage/drivers/atmos.py", "focal_class": null, "focal_method": "upload_object", "tests": "import unittest\n\nclass Test_upload_object(unittest.TestCase):\n def test_upload_object_success(self):\n\n def upload_file(self, response, file_path, chunked=False, calculate_hash=True):\n return (True, 'hash343hhash89h932439jsaa89', 1000)\n old_func = AtmosDriver._upload_file\n AtmosDriver._upload_file = upload_file\n path = os.path.abspath(__file__)\n container = Container(name='fbc', extra={}, driver=self)\n object_name = 'ftu'\n extra = {'meta_data': {'some-value': 'foobar'}}\n obj = self.driver.upload_object(file_path=path, container=container, extra=extra, object_name=object_name)\n self.assertEqual(obj.name, 'ftu')\n self.assertEqual(obj.size, 1000)\n self.assertTrue('some-value' in obj.meta_data)\n AtmosDriver._upload_file = old_func\n\n def test_upload_object_error(self):\n\n def dummy_content_type(name):\n return ('application/zip', None)\n\n def send(instance):\n raise Exception('')\n old_func1 = libcloud.utils.files.guess_file_mime_type\n libcloud.utils.files.guess_file_mime_type = dummy_content_type\n old_func2 = AtmosMockHttp.send\n AtmosMockHttp.send = send\n file_path = os.path.abspath(__file__)\n container = Container(name='fbc', extra={}, driver=self)\n object_name = 'ftu'\n try:\n self.driver.upload_object(file_path=file_path, container=container, object_name=object_name)\n except LibcloudError:\n pass\n else:\n self.fail('Timeout while uploading but an exception was not thrown')\n finally:\n libcloud.utils.files.guess_file_mime_type = old_func1\n AtmosMockHttp.send = old_func2\n", "method_code": " def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True):\n upload_func = self._upload_file\n upload_func_kwargs = {'file_path': file_path}\n method = 'PUT'\n extra = extra or {}\n object_name_cleaned = self._clean_object_name(object_name)\n request_path = self._namespace_path(container.name) + '/' + object_name_cleaned\n content_type = extra.get('content_type', None)\n try:\n self.connection.request(request_path + '?metadata/system')\n except AtmosError:\n e = sys.exc_info()[1]\n if e.code != 1003:\n raise\n method = 'POST'\n result_dict = self._upload_object(object_name=object_name, content_type=content_type, upload_func=upload_func, upload_func_kwargs=upload_func_kwargs, request_path=request_path, request_method=method, headers={}, file_path=file_path)\n bytes_transferred = result_dict['bytes_transferred']\n if extra is None:\n meta_data = {}\n else:\n meta_data = extra.get('meta_data', {})\n meta_data['md5'] = result_dict['data_hash']\n user_meta = ', '.join([k + '=' + str(v) for k, v in list(meta_data.items())])\n self.connection.request(request_path + '?metadata/user', method='POST', headers={'x-emc-meta': user_meta})\n result = self.connection.request(request_path + '?metadata/system')\n meta = self._emc_meta(result)\n del meta_data['md5']\n extra = {'object_id': meta['objectid'], 'meta_data': meta_data}\n return Object(object_name, bytes_transferred, result_dict['data_hash'], extra, meta_data, container, self)\n ", "context": "class AtmosDriver(StorageDriver):\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None): ...\n def iterate_containers(self): ...\n def get_container(self, container_name): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def get_object(self, container_name, object_name): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def delete_object(self, obj): ...\n def enable_object_cdn(self, obj): ...\n def get_object_cdn_url(self, obj, expiry=None, use_object=False): ...\n def _cdn_signature(self, path, params, expiry): ...\n def _list_objects(self, tree, object_type=None): ...\n def _clean_object_name(self, name): ...\n def _namespace_path(self, path): ...\n def _object_path(self, object_id): ...\n def _emc_tag(tag): ...\n def _emc_meta(self, response): ...\n def iterate_container_objects(self, container): ...\n\n connectionCls = AtmosConnection\n host = None\n path = None\n api_name = 'atmos'\n supports_chunked_encoding = True\n website = 'http://atmosonline.com/'\n name = 'atmos'\n DEFAULT_CDN_TTL = 60 * 60 * 24 * 7\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_upload_object_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1], "pynose_source_file": "test_000869.py"} {"focal_file": "libcloud/storage/drivers/atmos.py", "focal_class": null, "focal_method": "upload_object_via_stream", "tests": "import unittest\n\nclass Test_upload_object_via_stream(unittest.TestCase):\n def test_upload_object_via_stream_new_object(self):\n\n def dummy_content_type(name):\n return ('application/zip', None)\n old_func = libcloud.storage.drivers.atmos.guess_file_mime_type\n libcloud.storage.drivers.atmos.guess_file_mime_type = dummy_content_type\n container = Container(name='fbc', extra={}, driver=self)\n object_name = 'ftsdn'\n iterator = DummyIterator(data=['2', '3', '5'])\n try:\n self.driver.upload_object_via_stream(container=container, object_name=object_name, iterator=iterator)\n finally:\n libcloud.storage.drivers.atmos.guess_file_mime_type = old_func\n\n def test_upload_object_via_stream_existing_object(self):\n\n def dummy_content_type(name):\n return ('application/zip', None)\n old_func = libcloud.storage.drivers.atmos.guess_file_mime_type\n libcloud.storage.drivers.atmos.guess_file_mime_type = dummy_content_type\n container = Container(name='fbc', extra={}, driver=self)\n object_name = 'ftsde'\n iterator = DummyIterator(data=['2', '3', '5'])\n try:\n self.driver.upload_object_via_stream(container=container, object_name=object_name, iterator=iterator)\n finally:\n libcloud.storage.drivers.atmos.guess_file_mime_type = old_func\n\n def test_upload_object_via_stream_no_content_type(self):\n\n def no_content_type(name):\n return (None, None)\n old_func = libcloud.storage.drivers.atmos.guess_file_mime_type\n libcloud.storage.drivers.atmos.guess_file_mime_type = no_content_type\n container = Container(name='fbc', extra={}, driver=self)\n object_name = 'ftsdct'\n iterator = DummyIterator(data=['2', '3', '5'])\n try:\n self.driver.upload_object_via_stream(container=container, object_name=object_name, iterator=iterator)\n except AttributeError:\n pass\n else:\n self.fail('File content type not provided but an exception was not thrown')\n finally:\n libcloud.storage.drivers.atmos.guess_file_mime_type = old_func\n", "method_code": " def upload_object_via_stream(self, iterator, container, object_name, extra=None):\n if isinstance(iterator, file):\n iterator = iter(iterator)\n data_hash = hashlib.md5()\n generator = read_in_chunks(iterator, CHUNK_SIZE, True)\n bytes_transferred = 0\n try:\n chunk = next(generator)\n except StopIteration:\n chunk = ''\n path = self._namespace_path(container.name + '/' + object_name)\n method = 'PUT'\n if extra is not None:\n content_type = extra.get('content_type', None)\n else:\n content_type = None\n if not content_type:\n content_type, _ = guess_file_mime_type(object_name)\n if not content_type:\n raise AttributeError('File content-type could not be guessed and' + ' no content_type value provided')\n try:\n self.connection.request(path + '?metadata/system')\n except AtmosError:\n e = sys.exc_info()[1]\n if e.code != 1003:\n raise\n method = 'POST'\n while True:\n end = bytes_transferred + len(chunk) - 1\n data_hash.update(b(chunk))\n headers = {'x-emc-meta': 'md5=' + data_hash.hexdigest(), 'Content-Type': content_type}\n if len(chunk) > 0 and bytes_transferred > 0:\n headers['Range'] = 'Bytes=%d-%d' % (bytes_transferred, end)\n method = 'PUT'\n result = self.connection.request(path, method=method, data=chunk, headers=headers)\n bytes_transferred += len(chunk)\n try:\n chunk = next(generator)\n except StopIteration:\n break\n if len(chunk) == 0:\n break\n data_hash = data_hash.hexdigest()\n if extra is None:\n meta_data = {}\n else:\n meta_data = extra.get('meta_data', {})\n meta_data['md5'] = data_hash\n user_meta = ', '.join([k + '=' + str(v) for k, v in list(meta_data.items())])\n self.connection.request(path + '?metadata/user', method='POST', headers={'x-emc-meta': user_meta})\n result = self.connection.request(path + '?metadata/system')\n meta = self._emc_meta(result)\n extra = {'object_id': meta['objectid'], 'meta_data': meta_data}\n return Object(object_name, bytes_transferred, data_hash, extra, meta_data, container, self)\n ", "context": "class AtmosDriver(StorageDriver):\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None): ...\n def iterate_containers(self): ...\n def get_container(self, container_name): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def get_object(self, container_name, object_name): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def delete_object(self, obj): ...\n def enable_object_cdn(self, obj): ...\n def get_object_cdn_url(self, obj, expiry=None, use_object=False): ...\n def _cdn_signature(self, path, params, expiry): ...\n def _list_objects(self, tree, object_type=None): ...\n def _clean_object_name(self, name): ...\n def _namespace_path(self, path): ...\n def _object_path(self, object_id): ...\n def _emc_tag(tag): ...\n def _emc_meta(self, response): ...\n def iterate_container_objects(self, container): ...\n\n connectionCls = AtmosConnection\n host = None\n path = None\n api_name = 'atmos'\n supports_chunked_encoding = True\n website = 'http://atmosonline.com/'\n name = 'atmos'\n DEFAULT_CDN_TTL = 60 * 60 * 24 * 7\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_upload_object_via_stream_new_object", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000870.py"} {"focal_file": "libcloud/storage/drivers/atmos.py", "focal_class": "AtmosConnection", "focal_method": "_calculate_signature", "tests": "import unittest\n\nclass Test_AtmosConnection_calculate_signature(unittest.TestCase):\n def test_signature_algorithm(self):\n test_uid = 'fredsmagicuid'\n test_key = base64.b64encode(b('ssssshhhhhmysecretkey'))\n test_date = 'Mon, 04 Jul 2011 07:39:19 GMT'\n test_values = [('GET', '/rest/namespace/foo', '', {}, 'WfSASIA25TuqO2n0aO9k/dtg6S0='), ('GET', '/rest/namespace/foo%20%26%20bar', '', {}, 'vmlqXqcInxxoP4YX5mR09BonjX4='), ('POST', '/rest/namespace/foo', '', {}, 'oYKdsF+1DOuUT7iX5CJCDym2EQk='), ('PUT', '/rest/namespace/foo', '', {}, 'JleF9dpSWhaT3B2swZI3s41qqs4='), ('DELETE', '/rest/namespace/foo', '', {}, '2IX+Bd5XZF5YY+g4P59qXV1uLpo='), ('GET', '/rest/namespace/foo?metata/system', '', {}, 'zuHDEAgKM1winGnWn3WBsqnz4ks='), ('POST', '/rest/namespace/foo?metadata/user', '', {'x-emc-meta': 'fakemeta=fake, othermeta=faketoo'}, '7sLx1nxPIRAtocfv02jz9h1BjbU=')]\n\n class FakeDriver(object):\n path = ''\n for method, action, api_path, headers, expected in test_values:\n c = AtmosConnection(test_uid, test_key)\n c.method = method\n c.action = action\n d = FakeDriver()\n d.path = api_path\n c.driver = d\n headers = c.add_default_headers(headers)\n headers['Date'] = headers['x-emc-date'] = test_date\n self.assertEqual(c._calculate_signature({}, headers), b(expected).decode('utf-8'))\n", "method_code": " def _calculate_signature(self, params, headers):\n pathstring = urlunquote(self.action)\n if pathstring.startswith(self.driver.path):\n pathstring = pathstring[len(self.driver.path):]\n if params:\n if type(params) is dict:\n params = list(params.items())\n pathstring += '?' + urlencode(params)\n pathstring = pathstring.lower()\n xhdrs = [(k, v) for k, v in list(headers.items()) if k.startswith('x-emc-')]\n xhdrs.sort(key=lambda x: x[0])\n signature = [self.method, headers.get('Content-Type', ''), headers.get('Range', ''), headers.get('Date', ''), pathstring]\n signature.extend([k + ':' + collapse(v) for k, v in xhdrs])\n signature = '\\n'.join(signature)\n key = base64.b64decode(self.key)\n signature = hmac.new(b(key), b(signature), hashlib.sha1).digest()\n return base64.b64encode(b(signature)).decode('utf-8')\n ", "context": "class AtmosConnection(ConnectionUserAndKey):\n def _calculate_signature(self, params, headers): ...\n def add_default_headers(self, headers): ...\n def pre_connect_hook(self, params, headers): ...\n\n responseCls = AtmosResponse\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_signature_algorithm", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000871.py"} {"focal_file": "libcloud/storage/drivers/azure_blobs.py", "focal_class": null, "focal_method": "get_container", "tests": "import unittest\n\nclass Test_get_container(unittest.TestCase):\n def test_get_container_success(self):\n self.mock_response_klass.type = None\n container = self.driver.get_container(container_name='test_container200')\n self.assertTrue(container.name, 'test_container200')\n self.assertTrue(container.extra['etag'], '0x8CFB877BB56A6FB')\n self.assertTrue(container.extra['last_modified'], 'Fri, 04 Jan 2013 09:48:06 GMT')\n self.assertTrue(container.extra['lease']['status'], 'unlocked')\n self.assertTrue(container.extra['lease']['state'], 'available')\n self.assertTrue(container.extra['meta_data']['meta1'], 'value1')\n", "method_code": " def get_container(self, container_name):\n \"\"\"\n @inherits: L{StorageDriver.get_container}\n \"\"\"\n params = {'restype': 'container'}\n container_path = '/%s' % container_name\n response = self.connection.request(container_path, params=params, method='HEAD')\n if response.status == httplib.NOT_FOUND:\n raise ContainerDoesNotExistError('Container %s does not exist' % container_name, driver=self, container_name=container_name)\n elif response.status != httplib.OK:\n raise LibcloudError('Unexpected status code: %s' % response.status, driver=self)\n return self._response_to_container(container_name, response)\n ", "context": "class AzureBlobsStorageDriver(StorageDriver):\n def get_container(self, container_name): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None, **kwargs): ...\n def _xml_to_container(self, node): ...\n def _response_to_container(self, container_name, response): ...\n def _xml_to_object(self, container, blob): ...\n def _response_to_object(self, object_name, container, response): ...\n def iterate_containers(self): ...\n def iterate_container_objects(self, container): ...\n def get_object(self, container_name, object_name): ...\n def _get_container_path(self, container): ...\n def _get_object_path(self, container, object_name): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def _upload_in_chunks(self, response, data, iterator, object_path, blob_type, lease, calculate_hash=True): ...\n def _commit_blocks(self, object_path, chunks, lease): ...\n def _check_values(self, blob_type, object_size): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True, ex_blob_type=None, ex_use_lease=False): ...\n def upload_object_via_stream(self, iterator, container, object_name, verify_hash=False, extra=None, ex_use_lease=False, ex_blob_type=None, ex_page_blob_size=None): ...\n def delete_object(self, obj): ...\n def _update_metadata(self, headers, meta_data): ...\n def _prepare_upload_headers(self, object_name, object_size, extra, meta_data, blob_type): ...\n def _put_object(self, container, object_name, object_size, upload_func, upload_func_kwargs, file_path=None, extra=None, verify_hash=True, blob_type=None, use_lease=False): ...\n def ex_set_object_metadata(self, obj, meta_data): ...\n\n self.connectionCls.host = '%s.%s' % (key, self.connectionCls.host)\n\n name = 'Microsoft Azure (blobs)'\n website = 'http://windows.azure.com/'\n connectionCls = AzureBlobsConnection\n hash_type = 'md5'\n supports_chunked_encoding = False\n ex_blob_type = 'BlockBlob'\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_get_container_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 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": "libcloud/storage/drivers/azure_blobs.py", "focal_class": null, "focal_method": "create_container", "tests": "import unittest\n\nclass Test_create_container(unittest.TestCase):\n def test_create_container_invalid_name(self):\n self.mock_response_klass.type = 'INVALID_NAME'\n try:\n self.driver.create_container(container_name='new--container')\n except InvalidContainerNameError:\n pass\n else:\n self.fail('Exception was not thrown')\n\n def test_create_container_already_exists(self):\n self.mock_response_klass.type = 'ALREADY_EXISTS'\n try:\n self.driver.create_container(container_name='new-container')\n except ContainerAlreadyExistsError:\n pass\n else:\n self.fail('Exception was not thrown')\n\n def test_create_container_success(self):\n self.mock_response_klass.type = None\n name = 'new-container'\n container = self.driver.create_container(container_name=name)\n self.assertEqual(container.name, name)\n", "method_code": " def create_container(self, container_name):\n \"\"\"\n @inherits: L{StorageDriver.create_container}\n \"\"\"\n params = {'restype': 'container'}\n container_path = '/%s' % container_name\n response = self.connection.request(container_path, params=params, method='PUT')\n if response.status == httplib.CREATED:\n return self._response_to_container(container_name, response)\n elif response.status == httplib.CONFLICT:\n raise ContainerAlreadyExistsError(value='Container with this name already exists. The name must be unique among all the containers in the system', container_name=container_name, driver=self)\n elif response.status == httplib.BAD_REQUEST:\n raise InvalidContainerNameError(value='Container name contains ' + 'invalid characters.', container_name=container_name, driver=self)\n raise LibcloudError('Unexpected status code: %s' % response.status, driver=self)\n ", "context": "class AzureBlobsStorageDriver(StorageDriver):\n def create_container(self, container_name): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None, **kwargs): ...\n def _xml_to_container(self, node): ...\n def _response_to_container(self, container_name, response): ...\n def _xml_to_object(self, container, blob): ...\n def _response_to_object(self, object_name, container, response): ...\n def iterate_containers(self): ...\n def iterate_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def _get_container_path(self, container): ...\n def _get_object_path(self, container, object_name): ...\n def delete_container(self, container): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def _upload_in_chunks(self, response, data, iterator, object_path, blob_type, lease, calculate_hash=True): ...\n def _commit_blocks(self, object_path, chunks, lease): ...\n def _check_values(self, blob_type, object_size): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True, ex_blob_type=None, ex_use_lease=False): ...\n def upload_object_via_stream(self, iterator, container, object_name, verify_hash=False, extra=None, ex_use_lease=False, ex_blob_type=None, ex_page_blob_size=None): ...\n def delete_object(self, obj): ...\n def _update_metadata(self, headers, meta_data): ...\n def _prepare_upload_headers(self, object_name, object_size, extra, meta_data, blob_type): ...\n def _put_object(self, container, object_name, object_size, upload_func, upload_func_kwargs, file_path=None, extra=None, verify_hash=True, blob_type=None, use_lease=False): ...\n def ex_set_object_metadata(self, obj, meta_data): ...\n\n self.connectionCls.host = '%s.%s' % (key, self.connectionCls.host)\n\n name = 'Microsoft Azure (blobs)'\n website = 'http://windows.azure.com/'\n connectionCls = AzureBlobsConnection\n hash_type = 'md5'\n supports_chunked_encoding = False\n ex_blob_type = 'BlockBlob'\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_container_invalid_name", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000873.py"} {"focal_file": "libcloud/storage/drivers/azure_blobs.py", "focal_class": null, "focal_method": "delete_container", "tests": "import unittest\n\nclass Test_delete_container(unittest.TestCase):\n def test_delete_container_doesnt_exist(self):\n container = Container(name='new_container', extra=None, driver=self.driver)\n self.mock_response_klass.type = 'DOESNT_EXIST'\n try:\n self.driver.delete_container(container=container)\n except ContainerDoesNotExistError:\n pass\n else:\n self.fail('Exception was not thrown')\n\n def test_delete_container_not_empty(self):\n self.mock_response_klass.type = None\n AzureBlobsStorageDriver.RESPONSES_PER_REQUEST = 2\n container = Container(name='test_container', extra={}, driver=self.driver)\n try:\n self.driver.delete_container(container=container)\n except ContainerIsNotEmptyError:\n pass\n else:\n self.fail('Exception was not thrown')\n\n def test_delete_container_success(self):\n self.mock_response_klass.type = 'EMPTY'\n AzureBlobsStorageDriver.RESPONSES_PER_REQUEST = 2\n container = Container(name='test_container', extra={}, driver=self.driver)\n self.assertTrue(self.driver.delete_container(container=container))\n\n def test_delete_container_not_found(self):\n self.mock_response_klass.type = 'NOT_FOUND'\n container = Container(name='foo_bar_container', extra={}, driver=self.driver)\n try:\n self.driver.delete_container(container=container)\n except ContainerDoesNotExistError:\n pass\n else:\n self.fail('Container does not exist but an exception was not' + 'thrown')\n", "method_code": " def delete_container(self, container):\n \"\"\"\n @inherits: L{StorageDriver.delete_container}\n \"\"\"\n for obj in container.iterate_objects():\n raise ContainerIsNotEmptyError(value='Container must be empty before it can be deleted.', container_name=container.name, driver=self)\n params = {'restype': 'container'}\n container_path = self._get_container_path(container)\n response = self.connection.request(container_path, params=params, method='DELETE')\n if response.status == httplib.ACCEPTED:\n return True\n elif response.status == httplib.NOT_FOUND:\n raise ContainerDoesNotExistError(value=None, driver=self, container_name=container.name)\n return False\n ", "context": "class AzureBlobsStorageDriver(StorageDriver):\n def delete_container(self, container): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None, **kwargs): ...\n def _xml_to_container(self, node): ...\n def _response_to_container(self, container_name, response): ...\n def _xml_to_object(self, container, blob): ...\n def _response_to_object(self, object_name, container, response): ...\n def iterate_containers(self): ...\n def iterate_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def _get_container_path(self, container): ...\n def _get_object_path(self, container, object_name): ...\n def create_container(self, container_name): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def _upload_in_chunks(self, response, data, iterator, object_path, blob_type, lease, calculate_hash=True): ...\n def _commit_blocks(self, object_path, chunks, lease): ...\n def _check_values(self, blob_type, object_size): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True, ex_blob_type=None, ex_use_lease=False): ...\n def upload_object_via_stream(self, iterator, container, object_name, verify_hash=False, extra=None, ex_use_lease=False, ex_blob_type=None, ex_page_blob_size=None): ...\n def delete_object(self, obj): ...\n def _update_metadata(self, headers, meta_data): ...\n def _prepare_upload_headers(self, object_name, object_size, extra, meta_data, blob_type): ...\n def _put_object(self, container, object_name, object_size, upload_func, upload_func_kwargs, file_path=None, extra=None, verify_hash=True, blob_type=None, use_lease=False): ...\n def ex_set_object_metadata(self, obj, meta_data): ...\n\n self.connectionCls.host = '%s.%s' % (key, self.connectionCls.host)\n\n name = 'Microsoft Azure (blobs)'\n website = 'http://windows.azure.com/'\n connectionCls = AzureBlobsConnection\n hash_type = 'md5'\n supports_chunked_encoding = False\n ex_blob_type = 'BlockBlob'\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_delete_container_doesnt_exist", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000874.py"} {"focal_file": "libcloud/storage/drivers/azure_blobs.py", "focal_class": null, "focal_method": "download_object", "tests": "import unittest\n\nclass Test_download_object(unittest.TestCase):\n def test_download_object_success(self):\n container = Container(name='foo_bar_container', extra={}, driver=self.driver)\n obj = Object(name='foo_bar_object', size=1000, hash=None, extra={}, container=container, meta_data=None, driver=self.driver_type)\n destination_path = os.path.abspath(__file__) + '.temp'\n result = self.driver.download_object(obj=obj, destination_path=destination_path, overwrite_existing=False, delete_on_failure=True)\n self.assertTrue(result)\n", "method_code": " def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True):\n \"\"\"\n @inherits: L{StorageDriver.download_object}\n \"\"\"\n obj_path = self._get_object_path(obj.container, obj.name)\n response = self.connection.request(obj_path, raw=True, data=None)\n return self._get_object(obj=obj, callback=self._save_object, response=response, callback_kwargs={'obj': obj, 'response': response.response, 'destination_path': destination_path, 'overwrite_existing': overwrite_existing, 'delete_on_failure': delete_on_failure}, success_status_code=httplib.OK)\n ", "context": "class AzureBlobsStorageDriver(StorageDriver):\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None, **kwargs): ...\n def _xml_to_container(self, node): ...\n def _response_to_container(self, container_name, response): ...\n def _xml_to_object(self, container, blob): ...\n def _response_to_object(self, object_name, container, response): ...\n def iterate_containers(self): ...\n def iterate_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def _get_container_path(self, container): ...\n def _get_object_path(self, container, object_name): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def _upload_in_chunks(self, response, data, iterator, object_path, blob_type, lease, calculate_hash=True): ...\n def _commit_blocks(self, object_path, chunks, lease): ...\n def _check_values(self, blob_type, object_size): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True, ex_blob_type=None, ex_use_lease=False): ...\n def upload_object_via_stream(self, iterator, container, object_name, verify_hash=False, extra=None, ex_use_lease=False, ex_blob_type=None, ex_page_blob_size=None): ...\n def delete_object(self, obj): ...\n def _update_metadata(self, headers, meta_data): ...\n def _prepare_upload_headers(self, object_name, object_size, extra, meta_data, blob_type): ...\n def _put_object(self, container, object_name, object_size, upload_func, upload_func_kwargs, file_path=None, extra=None, verify_hash=True, blob_type=None, use_lease=False): ...\n def ex_set_object_metadata(self, obj, meta_data): ...\n\n self.connectionCls.host = '%s.%s' % (key, self.connectionCls.host)\n\n name = 'Microsoft Azure (blobs)'\n website = 'http://windows.azure.com/'\n connectionCls = AzureBlobsConnection\n hash_type = 'md5'\n supports_chunked_encoding = False\n ex_blob_type = 'BlockBlob'\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_download_object_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000875.py"} {"focal_file": "libcloud/storage/drivers/azure_blobs.py", "focal_class": null, "focal_method": "download_object_as_stream", "tests": "import unittest\n\nclass Test_download_object_as_stream(unittest.TestCase):\n def test_download_object_as_stream_success(self):\n container = Container(name='foo_bar_container', extra={}, driver=self.driver)\n obj = Object(name='foo_bar_object', size=1000, hash=None, extra={}, container=container, meta_data=None, driver=self.driver_type)\n stream = self.driver.download_object_as_stream(obj=obj, chunk_size=None)\n self.assertTrue(hasattr(stream, '__iter__'))\n", "method_code": " def download_object_as_stream(self, obj, chunk_size=None):\n \"\"\"\n @inherits: L{StorageDriver.download_object_as_stream}\n \"\"\"\n obj_path = self._get_object_path(obj.container, obj.name)\n response = self.connection.request(obj_path, raw=True, data=None)\n return self._get_object(obj=obj, callback=read_in_chunks, response=response, callback_kwargs={'iterator': response.response, 'chunk_size': chunk_size}, success_status_code=httplib.OK)\n ", "context": "class AzureBlobsStorageDriver(StorageDriver):\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None, **kwargs): ...\n def _xml_to_container(self, node): ...\n def _response_to_container(self, container_name, response): ...\n def _xml_to_object(self, container, blob): ...\n def _response_to_object(self, object_name, container, response): ...\n def iterate_containers(self): ...\n def iterate_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def _get_container_path(self, container): ...\n def _get_object_path(self, container, object_name): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def _upload_in_chunks(self, response, data, iterator, object_path, blob_type, lease, calculate_hash=True): ...\n def _commit_blocks(self, object_path, chunks, lease): ...\n def _check_values(self, blob_type, object_size): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True, ex_blob_type=None, ex_use_lease=False): ...\n def upload_object_via_stream(self, iterator, container, object_name, verify_hash=False, extra=None, ex_use_lease=False, ex_blob_type=None, ex_page_blob_size=None): ...\n def delete_object(self, obj): ...\n def _update_metadata(self, headers, meta_data): ...\n def _prepare_upload_headers(self, object_name, object_size, extra, meta_data, blob_type): ...\n def _put_object(self, container, object_name, object_size, upload_func, upload_func_kwargs, file_path=None, extra=None, verify_hash=True, blob_type=None, use_lease=False): ...\n def ex_set_object_metadata(self, obj, meta_data): ...\n\n self.connectionCls.host = '%s.%s' % (key, self.connectionCls.host)\n\n name = 'Microsoft Azure (blobs)'\n website = 'http://windows.azure.com/'\n connectionCls = AzureBlobsConnection\n hash_type = 'md5'\n supports_chunked_encoding = False\n ex_blob_type = 'BlockBlob'\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_download_object_as_stream_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000876.py"} {"focal_file": "libcloud/storage/drivers/azure_blobs.py", "focal_class": null, "focal_method": "upload_object", "tests": "import unittest\n\nclass Test_upload_object(unittest.TestCase):\n def test_upload_object_invalid_md5(self):\n self.mock_raw_response_klass.type = 'INVALID_HASH'\n container = Container(name='foo_bar_container', extra={}, driver=self.driver)\n object_name = 'foo_test_upload'\n file_path = os.path.abspath(__file__)\n try:\n self.driver.upload_object(file_path=file_path, container=container, object_name=object_name, verify_hash=True)\n except ObjectHashMismatchError:\n pass\n else:\n self.fail('Invalid hash was returned but an exception was not thrown')\n", "method_code": " def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True, ex_blob_type=None, ex_use_lease=False):\n \"\"\"\n Upload an object currently located on a disk.\n \n @inherits: L{StorageDriver.upload_object}\n \n @param ex_blob_type: Storage class\n @type ex_blob_type: C{str}\n \n @param ex_use_lease: Indicates if we must take a lease before upload\n @type ex_use_lease: C{bool}\n \"\"\"\n if ex_blob_type is None:\n ex_blob_type = self.ex_blob_type\n file_size = os.stat(file_path).st_size\n object_size = file_size\n self._check_values(ex_blob_type, file_size)\n with file(file_path, 'rb') as file_handle:\n iterator = iter(file_handle)\n if ex_blob_type == 'PageBlob' or file_size > AZURE_BLOCK_MAX_SIZE:\n if ex_blob_type == 'BlockBlob':\n object_size = None\n object_path = self._get_object_path(container, object_name)\n upload_func = self._upload_in_chunks\n upload_func_kwargs = {'iterator': iterator, 'object_path': object_path, 'blob_type': ex_blob_type, 'lease': None}\n else:\n upload_func = self._stream_data\n upload_func_kwargs = {'iterator': iterator, 'chunked': False, 'calculate_hash': verify_hash}\n return self._put_object(container=container, object_name=object_name, object_size=object_size, upload_func=upload_func, upload_func_kwargs=upload_func_kwargs, file_path=file_path, extra=extra, verify_hash=verify_hash, blob_type=ex_blob_type, use_lease=ex_use_lease)\n ", "context": "class AzureBlobsStorageDriver(StorageDriver):\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True, ex_blob_type=None, ex_use_lease=False): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None, **kwargs): ...\n def _xml_to_container(self, node): ...\n def _response_to_container(self, container_name, response): ...\n def _xml_to_object(self, container, blob): ...\n def _response_to_object(self, object_name, container, response): ...\n def iterate_containers(self): ...\n def iterate_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def _get_container_path(self, container): ...\n def _get_object_path(self, container, object_name): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def _upload_in_chunks(self, response, data, iterator, object_path, blob_type, lease, calculate_hash=True): ...\n def _commit_blocks(self, object_path, chunks, lease): ...\n def _check_values(self, blob_type, object_size): ...\n def upload_object_via_stream(self, iterator, container, object_name, verify_hash=False, extra=None, ex_use_lease=False, ex_blob_type=None, ex_page_blob_size=None): ...\n def delete_object(self, obj): ...\n def _update_metadata(self, headers, meta_data): ...\n def _prepare_upload_headers(self, object_name, object_size, extra, meta_data, blob_type): ...\n def _put_object(self, container, object_name, object_size, upload_func, upload_func_kwargs, file_path=None, extra=None, verify_hash=True, blob_type=None, use_lease=False): ...\n def ex_set_object_metadata(self, obj, meta_data): ...\n\n self.connectionCls.host = '%s.%s' % (key, self.connectionCls.host)\n\n name = 'Microsoft Azure (blobs)'\n website = 'http://windows.azure.com/'\n connectionCls = AzureBlobsConnection\n hash_type = 'md5'\n supports_chunked_encoding = False\n ex_blob_type = 'BlockBlob'\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_upload_object_invalid_md5", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000877.py"} {"focal_file": "libcloud/storage/drivers/azure_blobs.py", "focal_class": null, "focal_method": "upload_object_via_stream", "tests": "import unittest\n\nclass Test_upload_object_via_stream(unittest.TestCase):\n def test_upload_blob_object_via_stream(self):\n self.mock_response_klass.use_param = 'comp'\n container = Container(name='foo_bar_container', extra={}, driver=self.driver)\n object_name = 'foo_test_upload'\n iterator = DummyIterator(data=['2', '3', '5'])\n extra = {'content_type': 'text/plain'}\n obj = self.driver.upload_object_via_stream(container=container, object_name=object_name, iterator=iterator, extra=extra, ex_blob_type='BlockBlob')\n self.assertEqual(obj.name, object_name)\n self.assertEqual(obj.size, 3)\n self.mock_response_klass.use_param = None\n\n def test_upload_blob_object_via_stream_with_lease(self):\n self.mock_response_klass.use_param = 'comp'\n container = Container(name='foo_bar_container', extra={}, driver=self.driver)\n object_name = 'foo_test_upload'\n iterator = DummyIterator(data=['2', '3', '5'])\n extra = {'content_type': 'text/plain'}\n obj = self.driver.upload_object_via_stream(container=container, object_name=object_name, iterator=iterator, extra=extra, ex_blob_type='BlockBlob', ex_use_lease=True)\n self.assertEqual(obj.name, object_name)\n self.assertEqual(obj.size, 3)\n self.mock_response_klass.use_param = None\n\n def test_upload_page_object_via_stream(self):\n self.mock_response_klass.use_param = 'comp'\n container = Container(name='foo_bar_container', extra={}, driver=self.driver)\n object_name = 'foo_test_upload'\n blob_size = AZURE_PAGE_CHUNK_SIZE\n iterator = DummyIterator(data=['1'] * blob_size)\n extra = {'content_type': 'text/plain'}\n obj = self.driver.upload_object_via_stream(container=container, object_name=object_name, iterator=iterator, extra=extra, ex_blob_type='PageBlob', ex_page_blob_size=blob_size)\n self.assertEqual(obj.name, object_name)\n self.assertEqual(obj.size, blob_size)\n self.mock_response_klass.use_param = None\n\n def test_upload_page_object_via_stream_with_lease(self):\n self.mock_response_klass.use_param = 'comp'\n container = Container(name='foo_bar_container', extra={}, driver=self.driver)\n object_name = 'foo_test_upload'\n blob_size = AZURE_PAGE_CHUNK_SIZE\n iterator = DummyIterator(data=['1'] * blob_size)\n extra = {'content_type': 'text/plain'}\n obj = self.driver.upload_object_via_stream(container=container, object_name=object_name, iterator=iterator, extra=extra, ex_blob_type='PageBlob', ex_page_blob_size=blob_size, ex_use_lease=True)\n self.assertEqual(obj.name, object_name)\n self.assertEqual(obj.size, blob_size)\n", "method_code": " def upload_object_via_stream(self, iterator, container, object_name, verify_hash=False, extra=None, ex_use_lease=False, ex_blob_type=None, ex_page_blob_size=None):\n \"\"\"\n @inherits: L{StorageDriver.upload_object_via_stream}\n \n @param ex_blob_type: Storage class\n @type ex_blob_type: C{str}\n \n @param ex_page_blob_size: The maximum size to which the\n page blob can grow to\n @type ex_page_blob_size: C{int}\n \n @param ex_use_lease: Indicates if we must take a lease before upload\n @type ex_use_lease: C{bool}\n \"\"\"\n if ex_blob_type is None:\n ex_blob_type = self.ex_blob_type\n self._check_values(ex_blob_type, ex_page_blob_size)\n object_path = self._get_object_path(container, object_name)\n upload_func = self._upload_in_chunks\n upload_func_kwargs = {'iterator': iterator, 'object_path': object_path, 'blob_type': ex_blob_type, 'lease': None}\n return self._put_object(container=container, object_name=object_name, object_size=ex_page_blob_size, upload_func=upload_func, upload_func_kwargs=upload_func_kwargs, extra=extra, verify_hash=verify_hash, blob_type=ex_blob_type, use_lease=ex_use_lease)\n ", "context": "class AzureBlobsStorageDriver(StorageDriver):\n def upload_object_via_stream(self, iterator, container, object_name, verify_hash=False, extra=None, ex_use_lease=False, ex_blob_type=None, ex_page_blob_size=None): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None, **kwargs): ...\n def _xml_to_container(self, node): ...\n def _response_to_container(self, container_name, response): ...\n def _xml_to_object(self, container, blob): ...\n def _response_to_object(self, object_name, container, response): ...\n def iterate_containers(self): ...\n def iterate_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def _get_container_path(self, container): ...\n def _get_object_path(self, container, object_name): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def _upload_in_chunks(self, response, data, iterator, object_path, blob_type, lease, calculate_hash=True): ...\n def _commit_blocks(self, object_path, chunks, lease): ...\n def _check_values(self, blob_type, object_size): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True, ex_blob_type=None, ex_use_lease=False): ...\n def delete_object(self, obj): ...\n def _update_metadata(self, headers, meta_data): ...\n def _prepare_upload_headers(self, object_name, object_size, extra, meta_data, blob_type): ...\n def _put_object(self, container, object_name, object_size, upload_func, upload_func_kwargs, file_path=None, extra=None, verify_hash=True, blob_type=None, use_lease=False): ...\n def ex_set_object_metadata(self, obj, meta_data): ...\n\n self.connectionCls.host = '%s.%s' % (key, self.connectionCls.host)\n\n name = 'Microsoft Azure (blobs)'\n website = 'http://windows.azure.com/'\n connectionCls = AzureBlobsConnection\n hash_type = 'md5'\n supports_chunked_encoding = False\n ex_blob_type = 'BlockBlob'\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_upload_blob_object_via_stream", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000878.py"} {"focal_file": "libcloud/storage/drivers/azure_blobs.py", "focal_class": null, "focal_method": "delete_object", "tests": "import unittest\n\nclass Test_delete_object(unittest.TestCase):\n def test_delete_object_not_found(self):\n self.mock_response_klass.type = 'NOT_FOUND'\n container = Container(name='foo_bar_container', extra={}, driver=self.driver)\n obj = Object(name='foo_bar_object', size=1234, hash=None, extra=None, meta_data=None, container=container, driver=self.driver)\n try:\n self.driver.delete_object(obj=obj)\n except ObjectDoesNotExistError:\n pass\n else:\n self.fail('Exception was not thrown')\n\n def test_delete_object_success(self):\n container = Container(name='foo_bar_container', extra={}, driver=self.driver)\n obj = Object(name='foo_bar_object', size=1234, hash=None, extra=None, meta_data=None, container=container, driver=self.driver)\n result = self.driver.delete_object(obj=obj)\n self.assertTrue(result)\n", "method_code": " def delete_object(self, obj):\n \"\"\"\n @inherits: L{StorageDriver.delete_object}\n \"\"\"\n object_path = self._get_object_path(obj.container, obj.name)\n response = self.connection.request(object_path, method='DELETE')\n if response.status == httplib.ACCEPTED:\n return True\n elif response.status == httplib.NOT_FOUND:\n raise ObjectDoesNotExistError(value=None, driver=self, object_name=obj.name)\n return False\n ", "context": "class AzureBlobsStorageDriver(StorageDriver):\n def delete_object(self, obj): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None, **kwargs): ...\n def _xml_to_container(self, node): ...\n def _response_to_container(self, container_name, response): ...\n def _xml_to_object(self, container, blob): ...\n def _response_to_object(self, object_name, container, response): ...\n def iterate_containers(self): ...\n def iterate_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def _get_container_path(self, container): ...\n def _get_object_path(self, container, object_name): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def _upload_in_chunks(self, response, data, iterator, object_path, blob_type, lease, calculate_hash=True): ...\n def _commit_blocks(self, object_path, chunks, lease): ...\n def _check_values(self, blob_type, object_size): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True, ex_blob_type=None, ex_use_lease=False): ...\n def upload_object_via_stream(self, iterator, container, object_name, verify_hash=False, extra=None, ex_use_lease=False, ex_blob_type=None, ex_page_blob_size=None): ...\n def _update_metadata(self, headers, meta_data): ...\n def _prepare_upload_headers(self, object_name, object_size, extra, meta_data, blob_type): ...\n def _put_object(self, container, object_name, object_size, upload_func, upload_func_kwargs, file_path=None, extra=None, verify_hash=True, blob_type=None, use_lease=False): ...\n def ex_set_object_metadata(self, obj, meta_data): ...\n\n self.connectionCls.host = '%s.%s' % (key, self.connectionCls.host)\n\n name = 'Microsoft Azure (blobs)'\n website = 'http://windows.azure.com/'\n connectionCls = AzureBlobsConnection\n hash_type = 'md5'\n supports_chunked_encoding = False\n ex_blob_type = 'BlockBlob'\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_delete_object_not_found", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000879.py"} {"focal_file": "libcloud/storage/base.py", "focal_class": null, "focal_method": "_upload_data", "tests": "import unittest\n\nclass Test_upload_data(unittest.TestCase):\n def test__upload_data(self):\n\n def mock_send(data):\n self.send_called += 1\n response = Mock()\n response.connection.connection.send = mock_send\n data = '123456789901234567'\n success, data_hash, bytes_transferred = self.driver1._upload_data(response=response, data=data, calculate_hash=True)\n self.assertTrue(success)\n self.assertEqual(data_hash, hashlib.md5(b(data)).hexdigest())\n self.assertEqual(bytes_transferred, len(data))\n self.assertEqual(self.send_called, 1)\n", "method_code": " def _upload_data(self, response, data, calculate_hash=True):\n \"\"\"\n Upload data stored in a string.\n \n @type response: C{RawResponse}\n @param response: RawResponse object.\n \n @type data: C{str}\n @param data: Data to upload.\n \n @type calculate_hash: C{boolean}\n @param calculate_hash: True to calculate hash of the transfered data.\n (defauls to True).\n \n @rtype: C{tuple}\n @return: First item is a boolean indicator of success, second\n one is the uploaded data MD5 hash and the third one\n is the number of transferred bytes.\n \"\"\"\n bytes_transferred = 0\n data_hash = None\n if calculate_hash:\n data_hash = self._get_hash_function()\n data_hash.update(b(data))\n try:\n response.connection.connection.send(b(data))\n except Exception:\n return (False, None, bytes_transferred)\n bytes_transferred = len(data)\n if calculate_hash:\n data_hash = data_hash.hexdigest()\n return (True, data_hash, bytes_transferred)\n ", "context": "class StorageDriver(BaseDriver):\n def _upload_data(self, response, data, calculate_hash=True): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None, **kwargs): ...\n def iterate_containers(self): ...\n def list_containers(self): ...\n def iterate_container_objects(self, container): ...\n def list_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_container_cdn_url(self, container): ...\n def get_object(self, container_name, object_name): ...\n def get_object_cdn_url(self, obj): ...\n def enable_container_cdn(self, container): ...\n def enable_object_cdn(self, obj): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def delete_object(self, obj): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def _get_object(self, obj, callback, callback_kwargs, response, success_status_code=None): ...\n def _save_object(self, response, obj, destination_path, overwrite_existing=False, delete_on_failure=True, chunk_size=None): ...\n def _upload_object(self, object_name, content_type, upload_func, upload_func_kwargs, request_path, request_method='PUT', headers=None, file_path=None, iterator=None): ...\n def _stream_data(self, response, iterator, chunked=False, calculate_hash=True, chunk_size=None, data=None): ...\n def _upload_file(self, response, file_path, chunked=False, calculate_hash=True): ...\n def _get_hash_function(self): ...\n\n connectionCls = ConnectionUserAndKey\n name = None\n hash_type = 'md5'\n supports_chunked_encoding = False\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test__upload_data", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000880.py"} {"focal_file": "libcloud/storage/base.py", "focal_class": null, "focal_method": "_get_hash_function", "tests": "import unittest\n\nclass Test_get_hash_function(unittest.TestCase):\n def test__get_hash_function(self):\n self.driver1.hash_type = 'md5'\n func = self.driver1._get_hash_function()\n self.assertTrue(func)\n self.driver1.hash_type = 'sha1'\n func = self.driver1._get_hash_function()\n self.assertTrue(func)\n try:\n self.driver1.hash_type = 'invalid-hash-function'\n func = self.driver1._get_hash_function()\n except RuntimeError:\n pass\n else:\n self.fail('Invalid hash type but exception was not thrown')\n", "method_code": " def _get_hash_function(self):\n \"\"\"\n Return instantiated hash function for the hash type supported by\n the provider.\n \"\"\"\n try:\n func = getattr(hashlib, self.hash_type)()\n except AttributeError:\n raise RuntimeError('Invalid or unsupported hash type: %s' % self.hash_type)\n return func\n ", "context": "class StorageDriver(BaseDriver):\n def _get_hash_function(self): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None, **kwargs): ...\n def iterate_containers(self): ...\n def list_containers(self): ...\n def iterate_container_objects(self, container): ...\n def list_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_container_cdn_url(self, container): ...\n def get_object(self, container_name, object_name): ...\n def get_object_cdn_url(self, obj): ...\n def enable_container_cdn(self, container): ...\n def enable_object_cdn(self, obj): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def delete_object(self, obj): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def _get_object(self, obj, callback, callback_kwargs, response, success_status_code=None): ...\n def _save_object(self, response, obj, destination_path, overwrite_existing=False, delete_on_failure=True, chunk_size=None): ...\n def _upload_object(self, object_name, content_type, upload_func, upload_func_kwargs, request_path, request_method='PUT', headers=None, file_path=None, iterator=None): ...\n def _upload_data(self, response, data, calculate_hash=True): ...\n def _stream_data(self, response, iterator, chunked=False, calculate_hash=True, chunk_size=None, data=None): ...\n def _upload_file(self, response, file_path, chunked=False, calculate_hash=True): ...\n\n connectionCls = ConnectionUserAndKey\n name = None\n hash_type = 'md5'\n supports_chunked_encoding = False\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test__get_hash_function", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000881.py"} {"focal_file": "libcloud/storage/drivers/cloudfiles.py", "focal_class": null, "focal_method": "list_containers", "tests": "import unittest\n\nclass Test_list_containers(unittest.TestCase):\n def test_list_containers(self):\n CloudFilesMockHttp.type = 'EMPTY'\n containers = self.driver.list_containers()\n self.assertEqual(len(containers), 0)\n CloudFilesMockHttp.type = None\n containers = self.driver.list_containers()\n self.assertEqual(len(containers), 3)\n container = [c for c in containers if c.name == 'container2'][0]\n self.assertEqual(container.extra['object_count'], 120)\n self.assertEqual(container.extra['size'], 340084450)\n", "method_code": " def list_containers(self):\n response = self.connection.request('')\n if response.status == httplib.NO_CONTENT:\n return []\n elif response.status == httplib.OK:\n return self._to_container_list(json.loads(response.body))\n raise LibcloudError('Unexpected status code: %s' % response.status)\n ", "context": "class CloudFilesStorageDriver(StorageDriverOpenStackDriverMixin):\n def list_containers(self): ...\n def __init__(self, *args, **kwargs): ...\n def list_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def get_container_cdn_url(self, container): ...\n def get_object_cdn_url(self, obj): ...\n def enable_container_cdn(self, container, ex_ttl=None): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def delete_object(self, obj): ...\n def ex_purge_object_from_cdn(self, obj, email=None): ...\n def ex_get_meta_data(self): ...\n def ex_multipart_upload_object(self, file_path, container, object_name, chunk_size=33554432, extra=None, verify_hash=True): ...\n def ex_enable_static_website(self, container, index_file='index.html'): ...\n def ex_set_error_page(self, container, file_name='error.html'): ...\n def ex_set_account_metadata_temp_url_key(self, key): ...\n def ex_get_object_temp_url(self, obj, method='GET', timeout=60): ...\n def _upload_object_part(self, container, object_name, part_number, iterator, verify_hash=True): ...\n def _upload_object_manifest(self, container, object_name, extra=None, verify_hash=True): ...\n def _get_more(self, last_key, value_dict): ...\n def _put_object(self, container, object_name, upload_func, upload_func_kwargs, extra=None, file_path=None, iterator=None, verify_hash=True): ...\n def _encode_container_name(self, name): ...\n def _encode_object_name(self, name): ...\n def _to_container_list(self, response): ...\n def _to_object_list(self, response, container): ...\n def _headers_to_container(self, name, headers): ...\n def _headers_to_object(self, name, container, headers): ...\n def _ex_connection_class_kwargs(self): ...\n\n name = 'CloudFiles'\n website = 'http://www.rackspace.com/'\n connectionCls = CloudFilesConnection\n hash_type = 'md5'\n supports_chunked_encoding = True\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_containers", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000882.py"} {"focal_file": "libcloud/storage/drivers/cloudfiles.py", "focal_class": null, "focal_method": "list_container_objects", "tests": "import unittest\n\nclass Test_list_container_objects(unittest.TestCase):\n def test_list_container_objects(self):\n CloudFilesMockHttp.type = 'EMPTY'\n container = Container(name='test_container', extra={}, driver=self.driver)\n objects = self.driver.list_container_objects(container=container)\n self.assertEqual(len(objects), 0)\n CloudFilesMockHttp.type = None\n objects = self.driver.list_container_objects(container=container)\n self.assertEqual(len(objects), 4)\n obj = [o for o in objects if o.name == 'foo test 1'][0]\n self.assertEqual(obj.hash, '16265549b5bda64ecdaa5156de4c97cc')\n self.assertEqual(obj.size, 1160520)\n self.assertEqual(obj.container.name, 'test_container')\n\n def test_list_container_objects_iterator(self):\n CloudFilesMockHttp.type = 'ITERATOR'\n container = Container(name='test_container', extra={}, driver=self.driver)\n objects = self.driver.list_container_objects(container=container)\n self.assertEqual(len(objects), 5)\n obj = [o for o in objects if o.name == 'foo-test-1'][0]\n self.assertEqual(obj.hash, '16265549b5bda64ecdaa5156de4c97cc')\n self.assertEqual(obj.size, 1160520)\n self.assertEqual(obj.container.name, 'test_container')\n", "method_code": " def list_container_objects(self, container):\n value_dict = {'container': container}\n return LazyList(get_more=self._get_more, value_dict=value_dict)\n ", "context": "class CloudFilesStorageDriver(StorageDriverOpenStackDriverMixin):\n def list_container_objects(self, container): ...\n def __init__(self, *args, **kwargs): ...\n def list_containers(self): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def get_container_cdn_url(self, container): ...\n def get_object_cdn_url(self, obj): ...\n def enable_container_cdn(self, container, ex_ttl=None): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def delete_object(self, obj): ...\n def ex_purge_object_from_cdn(self, obj, email=None): ...\n def ex_get_meta_data(self): ...\n def ex_multipart_upload_object(self, file_path, container, object_name, chunk_size=33554432, extra=None, verify_hash=True): ...\n def ex_enable_static_website(self, container, index_file='index.html'): ...\n def ex_set_error_page(self, container, file_name='error.html'): ...\n def ex_set_account_metadata_temp_url_key(self, key): ...\n def ex_get_object_temp_url(self, obj, method='GET', timeout=60): ...\n def _upload_object_part(self, container, object_name, part_number, iterator, verify_hash=True): ...\n def _upload_object_manifest(self, container, object_name, extra=None, verify_hash=True): ...\n def _get_more(self, last_key, value_dict): ...\n def _put_object(self, container, object_name, upload_func, upload_func_kwargs, extra=None, file_path=None, iterator=None, verify_hash=True): ...\n def _encode_container_name(self, name): ...\n def _encode_object_name(self, name): ...\n def _to_container_list(self, response): ...\n def _to_object_list(self, response, container): ...\n def _headers_to_container(self, name, headers): ...\n def _headers_to_object(self, name, container, headers): ...\n def _ex_connection_class_kwargs(self): ...\n\n name = 'CloudFiles'\n website = 'http://www.rackspace.com/'\n connectionCls = CloudFilesConnection\n hash_type = 'md5'\n supports_chunked_encoding = True\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_list_container_objects", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000883.py"} {"focal_file": "libcloud/storage/drivers/cloudfiles.py", "focal_class": null, "focal_method": "get_container", "tests": "import unittest\n\nclass Test_get_container(unittest.TestCase):\n def test_get_container(self):\n container = self.driver.get_container(container_name='test_container')\n self.assertEqual(container.name, 'test_container')\n self.assertEqual(container.extra['object_count'], 800)\n self.assertEqual(container.extra['size'], 1234568)\n\n def test_get_container_not_found(self):\n try:\n self.driver.get_container(container_name='not_found')\n except ContainerDoesNotExistError:\n pass\n else:\n self.fail('Exception was not thrown')\n", "method_code": " def get_container(self, container_name):\n container_name_encoded = self._encode_container_name(container_name)\n response = self.connection.request('/%s' % container_name_encoded, method='HEAD')\n if response.status == httplib.NO_CONTENT:\n container = self._headers_to_container(container_name, response.headers)\n return container\n elif response.status == httplib.NOT_FOUND:\n raise ContainerDoesNotExistError(None, self, container_name)\n raise LibcloudError('Unexpected status code: %s' % response.status)\n ", "context": "class CloudFilesStorageDriver(StorageDriverOpenStackDriverMixin):\n def get_container(self, container_name): ...\n def __init__(self, *args, **kwargs): ...\n def list_containers(self): ...\n def list_container_objects(self, container): ...\n def get_object(self, container_name, object_name): ...\n def get_container_cdn_url(self, container): ...\n def get_object_cdn_url(self, obj): ...\n def enable_container_cdn(self, container, ex_ttl=None): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def delete_object(self, obj): ...\n def ex_purge_object_from_cdn(self, obj, email=None): ...\n def ex_get_meta_data(self): ...\n def ex_multipart_upload_object(self, file_path, container, object_name, chunk_size=33554432, extra=None, verify_hash=True): ...\n def ex_enable_static_website(self, container, index_file='index.html'): ...\n def ex_set_error_page(self, container, file_name='error.html'): ...\n def ex_set_account_metadata_temp_url_key(self, key): ...\n def ex_get_object_temp_url(self, obj, method='GET', timeout=60): ...\n def _upload_object_part(self, container, object_name, part_number, iterator, verify_hash=True): ...\n def _upload_object_manifest(self, container, object_name, extra=None, verify_hash=True): ...\n def _get_more(self, last_key, value_dict): ...\n def _put_object(self, container, object_name, upload_func, upload_func_kwargs, extra=None, file_path=None, iterator=None, verify_hash=True): ...\n def _encode_container_name(self, name): ...\n def _encode_object_name(self, name): ...\n def _to_container_list(self, response): ...\n def _to_object_list(self, response, container): ...\n def _headers_to_container(self, name, headers): ...\n def _headers_to_object(self, name, container, headers): ...\n def _ex_connection_class_kwargs(self): ...\n\n name = 'CloudFiles'\n website = 'http://www.rackspace.com/'\n connectionCls = CloudFilesConnection\n hash_type = 'md5'\n supports_chunked_encoding = True\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_get_container", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000884.py"} {"focal_file": "libcloud/storage/drivers/cloudfiles.py", "focal_class": null, "focal_method": "create_container", "tests": "import unittest\n\nclass Test_create_container(unittest.TestCase):\n def test_create_container_success(self):\n container = self.driver.create_container(container_name='test_create_container')\n self.assertTrue(isinstance(container, Container))\n self.assertEqual(container.name, 'test_create_container')\n self.assertEqual(container.extra['object_count'], 0)\n\n def test_create_container_already_exists(self):\n CloudFilesMockHttp.type = 'ALREADY_EXISTS'\n try:\n self.driver.create_container(container_name='test_create_container')\n except ContainerAlreadyExistsError:\n pass\n else:\n self.fail('Container already exists but an exception was not thrown')\n", "method_code": " def create_container(self, container_name):\n container_name_encoded = self._encode_container_name(container_name)\n response = self.connection.request('/%s' % container_name_encoded, method='PUT')\n if response.status == httplib.CREATED:\n extra = {'object_count': 0}\n container = Container(name=container_name, extra=extra, driver=self)\n return container\n elif response.status == httplib.ACCEPTED:\n error = ContainerAlreadyExistsError(None, self, container_name)\n raise error\n raise LibcloudError('Unexpected status code: %s' % response.status)\n ", "context": "class CloudFilesStorageDriver(StorageDriverOpenStackDriverMixin):\n def create_container(self, container_name): ...\n def __init__(self, *args, **kwargs): ...\n def list_containers(self): ...\n def list_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def get_container_cdn_url(self, container): ...\n def get_object_cdn_url(self, obj): ...\n def enable_container_cdn(self, container, ex_ttl=None): ...\n def delete_container(self, container): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def delete_object(self, obj): ...\n def ex_purge_object_from_cdn(self, obj, email=None): ...\n def ex_get_meta_data(self): ...\n def ex_multipart_upload_object(self, file_path, container, object_name, chunk_size=33554432, extra=None, verify_hash=True): ...\n def ex_enable_static_website(self, container, index_file='index.html'): ...\n def ex_set_error_page(self, container, file_name='error.html'): ...\n def ex_set_account_metadata_temp_url_key(self, key): ...\n def ex_get_object_temp_url(self, obj, method='GET', timeout=60): ...\n def _upload_object_part(self, container, object_name, part_number, iterator, verify_hash=True): ...\n def _upload_object_manifest(self, container, object_name, extra=None, verify_hash=True): ...\n def _get_more(self, last_key, value_dict): ...\n def _put_object(self, container, object_name, upload_func, upload_func_kwargs, extra=None, file_path=None, iterator=None, verify_hash=True): ...\n def _encode_container_name(self, name): ...\n def _encode_object_name(self, name): ...\n def _to_container_list(self, response): ...\n def _to_object_list(self, response, container): ...\n def _headers_to_container(self, name, headers): ...\n def _headers_to_object(self, name, container, headers): ...\n def _ex_connection_class_kwargs(self): ...\n\n name = 'CloudFiles'\n website = 'http://www.rackspace.com/'\n connectionCls = CloudFilesConnection\n hash_type = 'md5'\n supports_chunked_encoding = True\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_container_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000885.py"} {"focal_file": "libcloud/storage/drivers/cloudfiles.py", "focal_class": null, "focal_method": "delete_container", "tests": "import unittest\n\nclass Test_delete_container(unittest.TestCase):\n def test_delete_container_success(self):\n container = Container(name='foo_bar_container', extra={}, driver=self)\n result = self.driver.delete_container(container=container)\n self.assertTrue(result)\n\n def test_delete_container_not_found(self):\n CloudFilesMockHttp.type = 'NOT_FOUND'\n container = Container(name='foo_bar_container', extra={}, driver=self)\n try:\n self.driver.delete_container(container=container)\n except ContainerDoesNotExistError:\n pass\n else:\n self.fail('Container does not exist but an exception was not thrown')\n\n def test_delete_container_not_empty(self):\n CloudFilesMockHttp.type = 'NOT_EMPTY'\n container = Container(name='foo_bar_container', extra={}, driver=self)\n try:\n self.driver.delete_container(container=container)\n except ContainerIsNotEmptyError:\n pass\n else:\n self.fail('Container is not empty but an exception was not thrown')\n", "method_code": " def delete_container(self, container):\n name = self._encode_container_name(container.name)\n response = self.connection.request('/%s' % name, method='DELETE')\n if response.status == httplib.NO_CONTENT:\n return True\n elif response.status == httplib.NOT_FOUND:\n raise ContainerDoesNotExistError(value='', container_name=name, driver=self)\n elif response.status == httplib.CONFLICT:\n raise ContainerIsNotEmptyError(value='', container_name=name, driver=self)\n ", "context": "class CloudFilesStorageDriver(StorageDriverOpenStackDriverMixin):\n def delete_container(self, container): ...\n def __init__(self, *args, **kwargs): ...\n def list_containers(self): ...\n def list_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def get_container_cdn_url(self, container): ...\n def get_object_cdn_url(self, obj): ...\n def enable_container_cdn(self, container, ex_ttl=None): ...\n def create_container(self, container_name): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def delete_object(self, obj): ...\n def ex_purge_object_from_cdn(self, obj, email=None): ...\n def ex_get_meta_data(self): ...\n def ex_multipart_upload_object(self, file_path, container, object_name, chunk_size=33554432, extra=None, verify_hash=True): ...\n def ex_enable_static_website(self, container, index_file='index.html'): ...\n def ex_set_error_page(self, container, file_name='error.html'): ...\n def ex_set_account_metadata_temp_url_key(self, key): ...\n def ex_get_object_temp_url(self, obj, method='GET', timeout=60): ...\n def _upload_object_part(self, container, object_name, part_number, iterator, verify_hash=True): ...\n def _upload_object_manifest(self, container, object_name, extra=None, verify_hash=True): ...\n def _get_more(self, last_key, value_dict): ...\n def _put_object(self, container, object_name, upload_func, upload_func_kwargs, extra=None, file_path=None, iterator=None, verify_hash=True): ...\n def _encode_container_name(self, name): ...\n def _encode_object_name(self, name): ...\n def _to_container_list(self, response): ...\n def _to_object_list(self, response, container): ...\n def _headers_to_container(self, name, headers): ...\n def _headers_to_object(self, name, container, headers): ...\n def _ex_connection_class_kwargs(self): ...\n\n name = 'CloudFiles'\n website = 'http://www.rackspace.com/'\n connectionCls = CloudFilesConnection\n hash_type = 'md5'\n supports_chunked_encoding = True\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_delete_container_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000886.py"} {"focal_file": "libcloud/storage/drivers/cloudfiles.py", "focal_class": null, "focal_method": "download_object", "tests": "import unittest\n\nclass Test_download_object(unittest.TestCase):\n def test_download_object_success(self):\n container = Container(name='foo_bar_container', extra={}, driver=self)\n obj = Object(name='foo_bar_object', size=1000, hash=None, extra={}, container=container, meta_data=None, driver=CloudFilesStorageDriver)\n destination_path = os.path.abspath(__file__) + '.temp'\n result = self.driver.download_object(obj=obj, destination_path=destination_path, overwrite_existing=False, delete_on_failure=True)\n", "method_code": " def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True):\n container_name = obj.container.name\n object_name = obj.name\n response = self.connection.request('/%s/%s' % (container_name, object_name), method='GET', raw=True)\n return self._get_object(obj=obj, callback=self._save_object, response=response, callback_kwargs={'obj': obj, 'response': response.response, 'destination_path': destination_path, 'overwrite_existing': overwrite_existing, 'delete_on_failure': delete_on_failure}, success_status_code=httplib.OK)\n ", "context": "class CloudFilesStorageDriver(StorageDriverOpenStackDriverMixin):\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def __init__(self, *args, **kwargs): ...\n def list_containers(self): ...\n def list_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def get_container_cdn_url(self, container): ...\n def get_object_cdn_url(self, obj): ...\n def enable_container_cdn(self, container, ex_ttl=None): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def delete_object(self, obj): ...\n def ex_purge_object_from_cdn(self, obj, email=None): ...\n def ex_get_meta_data(self): ...\n def ex_multipart_upload_object(self, file_path, container, object_name, chunk_size=33554432, extra=None, verify_hash=True): ...\n def ex_enable_static_website(self, container, index_file='index.html'): ...\n def ex_set_error_page(self, container, file_name='error.html'): ...\n def ex_set_account_metadata_temp_url_key(self, key): ...\n def ex_get_object_temp_url(self, obj, method='GET', timeout=60): ...\n def _upload_object_part(self, container, object_name, part_number, iterator, verify_hash=True): ...\n def _upload_object_manifest(self, container, object_name, extra=None, verify_hash=True): ...\n def _get_more(self, last_key, value_dict): ...\n def _put_object(self, container, object_name, upload_func, upload_func_kwargs, extra=None, file_path=None, iterator=None, verify_hash=True): ...\n def _encode_container_name(self, name): ...\n def _encode_object_name(self, name): ...\n def _to_container_list(self, response): ...\n def _to_object_list(self, response, container): ...\n def _headers_to_container(self, name, headers): ...\n def _headers_to_object(self, name, container, headers): ...\n def _ex_connection_class_kwargs(self): ...\n\n name = 'CloudFiles'\n website = 'http://www.rackspace.com/'\n connectionCls = CloudFilesConnection\n hash_type = 'md5'\n supports_chunked_encoding = True\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_download_object_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000887.py"} {"focal_file": "libcloud/storage/drivers/cloudfiles.py", "focal_class": null, "focal_method": "download_object_as_stream", "tests": "import unittest\n\nclass Test_download_object_as_stream(unittest.TestCase):\n def test_download_object_as_stream(self):\n container = Container(name='foo_bar_container', extra={}, driver=self)\n obj = Object(name='foo_bar_object', size=1000, hash=None, extra={}, container=container, meta_data=None, driver=CloudFilesStorageDriver)\n stream = self.driver.download_object_as_stream(obj=obj, chunk_size=None)\n self.assertTrue(hasattr(stream, '__iter__'))\n", "method_code": " def download_object_as_stream(self, obj, chunk_size=None):\n container_name = obj.container.name\n object_name = obj.name\n response = self.connection.request('/%s/%s' % (container_name, object_name), method='GET', raw=True)\n return self._get_object(obj=obj, callback=read_in_chunks, response=response, callback_kwargs={'iterator': response.response, 'chunk_size': chunk_size}, success_status_code=httplib.OK)\n ", "context": "class CloudFilesStorageDriver(StorageDriverOpenStackDriverMixin):\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def __init__(self, *args, **kwargs): ...\n def list_containers(self): ...\n def list_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def get_container_cdn_url(self, container): ...\n def get_object_cdn_url(self, obj): ...\n def enable_container_cdn(self, container, ex_ttl=None): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def delete_object(self, obj): ...\n def ex_purge_object_from_cdn(self, obj, email=None): ...\n def ex_get_meta_data(self): ...\n def ex_multipart_upload_object(self, file_path, container, object_name, chunk_size=33554432, extra=None, verify_hash=True): ...\n def ex_enable_static_website(self, container, index_file='index.html'): ...\n def ex_set_error_page(self, container, file_name='error.html'): ...\n def ex_set_account_metadata_temp_url_key(self, key): ...\n def ex_get_object_temp_url(self, obj, method='GET', timeout=60): ...\n def _upload_object_part(self, container, object_name, part_number, iterator, verify_hash=True): ...\n def _upload_object_manifest(self, container, object_name, extra=None, verify_hash=True): ...\n def _get_more(self, last_key, value_dict): ...\n def _put_object(self, container, object_name, upload_func, upload_func_kwargs, extra=None, file_path=None, iterator=None, verify_hash=True): ...\n def _encode_container_name(self, name): ...\n def _encode_object_name(self, name): ...\n def _to_container_list(self, response): ...\n def _to_object_list(self, response, container): ...\n def _headers_to_container(self, name, headers): ...\n def _headers_to_object(self, name, container, headers): ...\n def _ex_connection_class_kwargs(self): ...\n\n name = 'CloudFiles'\n website = 'http://www.rackspace.com/'\n connectionCls = CloudFilesConnection\n hash_type = 'md5'\n supports_chunked_encoding = True\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_download_object_as_stream", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 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": "libcloud/storage/drivers/cloudfiles.py", "focal_class": null, "focal_method": "upload_object", "tests": "import unittest\n\nclass Test_upload_object(unittest.TestCase):\n def test_upload_object_success(self):\n\n def upload_file(self, response, file_path, chunked=False, calculate_hash=True):\n return (True, 'hash343hhash89h932439jsaa89', 1000)\n old_func = CloudFilesStorageDriver._upload_file\n CloudFilesStorageDriver._upload_file = upload_file\n file_path = os.path.abspath(__file__)\n container = Container(name='foo_bar_container', extra={}, driver=self)\n object_name = 'foo_test_upload'\n extra = {'meta_data': {'some-value': 'foobar'}}\n obj = self.driver.upload_object(file_path=file_path, container=container, extra=extra, object_name=object_name)\n self.assertEqual(obj.name, 'foo_test_upload')\n self.assertEqual(obj.size, 1000)\n self.assertTrue('some-value' in obj.meta_data)\n CloudFilesStorageDriver._upload_file = old_func\n\n def test_upload_object_error(self):\n\n def dummy_content_type(name):\n return ('application/zip', None)\n\n def send(instance):\n raise Exception('')\n old_func1 = libcloud.utils.files.guess_file_mime_type\n libcloud.utils.files.guess_file_mime_type = dummy_content_type\n old_func2 = CloudFilesMockHttp.send\n CloudFilesMockHttp.send = send\n file_path = os.path.abspath(__file__)\n container = Container(name='foo_bar_container', extra={}, driver=self)\n object_name = 'foo_test_upload'\n try:\n self.driver.upload_object(file_path=file_path, container=container, object_name=object_name)\n except LibcloudError:\n pass\n else:\n self.fail('Timeout while uploading but an exception was not thrown')\n finally:\n libcloud.utils.files.guess_file_mime_type = old_func1\n CloudFilesMockHttp.send = old_func2\n", "method_code": " def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True):\n \"\"\"\n Upload an object.\n \n Note: This will override file with a same name if it already exists.\n \"\"\"\n upload_func = self._upload_file\n upload_func_kwargs = {'file_path': file_path}\n return self._put_object(container=container, object_name=object_name, upload_func=upload_func, upload_func_kwargs=upload_func_kwargs, extra=extra, file_path=file_path, verify_hash=verify_hash)\n ", "context": "class CloudFilesStorageDriver(StorageDriverOpenStackDriverMixin):\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def __init__(self, *args, **kwargs): ...\n def list_containers(self): ...\n def list_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def get_container_cdn_url(self, container): ...\n def get_object_cdn_url(self, obj): ...\n def enable_container_cdn(self, container, ex_ttl=None): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def delete_object(self, obj): ...\n def ex_purge_object_from_cdn(self, obj, email=None): ...\n def ex_get_meta_data(self): ...\n def ex_multipart_upload_object(self, file_path, container, object_name, chunk_size=33554432, extra=None, verify_hash=True): ...\n def ex_enable_static_website(self, container, index_file='index.html'): ...\n def ex_set_error_page(self, container, file_name='error.html'): ...\n def ex_set_account_metadata_temp_url_key(self, key): ...\n def ex_get_object_temp_url(self, obj, method='GET', timeout=60): ...\n def _upload_object_part(self, container, object_name, part_number, iterator, verify_hash=True): ...\n def _upload_object_manifest(self, container, object_name, extra=None, verify_hash=True): ...\n def _get_more(self, last_key, value_dict): ...\n def _put_object(self, container, object_name, upload_func, upload_func_kwargs, extra=None, file_path=None, iterator=None, verify_hash=True): ...\n def _encode_container_name(self, name): ...\n def _encode_object_name(self, name): ...\n def _to_container_list(self, response): ...\n def _to_object_list(self, response, container): ...\n def _headers_to_container(self, name, headers): ...\n def _headers_to_object(self, name, container, headers): ...\n def _ex_connection_class_kwargs(self): ...\n\n name = 'CloudFiles'\n website = 'http://www.rackspace.com/'\n connectionCls = CloudFilesConnection\n hash_type = 'md5'\n supports_chunked_encoding = True\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_upload_object_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1], "pynose_source_file": "test_000889.py"} {"focal_file": "libcloud/storage/drivers/cloudfiles.py", "focal_class": null, "focal_method": "upload_object_via_stream", "tests": "import unittest\n\nclass Test_upload_object_via_stream(unittest.TestCase):\n def test_upload_object_via_stream(self):\n\n def dummy_content_type(name):\n return ('application/zip', None)\n old_func = libcloud.utils.files.guess_file_mime_type\n libcloud.utils.files.guess_file_mime_type = dummy_content_type\n container = Container(name='foo_bar_container', extra={}, driver=self)\n object_name = 'foo_test_stream_data'\n iterator = DummyIterator(data=['2', '3', '5'])\n try:\n self.driver.upload_object_via_stream(container=container, object_name=object_name, iterator=iterator)\n finally:\n libcloud.utils.files.guess_file_mime_type = old_func\n", "method_code": " def upload_object_via_stream(self, iterator, container, object_name, extra=None):\n if isinstance(iterator, file):\n iterator = iter(iterator)\n upload_func = self._stream_data\n upload_func_kwargs = {'iterator': iterator}\n return self._put_object(container=container, object_name=object_name, upload_func=upload_func, upload_func_kwargs=upload_func_kwargs, extra=extra, iterator=iterator)\n ", "context": "class CloudFilesStorageDriver(StorageDriverOpenStackDriverMixin):\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def __init__(self, *args, **kwargs): ...\n def list_containers(self): ...\n def list_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def get_container_cdn_url(self, container): ...\n def get_object_cdn_url(self, obj): ...\n def enable_container_cdn(self, container, ex_ttl=None): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def delete_object(self, obj): ...\n def ex_purge_object_from_cdn(self, obj, email=None): ...\n def ex_get_meta_data(self): ...\n def ex_multipart_upload_object(self, file_path, container, object_name, chunk_size=33554432, extra=None, verify_hash=True): ...\n def ex_enable_static_website(self, container, index_file='index.html'): ...\n def ex_set_error_page(self, container, file_name='error.html'): ...\n def ex_set_account_metadata_temp_url_key(self, key): ...\n def ex_get_object_temp_url(self, obj, method='GET', timeout=60): ...\n def _upload_object_part(self, container, object_name, part_number, iterator, verify_hash=True): ...\n def _upload_object_manifest(self, container, object_name, extra=None, verify_hash=True): ...\n def _get_more(self, last_key, value_dict): ...\n def _put_object(self, container, object_name, upload_func, upload_func_kwargs, extra=None, file_path=None, iterator=None, verify_hash=True): ...\n def _encode_container_name(self, name): ...\n def _encode_object_name(self, name): ...\n def _to_container_list(self, response): ...\n def _to_object_list(self, response, container): ...\n def _headers_to_container(self, name, headers): ...\n def _headers_to_object(self, name, container, headers): ...\n def _ex_connection_class_kwargs(self): ...\n\n name = 'CloudFiles'\n website = 'http://www.rackspace.com/'\n connectionCls = CloudFilesConnection\n hash_type = 'md5'\n supports_chunked_encoding = True\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_upload_object_via_stream", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000890.py"} {"focal_file": "libcloud/storage/drivers/cloudfiles.py", "focal_class": null, "focal_method": "delete_object", "tests": "import unittest\n\nclass Test_delete_object(unittest.TestCase):\n def test_delete_object_success(self):\n container = Container(name='foo_bar_container', extra={}, driver=self)\n obj = Object(name='foo_bar_object', size=1000, hash=None, extra={}, container=container, meta_data=None, driver=CloudFilesStorageDriver)\n status = self.driver.delete_object(obj=obj)\n self.assertTrue(status)\n\n def test_delete_object_not_found(self):\n CloudFilesMockHttp.type = 'NOT_FOUND'\n container = Container(name='foo_bar_container', extra={}, driver=self)\n obj = Object(name='foo_bar_object', size=1000, hash=None, extra={}, container=container, meta_data=None, driver=CloudFilesStorageDriver)\n try:\n self.driver.delete_object(obj=obj)\n except ObjectDoesNotExistError:\n pass\n else:\n self.fail('Object does not exist but an exception was not thrown')\n", "method_code": " def delete_object(self, obj):\n container_name = self._encode_container_name(obj.container.name)\n object_name = self._encode_object_name(obj.name)\n response = self.connection.request('/%s/%s' % (container_name, object_name), method='DELETE')\n if response.status == httplib.NO_CONTENT:\n return True\n elif response.status == httplib.NOT_FOUND:\n raise ObjectDoesNotExistError(value='', object_name=object_name, driver=self)\n raise LibcloudError('Unexpected status code: %s' % response.status)\n ", "context": "class CloudFilesStorageDriver(StorageDriverOpenStackDriverMixin):\n def delete_object(self, obj): ...\n def __init__(self, *args, **kwargs): ...\n def list_containers(self): ...\n def list_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def get_container_cdn_url(self, container): ...\n def get_object_cdn_url(self, obj): ...\n def enable_container_cdn(self, container, ex_ttl=None): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def ex_purge_object_from_cdn(self, obj, email=None): ...\n def ex_get_meta_data(self): ...\n def ex_multipart_upload_object(self, file_path, container, object_name, chunk_size=33554432, extra=None, verify_hash=True): ...\n def ex_enable_static_website(self, container, index_file='index.html'): ...\n def ex_set_error_page(self, container, file_name='error.html'): ...\n def ex_set_account_metadata_temp_url_key(self, key): ...\n def ex_get_object_temp_url(self, obj, method='GET', timeout=60): ...\n def _upload_object_part(self, container, object_name, part_number, iterator, verify_hash=True): ...\n def _upload_object_manifest(self, container, object_name, extra=None, verify_hash=True): ...\n def _get_more(self, last_key, value_dict): ...\n def _put_object(self, container, object_name, upload_func, upload_func_kwargs, extra=None, file_path=None, iterator=None, verify_hash=True): ...\n def _encode_container_name(self, name): ...\n def _encode_object_name(self, name): ...\n def _to_container_list(self, response): ...\n def _to_object_list(self, response, container): ...\n def _headers_to_container(self, name, headers): ...\n def _headers_to_object(self, name, container, headers): ...\n def _ex_connection_class_kwargs(self): ...\n\n name = 'CloudFiles'\n website = 'http://www.rackspace.com/'\n connectionCls = CloudFilesConnection\n hash_type = 'md5'\n supports_chunked_encoding = True\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_delete_object_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000891.py"} {"focal_file": "libcloud/storage/drivers/cloudfiles.py", "focal_class": null, "focal_method": "ex_get_meta_data", "tests": "import unittest\n\nclass Test_ex_get_meta_data(unittest.TestCase):\n def test_ex_get_meta_data(self):\n meta_data = self.driver.ex_get_meta_data()\n self.assertTrue(isinstance(meta_data, dict))\n self.assertTrue('object_count' in meta_data)\n self.assertTrue('container_count' in meta_data)\n self.assertTrue('bytes_used' in meta_data)\n self.assertTrue('temp_url_key' in meta_data)\n", "method_code": " def ex_get_meta_data(self):\n \"\"\"\n Get meta data\n \n @rtype: C{dict}\n \"\"\"\n response = self.connection.request('', method='HEAD')\n if response.status == httplib.NO_CONTENT:\n container_count = response.headers.get('x-account-container-count', 'unknown')\n object_count = response.headers.get('x-account-object-count', 'unknown')\n bytes_used = response.headers.get('x-account-bytes-used', 'unknown')\n temp_url_key = response.headers.get('x-account-meta-temp-url-key', None)\n return {'container_count': int(container_count), 'object_count': int(object_count), 'bytes_used': int(bytes_used), 'temp_url_key': temp_url_key}\n raise LibcloudError('Unexpected status code: %s' % response.status)\n ", "context": "class CloudFilesStorageDriver(StorageDriverOpenStackDriverMixin):\n def ex_get_meta_data(self): ...\n def __init__(self, *args, **kwargs): ...\n def list_containers(self): ...\n def list_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def get_container_cdn_url(self, container): ...\n def get_object_cdn_url(self, obj): ...\n def enable_container_cdn(self, container, ex_ttl=None): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def delete_object(self, obj): ...\n def ex_purge_object_from_cdn(self, obj, email=None): ...\n def ex_multipart_upload_object(self, file_path, container, object_name, chunk_size=33554432, extra=None, verify_hash=True): ...\n def ex_enable_static_website(self, container, index_file='index.html'): ...\n def ex_set_error_page(self, container, file_name='error.html'): ...\n def ex_set_account_metadata_temp_url_key(self, key): ...\n def ex_get_object_temp_url(self, obj, method='GET', timeout=60): ...\n def _upload_object_part(self, container, object_name, part_number, iterator, verify_hash=True): ...\n def _upload_object_manifest(self, container, object_name, extra=None, verify_hash=True): ...\n def _get_more(self, last_key, value_dict): ...\n def _put_object(self, container, object_name, upload_func, upload_func_kwargs, extra=None, file_path=None, iterator=None, verify_hash=True): ...\n def _encode_container_name(self, name): ...\n def _encode_object_name(self, name): ...\n def _to_container_list(self, response): ...\n def _to_object_list(self, response, container): ...\n def _headers_to_container(self, name, headers): ...\n def _headers_to_object(self, name, container, headers): ...\n def _ex_connection_class_kwargs(self): ...\n\n name = 'CloudFiles'\n website = 'http://www.rackspace.com/'\n connectionCls = CloudFilesConnection\n hash_type = 'md5'\n supports_chunked_encoding = True\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_get_meta_data", "smells": [1, 0, 0, 0, 0, 0, 1, 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_000892.py"} {"focal_file": "libcloud/storage/drivers/cloudfiles.py", "focal_class": null, "focal_method": "ex_multipart_upload_object", "tests": "import unittest\n\nclass Test_ex_multipart_upload_object(unittest.TestCase):\n @mock.patch('os.path.getsize')\n def test_ex_multipart_upload_object_for_small_files(self, getsize_mock):\n getsize_mock.return_value = 0\n old_func = CloudFilesStorageDriver.upload_object\n mocked_upload_object = mock.Mock(return_value='test')\n CloudFilesStorageDriver.upload_object = mocked_upload_object\n file_path = os.path.abspath(__file__)\n container = Container(name='foo_bar_container', extra={}, driver=self)\n object_name = 'foo_test_upload'\n obj = self.driver.ex_multipart_upload_object(file_path=file_path, container=container, object_name=object_name)\n CloudFilesStorageDriver.upload_object = old_func\n self.assertTrue(mocked_upload_object.called)\n self.assertEqual(obj, 'test')\n\n def test_ex_multipart_upload_object_success(self):\n _upload_object_part = CloudFilesStorageDriver._upload_object_part\n _upload_object_manifest = CloudFilesStorageDriver._upload_object_manifest\n mocked__upload_object_part = mock.Mock(return_value='test_part')\n mocked__upload_object_manifest = mock.Mock(return_value='test_manifest')\n CloudFilesStorageDriver._upload_object_part = mocked__upload_object_part\n CloudFilesStorageDriver._upload_object_manifest = mocked__upload_object_manifest\n parts = 5\n file_path = os.path.abspath(__file__)\n chunk_size = int(math.ceil(float(os.path.getsize(file_path)) / parts))\n container = Container(name='foo_bar_container', extra={}, driver=self)\n object_name = 'foo_test_upload'\n self.driver.ex_multipart_upload_object(file_path=file_path, container=container, object_name=object_name, chunk_size=chunk_size)\n CloudFilesStorageDriver._upload_object_part = _upload_object_part\n CloudFilesStorageDriver._upload_object_manifest = _upload_object_manifest\n self.assertEqual(mocked__upload_object_part.call_count, parts)\n self.assertTrue(mocked__upload_object_manifest.call_count, 1)\n", "method_code": " def ex_multipart_upload_object(self, file_path, container, object_name, chunk_size=33554432, extra=None, verify_hash=True):\n object_size = os.path.getsize(file_path)\n if object_size < chunk_size:\n return self.upload_object(file_path, container, object_name, extra=extra, verify_hash=verify_hash)\n iter_chunk_reader = FileChunkReader(file_path, chunk_size)\n for index, iterator in enumerate(iter_chunk_reader):\n self._upload_object_part(container=container, object_name=object_name, part_number=index, iterator=iterator, verify_hash=verify_hash)\n return self._upload_object_manifest(container=container, object_name=object_name, extra=extra, verify_hash=verify_hash)\n ", "context": "class CloudFilesStorageDriver(StorageDriverOpenStackDriverMixin):\n def ex_multipart_upload_object(self, file_path, container, object_name, chunk_size=33554432, extra=None, verify_hash=True): ...\n def __init__(self, *args, **kwargs): ...\n def list_containers(self): ...\n def list_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def get_container_cdn_url(self, container): ...\n def get_object_cdn_url(self, obj): ...\n def enable_container_cdn(self, container, ex_ttl=None): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def delete_object(self, obj): ...\n def ex_purge_object_from_cdn(self, obj, email=None): ...\n def ex_get_meta_data(self): ...\n def ex_enable_static_website(self, container, index_file='index.html'): ...\n def ex_set_error_page(self, container, file_name='error.html'): ...\n def ex_set_account_metadata_temp_url_key(self, key): ...\n def ex_get_object_temp_url(self, obj, method='GET', timeout=60): ...\n def _upload_object_part(self, container, object_name, part_number, iterator, verify_hash=True): ...\n def _upload_object_manifest(self, container, object_name, extra=None, verify_hash=True): ...\n def _get_more(self, last_key, value_dict): ...\n def _put_object(self, container, object_name, upload_func, upload_func_kwargs, extra=None, file_path=None, iterator=None, verify_hash=True): ...\n def _encode_container_name(self, name): ...\n def _encode_object_name(self, name): ...\n def _to_container_list(self, response): ...\n def _to_object_list(self, response, container): ...\n def _headers_to_container(self, name, headers): ...\n def _headers_to_object(self, name, container, headers): ...\n def _ex_connection_class_kwargs(self): ...\n\n name = 'CloudFiles'\n website = 'http://www.rackspace.com/'\n connectionCls = CloudFilesConnection\n hash_type = 'md5'\n supports_chunked_encoding = True\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000893.py"} {"focal_file": "libcloud/storage/drivers/cloudfiles.py", "focal_class": null, "focal_method": "_upload_object_part", "tests": "import unittest\n\nclass Test_upload_object_part(unittest.TestCase):\n def test__upload_object_part(self):\n _put_object = CloudFilesStorageDriver._put_object\n mocked__put_object = mock.Mock(return_value='test')\n CloudFilesStorageDriver._put_object = mocked__put_object\n part_number = 7\n object_name = 'test_object'\n expected_name = object_name + '/%08d' % part_number\n container = Container(name='foo_bar_container', extra={}, driver=self)\n self.driver._upload_object_part(container, object_name, part_number, None)\n CloudFilesStorageDriver._put_object = _put_object\n func_kwargs = tuple(mocked__put_object.call_args)[1]\n self.assertEquals(func_kwargs['object_name'], expected_name)\n self.assertEquals(func_kwargs['container'], container)\n", "method_code": " def _upload_object_part(self, container, object_name, part_number, iterator, verify_hash=True):\n upload_func = self._stream_data\n upload_func_kwargs = {'iterator': iterator}\n part_name = object_name + '/%08d' % part_number\n extra = {'content_type': 'application/octet-stream'}\n self._put_object(container=container, object_name=part_name, upload_func=upload_func, upload_func_kwargs=upload_func_kwargs, extra=extra, iterator=iterator, verify_hash=verify_hash)\n ", "context": "class CloudFilesStorageDriver(StorageDriverOpenStackDriverMixin):\n def _upload_object_part(self, container, object_name, part_number, iterator, verify_hash=True): ...\n def __init__(self, *args, **kwargs): ...\n def list_containers(self): ...\n def list_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def get_container_cdn_url(self, container): ...\n def get_object_cdn_url(self, obj): ...\n def enable_container_cdn(self, container, ex_ttl=None): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def delete_object(self, obj): ...\n def ex_purge_object_from_cdn(self, obj, email=None): ...\n def ex_get_meta_data(self): ...\n def ex_multipart_upload_object(self, file_path, container, object_name, chunk_size=33554432, extra=None, verify_hash=True): ...\n def ex_enable_static_website(self, container, index_file='index.html'): ...\n def ex_set_error_page(self, container, file_name='error.html'): ...\n def ex_set_account_metadata_temp_url_key(self, key): ...\n def ex_get_object_temp_url(self, obj, method='GET', timeout=60): ...\n def _upload_object_manifest(self, container, object_name, extra=None, verify_hash=True): ...\n def _get_more(self, last_key, value_dict): ...\n def _put_object(self, container, object_name, upload_func, upload_func_kwargs, extra=None, file_path=None, iterator=None, verify_hash=True): ...\n def _encode_container_name(self, name): ...\n def _encode_object_name(self, name): ...\n def _to_container_list(self, response): ...\n def _to_object_list(self, response, container): ...\n def _headers_to_container(self, name, headers): ...\n def _headers_to_object(self, name, container, headers): ...\n def _ex_connection_class_kwargs(self): ...\n\n name = 'CloudFiles'\n website = 'http://www.rackspace.com/'\n connectionCls = CloudFilesConnection\n hash_type = 'md5'\n supports_chunked_encoding = True\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test__upload_object_part", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/storage/drivers/cloudfiles.py", "focal_class": null, "focal_method": "_upload_object_manifest", "tests": "import unittest\n\nclass Test_upload_object_manifest(unittest.TestCase):\n def test__upload_object_manifest(self):\n hash_function = self.driver._get_hash_function()\n hash_function.update(b(''))\n data_hash = hash_function.hexdigest()\n fake_response = type('CloudFilesResponse', (), {'headers': {'etag': data_hash}})\n _request = self.driver.connection.request\n mocked_request = mock.Mock(return_value=fake_response)\n self.driver.connection.request = mocked_request\n container = Container(name='foo_bar_container', extra={}, driver=self)\n object_name = 'test_object'\n self.driver._upload_object_manifest(container, object_name)\n func_args, func_kwargs = tuple(mocked_request.call_args)\n self.driver.connection.request = _request\n self.assertEquals(func_args[0], '/' + container.name + '/' + object_name)\n self.assertEquals(func_kwargs['headers']['X-Object-Manifest'], container.name + '/' + object_name + '/')\n self.assertEquals(func_kwargs['method'], 'PUT')\n\n def test__upload_object_manifest_wrong_hash(self):\n fake_response = type('CloudFilesResponse', (), {'headers': {'etag': '0000000'}})\n _request = self.driver.connection.request\n mocked_request = mock.Mock(return_value=fake_response)\n self.driver.connection.request = mocked_request\n container = Container(name='foo_bar_container', extra={}, driver=self)\n object_name = 'test_object'\n try:\n self.driver._upload_object_manifest(container, object_name)\n except ObjectHashMismatchError:\n pass\n else:\n self.fail('Exception was not thrown')\n finally:\n self.driver.connection.request = _request\n", "method_code": " def _upload_object_manifest(self, container, object_name, extra=None, verify_hash=True):\n extra = extra or {}\n meta_data = extra.get('meta_data')\n container_name_encoded = self._encode_container_name(container.name)\n object_name_encoded = self._encode_object_name(object_name)\n request_path = '/%s/%s' % (container_name_encoded, object_name_encoded)\n headers = {'X-Auth-Token': self.connection.auth_token, 'X-Object-Manifest': '%s/%s/' % (container_name_encoded, object_name_encoded)}\n data = ''\n response = self.connection.request(request_path, method='PUT', data=data, headers=headers, raw=True)\n object_hash = None\n if verify_hash:\n hash_function = self._get_hash_function()\n hash_function.update(b(data))\n data_hash = hash_function.hexdigest()\n object_hash = response.headers.get('etag')\n if object_hash != data_hash:\n raise ObjectHashMismatchError(value=('MD5 hash checksum does not match (expected=%s, ' + 'actual=%s)') % (data_hash, object_hash), object_name=object_name, driver=self)\n obj = Object(name=object_name, size=0, hash=object_hash, extra=None, meta_data=meta_data, container=container, driver=self)\n return obj\n ", "context": "class CloudFilesStorageDriver(StorageDriverOpenStackDriverMixin):\n def _upload_object_manifest(self, container, object_name, extra=None, verify_hash=True): ...\n def __init__(self, *args, **kwargs): ...\n def list_containers(self): ...\n def list_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def get_container_cdn_url(self, container): ...\n def get_object_cdn_url(self, obj): ...\n def enable_container_cdn(self, container, ex_ttl=None): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def delete_object(self, obj): ...\n def ex_purge_object_from_cdn(self, obj, email=None): ...\n def ex_get_meta_data(self): ...\n def ex_multipart_upload_object(self, file_path, container, object_name, chunk_size=33554432, extra=None, verify_hash=True): ...\n def ex_enable_static_website(self, container, index_file='index.html'): ...\n def ex_set_error_page(self, container, file_name='error.html'): ...\n def ex_set_account_metadata_temp_url_key(self, key): ...\n def ex_get_object_temp_url(self, obj, method='GET', timeout=60): ...\n def _upload_object_part(self, container, object_name, part_number, iterator, verify_hash=True): ...\n def _get_more(self, last_key, value_dict): ...\n def _put_object(self, container, object_name, upload_func, upload_func_kwargs, extra=None, file_path=None, iterator=None, verify_hash=True): ...\n def _encode_container_name(self, name): ...\n def _encode_object_name(self, name): ...\n def _to_container_list(self, response): ...\n def _to_object_list(self, response, container): ...\n def _headers_to_container(self, name, headers): ...\n def _headers_to_object(self, name, container, headers): ...\n def _ex_connection_class_kwargs(self): ...\n\n name = 'CloudFiles'\n website = 'http://www.rackspace.com/'\n connectionCls = CloudFilesConnection\n hash_type = 'md5'\n supports_chunked_encoding = True\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test__upload_object_manifest", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000895.py"} {"focal_file": "libcloud/storage/drivers/cloudfiles.py", "focal_class": null, "focal_method": "ex_enable_static_website", "tests": "import unittest\n\nclass Test_ex_enable_static_website(unittest.TestCase):\n def test_ex_enable_static_website(self):\n container = Container(name='foo_bar_container', extra={}, driver=self)\n result = self.driver.ex_enable_static_website(container=container, index_file='index.html')\n self.assertTrue(result)\n", "method_code": " def ex_enable_static_website(self, container, index_file='index.html'):\n \"\"\"\n Enable serving a static website.\n \n @param container: Container instance\n @type container: L{Container}\n \n @param index_file: Name of the object which becomes an index page for\n every sub-directory in this container.\n @type index_file: C{str}\n \n @rtype: C{bool}\n \"\"\"\n container_name = container.name\n headers = {'X-Container-Meta-Web-Index': index_file}\n response = self.connection.request('/%s' % container_name, method='POST', headers=headers, cdn_request=False)\n return response.status in [httplib.CREATED, httplib.ACCEPTED]\n ", "context": "class CloudFilesStorageDriver(StorageDriverOpenStackDriverMixin):\n def ex_enable_static_website(self, container, index_file='index.html'): ...\n def __init__(self, *args, **kwargs): ...\n def list_containers(self): ...\n def list_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def get_container_cdn_url(self, container): ...\n def get_object_cdn_url(self, obj): ...\n def enable_container_cdn(self, container, ex_ttl=None): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def delete_object(self, obj): ...\n def ex_purge_object_from_cdn(self, obj, email=None): ...\n def ex_get_meta_data(self): ...\n def ex_multipart_upload_object(self, file_path, container, object_name, chunk_size=33554432, extra=None, verify_hash=True): ...\n def ex_set_error_page(self, container, file_name='error.html'): ...\n def ex_set_account_metadata_temp_url_key(self, key): ...\n def ex_get_object_temp_url(self, obj, method='GET', timeout=60): ...\n def _upload_object_part(self, container, object_name, part_number, iterator, verify_hash=True): ...\n def _upload_object_manifest(self, container, object_name, extra=None, verify_hash=True): ...\n def _get_more(self, last_key, value_dict): ...\n def _put_object(self, container, object_name, upload_func, upload_func_kwargs, extra=None, file_path=None, iterator=None, verify_hash=True): ...\n def _encode_container_name(self, name): ...\n def _encode_object_name(self, name): ...\n def _to_container_list(self, response): ...\n def _to_object_list(self, response, container): ...\n def _headers_to_container(self, name, headers): ...\n def _headers_to_object(self, name, container, headers): ...\n def _ex_connection_class_kwargs(self): ...\n\n name = 'CloudFiles'\n website = 'http://www.rackspace.com/'\n connectionCls = CloudFilesConnection\n hash_type = 'md5'\n supports_chunked_encoding = True\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_enable_static_website", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/storage/drivers/cloudfiles.py", "focal_class": null, "focal_method": "ex_set_error_page", "tests": "import unittest\n\nclass Test_ex_set_error_page(unittest.TestCase):\n def test_ex_set_error_page(self):\n container = Container(name='foo_bar_container', extra={}, driver=self)\n result = self.driver.ex_set_error_page(container=container, file_name='error.html')\n self.assertTrue(result)\n", "method_code": " def ex_set_error_page(self, container, file_name='error.html'):\n \"\"\"\n Set a custom error page which is displayed if file is not found and\n serving of a static website is enabled.\n \n @param container: Container instance\n @type container: L{Container}\n \n @param file_name: Name of the object which becomes the error page.\n @type file_name: C{str}\n \n @rtype: C{bool}\n \"\"\"\n container_name = container.name\n headers = {'X-Container-Meta-Web-Error': file_name}\n response = self.connection.request('/%s' % container_name, method='POST', headers=headers, cdn_request=False)\n return response.status in [httplib.CREATED, httplib.ACCEPTED]\n ", "context": "class CloudFilesStorageDriver(StorageDriverOpenStackDriverMixin):\n def ex_set_error_page(self, container, file_name='error.html'): ...\n def __init__(self, *args, **kwargs): ...\n def list_containers(self): ...\n def list_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def get_container_cdn_url(self, container): ...\n def get_object_cdn_url(self, obj): ...\n def enable_container_cdn(self, container, ex_ttl=None): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def delete_object(self, obj): ...\n def ex_purge_object_from_cdn(self, obj, email=None): ...\n def ex_get_meta_data(self): ...\n def ex_multipart_upload_object(self, file_path, container, object_name, chunk_size=33554432, extra=None, verify_hash=True): ...\n def ex_enable_static_website(self, container, index_file='index.html'): ...\n def ex_set_account_metadata_temp_url_key(self, key): ...\n def ex_get_object_temp_url(self, obj, method='GET', timeout=60): ...\n def _upload_object_part(self, container, object_name, part_number, iterator, verify_hash=True): ...\n def _upload_object_manifest(self, container, object_name, extra=None, verify_hash=True): ...\n def _get_more(self, last_key, value_dict): ...\n def _put_object(self, container, object_name, upload_func, upload_func_kwargs, extra=None, file_path=None, iterator=None, verify_hash=True): ...\n def _encode_container_name(self, name): ...\n def _encode_object_name(self, name): ...\n def _to_container_list(self, response): ...\n def _to_object_list(self, response, container): ...\n def _headers_to_container(self, name, headers): ...\n def _headers_to_object(self, name, container, headers): ...\n def _ex_connection_class_kwargs(self): ...\n\n name = 'CloudFiles'\n website = 'http://www.rackspace.com/'\n connectionCls = CloudFilesConnection\n hash_type = 'md5'\n supports_chunked_encoding = True\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_set_error_page", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/storage/drivers/cloudfiles.py", "focal_class": null, "focal_method": "ex_set_account_metadata_temp_url_key", "tests": "import unittest\n\nclass Test_ex_set_account_metadata_temp_url_key(unittest.TestCase):\n def test_ex_set_account_metadata_temp_url_key(self):\n result = self.driver.ex_set_account_metadata_temp_url_key('a key')\n self.assertTrue(result)\n", "method_code": " def ex_set_account_metadata_temp_url_key(self, key):\n \"\"\"\n Set the metadata header X-Account-Meta-Temp-URL-Key on your Cloud\n Files account.\n \n @param key: X-Account-Meta-Temp-URL-Key\n @type key: C{str}\n \n @rtype: C{bool}\n \"\"\"\n headers = {'X-Account-Meta-Temp-URL-Key': key}\n response = self.connection.request('', method='POST', headers=headers, cdn_request=False)\n return response.status in [httplib.OK, httplib.NO_CONTENT, httplib.CREATED, httplib.ACCEPTED]\n ", "context": "class CloudFilesStorageDriver(StorageDriverOpenStackDriverMixin):\n def ex_set_account_metadata_temp_url_key(self, key): ...\n def __init__(self, *args, **kwargs): ...\n def list_containers(self): ...\n def list_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def get_container_cdn_url(self, container): ...\n def get_object_cdn_url(self, obj): ...\n def enable_container_cdn(self, container, ex_ttl=None): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def delete_object(self, obj): ...\n def ex_purge_object_from_cdn(self, obj, email=None): ...\n def ex_get_meta_data(self): ...\n def ex_multipart_upload_object(self, file_path, container, object_name, chunk_size=33554432, extra=None, verify_hash=True): ...\n def ex_enable_static_website(self, container, index_file='index.html'): ...\n def ex_set_error_page(self, container, file_name='error.html'): ...\n def ex_get_object_temp_url(self, obj, method='GET', timeout=60): ...\n def _upload_object_part(self, container, object_name, part_number, iterator, verify_hash=True): ...\n def _upload_object_manifest(self, container, object_name, extra=None, verify_hash=True): ...\n def _get_more(self, last_key, value_dict): ...\n def _put_object(self, container, object_name, upload_func, upload_func_kwargs, extra=None, file_path=None, iterator=None, verify_hash=True): ...\n def _encode_container_name(self, name): ...\n def _encode_object_name(self, name): ...\n def _to_container_list(self, response): ...\n def _to_object_list(self, response, container): ...\n def _headers_to_container(self, name, headers): ...\n def _headers_to_object(self, name, container, headers): ...\n def _ex_connection_class_kwargs(self): ...\n\n name = 'CloudFiles'\n website = 'http://www.rackspace.com/'\n connectionCls = CloudFilesConnection\n hash_type = 'md5'\n supports_chunked_encoding = True\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_ex_set_account_metadata_temp_url_key", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/storage/drivers/cloudfiles.py", "focal_class": null, "focal_method": "ex_get_object_temp_url", "tests": "import unittest\n\nclass Test_ex_get_object_temp_url(unittest.TestCase):\n @mock.patch('libcloud.storage.drivers.cloudfiles.time')\n def test_ex_get_object_temp_url(self, time):\n time.return_value = 0\n self.driver.ex_get_meta_data = mock.Mock()\n self.driver.ex_get_meta_data.return_value = {'container_count': 1, 'object_count': 1, 'bytes_used': 1, 'temp_url_key': 'foo'}\n container = Container(name='foo_bar_container', extra={}, driver=self)\n obj = Object(name='foo_bar_object', size=1000, hash=None, extra={}, container=container, meta_data=None, driver=self)\n hmac_body = '%s\\n%s\\n%s' % ('GET', 60, '/v1/MossoCloudFS/foo_bar_container/foo_bar_object')\n sig = hmac.new(b('foo'), b(hmac_body), sha1).hexdigest()\n ret = self.driver.ex_get_object_temp_url(obj, 'GET')\n temp_url = 'https://storage101.ord1.clouddrive.com/v1/MossoCloudFS/foo_bar_container/foo_bar_object?temp_url_expires=60&temp_url_sig=%s' % sig\n self.assertEquals(''.join(sorted(ret)), ''.join(sorted(temp_url)))\n", "method_code": " def ex_get_object_temp_url(self, obj, method='GET', timeout=60):\n \"\"\"\n Create a temporary URL to allow others to retrieve or put objects\n in your Cloud Files account for as long or as short a time as you\n wish. This method is specifically for allowing users to retrieve\n or update an object.\n \n @param obj: The object that you wish to make temporarily public\n @type obj: L{Object}\n \n @param method: Which method you would like to allow, 'PUT' or 'GET'\n @type method: C{str}\n \n @param timeout: Time (in seconds) after which you want the TempURL\n to expire.\n @type timeout: C{int}\n \n @rtype: C{bool}\n \"\"\"\n self.connection._populate_hosts_and_request_paths()\n expires = int(time() + timeout)\n path = '%s/%s/%s' % (self.connection.request_path, obj.container.name, obj.name)\n try:\n key = self.ex_get_meta_data()['temp_url_key']\n assert key is not None\n except Exception:\n raise KeyError('You must first set the ' + 'X-Account-Meta-Temp-URL-Key header on your ' + 'Cloud Files account using ' + 'ex_set_account_metadata_temp_url_key before ' + 'you can use this method.')\n hmac_body = '%s\\n%s\\n%s' % (method, expires, path)\n sig = hmac.new(b(key), b(hmac_body), sha1).hexdigest()\n params = urlencode({'temp_url_sig': sig, 'temp_url_expires': expires})\n temp_url = 'https://%s/%s/%s?%s' % (self.connection.host + self.connection.request_path, obj.container.name, obj.name, params)\n return temp_url\n ", "context": "class CloudFilesStorageDriver(StorageDriverOpenStackDriverMixin):\n def ex_get_object_temp_url(self, obj, method='GET', timeout=60): ...\n def __init__(self, *args, **kwargs): ...\n def list_containers(self): ...\n def list_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def get_container_cdn_url(self, container): ...\n def get_object_cdn_url(self, obj): ...\n def enable_container_cdn(self, container, ex_ttl=None): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def delete_object(self, obj): ...\n def ex_purge_object_from_cdn(self, obj, email=None): ...\n def ex_get_meta_data(self): ...\n def ex_multipart_upload_object(self, file_path, container, object_name, chunk_size=33554432, extra=None, verify_hash=True): ...\n def ex_enable_static_website(self, container, index_file='index.html'): ...\n def ex_set_error_page(self, container, file_name='error.html'): ...\n def ex_set_account_metadata_temp_url_key(self, key): ...\n def _upload_object_part(self, container, object_name, part_number, iterator, verify_hash=True): ...\n def _upload_object_manifest(self, container, object_name, extra=None, verify_hash=True): ...\n def _get_more(self, last_key, value_dict): ...\n def _put_object(self, container, object_name, upload_func, upload_func_kwargs, extra=None, file_path=None, iterator=None, verify_hash=True): ...\n def _encode_container_name(self, name): ...\n def _encode_object_name(self, name): ...\n def _to_container_list(self, response): ...\n def _to_object_list(self, response, container): ...\n def _headers_to_container(self, name, headers): ...\n def _headers_to_object(self, name, container, headers): ...\n def _ex_connection_class_kwargs(self): ...\n\n name = 'CloudFiles'\n website = 'http://www.rackspace.com/'\n connectionCls = CloudFilesConnection\n hash_type = 'md5'\n supports_chunked_encoding = True\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/storage/drivers/local.py", "focal_class": null, "focal_method": "get_container", "tests": "import unittest\n\nclass Test_get_container(unittest.TestCase):\n def test_get_container_success(self):\n self.driver.create_container('test4')\n container = self.driver.get_container(container_name='test4')\n self.assertTrue(container.name, 'test4')\n container.delete()\n", "method_code": " def get_container(self, container_name):\n \"\"\"\n Return a container instance.\n \n @param container_name: Container name.\n @type container_name: C{str}\n \n @return: L{Container} instance.\n @rtype: L{Container}\n \"\"\"\n return self._make_container(container_name)\n ", "context": "class LocalStorageDriver(StorageDriver):\n def get_container(self, container_name): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None, **kwargs): ...\n def _make_path(self, path, ignore_existing=True): ...\n def _check_container_name(self, container_name): ...\n def _make_container(self, container_name): ...\n def _make_object(self, container, object_name): ...\n def iterate_containers(self): ...\n def _get_objects(self, container): ...\n def iterate_container_objects(self, container): ...\n def get_container_cdn_url(self, container, check=False): ...\n def get_object(self, container_name, object_name): ...\n def get_object_cdn_url(self, obj): ...\n def enable_container_cdn(self, container): ...\n def enable_object_cdn(self, obj): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def delete_object(self, obj): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n\n self.base_path = key\n\n connectionCls = Connection\n name = 'Local Storage'\n website = 'http://example.com'\n hash_type = 'md5'\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_get_container_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/storage/drivers/local.py", "focal_class": null, "focal_method": "create_container", "tests": "import unittest\n\nclass Test_create_container(unittest.TestCase):\n def test_create_container_invalid_name(self):\n try:\n self.driver.create_container(container_name='new/container')\n except InvalidContainerNameError:\n pass\n else:\n self.fail('Exception was not thrown')\n\n def test_create_container_already_exists(self):\n container = self.driver.create_container(container_name='new-container')\n try:\n self.driver.create_container(container_name='new-container')\n except ContainerAlreadyExistsError:\n pass\n else:\n self.fail('Exception was not thrown')\n self.driver.delete_container(container)\n\n def test_create_container_success(self):\n name = 'new_container'\n container = self.driver.create_container(container_name=name)\n self.assertEqual(container.name, name)\n self.driver.delete_container(container)\n", "method_code": " def create_container(self, container_name):\n \"\"\"\n Create a new container.\n \n @type container_name: C{str}\n @param container_name: Container name.\n \n @return: C{Container} instance on success.\n @rtype: L{Container}\n \"\"\"\n self._check_container_name(container_name)\n path = os.path.join(self.base_path, container_name)\n try:\n self._make_path(path, ignore_existing=False)\n except OSError:\n exp = sys.exc_info()[1]\n if exp.errno == errno.EEXIST:\n raise ContainerAlreadyExistsError(value='Container with this name already exists. The name must be unique among all the containers in the system', container_name=container_name, driver=self)\n else:\n raise LibcloudError('Error creating container %s' % container_name, driver=self)\n except Exception:\n raise LibcloudError('Error creating container %s' % container_name, driver=self)\n return self._make_container(container_name)\n ", "context": "class LocalStorageDriver(StorageDriver):\n def create_container(self, container_name): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None, **kwargs): ...\n def _make_path(self, path, ignore_existing=True): ...\n def _check_container_name(self, container_name): ...\n def _make_container(self, container_name): ...\n def _make_object(self, container, object_name): ...\n def iterate_containers(self): ...\n def _get_objects(self, container): ...\n def iterate_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_container_cdn_url(self, container, check=False): ...\n def get_object(self, container_name, object_name): ...\n def get_object_cdn_url(self, obj): ...\n def enable_container_cdn(self, container): ...\n def enable_object_cdn(self, obj): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def delete_object(self, obj): ...\n def delete_container(self, container): ...\n\n self.base_path = key\n\n connectionCls = Connection\n name = 'Local Storage'\n website = 'http://example.com'\n hash_type = 'md5'\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_container_invalid_name", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000901.py"} {"focal_file": "libcloud/storage/drivers/local.py", "focal_class": null, "focal_method": "delete_container", "tests": "import unittest\n\nclass Test_delete_container(unittest.TestCase):\n def test_delete_container_doesnt_exist(self):\n container = Container(name='new_container', extra=None, driver=self.driver)\n try:\n self.driver.delete_container(container=container)\n except ContainerDoesNotExistError:\n pass\n else:\n self.fail('Exception was not thrown')\n\n def test_delete_container_not_empty(self):\n tmppath = self.make_tmp_file()\n container = self.driver.create_container('test6')\n obj = container.upload_object(tmppath, 'test')\n try:\n self.driver.delete_container(container=container)\n except ContainerIsNotEmptyError:\n pass\n else:\n self.fail('Exception was not thrown')\n obj.delete()\n self.remove_tmp_file(tmppath)\n self.assertTrue(self.driver.delete_container(container=container))\n\n def test_delete_container_not_found(self):\n container = Container(name='foo_bar_container', extra={}, driver=self.driver)\n try:\n self.driver.delete_container(container=container)\n except ContainerDoesNotExistError:\n pass\n else:\n self.fail('Container does not exist but an exception was not' + 'thrown')\n\n def test_delete_container_success(self):\n container = self.driver.create_container('test7')\n self.assertTrue(self.driver.delete_container(container=container))\n", "method_code": " def delete_container(self, container):\n \"\"\"\n Delete a container.\n \n @type container: L{Container}\n @param container: Container instance\n \n @return: True on success, False otherwise.\n @rtype: C{bool}\n \"\"\"\n for obj in self._get_objects(container):\n raise ContainerIsNotEmptyError(value='Container is not empty', container_name=container.name, driver=self)\n path = self.get_container_cdn_url(container, check=True)\n with LockLocalStorage(path) as lock:\n try:\n shutil.rmtree(path)\n except Exception:\n return False\n return True\n ", "context": "class LocalStorageDriver(StorageDriver):\n def delete_container(self, container): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None, **kwargs): ...\n def _make_path(self, path, ignore_existing=True): ...\n def _check_container_name(self, container_name): ...\n def _make_container(self, container_name): ...\n def _make_object(self, container, object_name): ...\n def iterate_containers(self): ...\n def _get_objects(self, container): ...\n def iterate_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_container_cdn_url(self, container, check=False): ...\n def get_object(self, container_name, object_name): ...\n def get_object_cdn_url(self, obj): ...\n def enable_container_cdn(self, container): ...\n def enable_object_cdn(self, obj): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def delete_object(self, obj): ...\n def create_container(self, container_name): ...\n\n self.base_path = key\n\n connectionCls = Connection\n name = 'Local Storage'\n website = 'http://example.com'\n hash_type = 'md5'\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_delete_container_doesnt_exist", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000902.py"} {"focal_file": "libcloud/storage/drivers/local.py", "focal_class": null, "focal_method": "download_object", "tests": "import unittest\n\nclass Test_download_object(unittest.TestCase):\n def test_download_object_success(self):\n tmppath = self.make_tmp_file()\n container = self.driver.create_container('test6')\n obj = container.upload_object(tmppath, 'test')\n destination_path = tmppath + '.temp'\n result = self.driver.download_object(obj=obj, destination_path=destination_path, overwrite_existing=False, delete_on_failure=True)\n self.assertTrue(result)\n obj.delete()\n container.delete()\n self.remove_tmp_file(tmppath)\n os.unlink(destination_path)\n\n def test_download_object_and_overwrite(self):\n tmppath = self.make_tmp_file()\n container = self.driver.create_container('test6')\n obj = container.upload_object(tmppath, 'test')\n destination_path = tmppath + '.temp'\n result = self.driver.download_object(obj=obj, destination_path=destination_path, overwrite_existing=False, delete_on_failure=True)\n self.assertTrue(result)\n try:\n self.driver.download_object(obj=obj, destination_path=destination_path, overwrite_existing=False, delete_on_failure=True)\n except LibcloudError:\n pass\n else:\n self.fail('Exception was not thrown')\n result = self.driver.download_object(obj=obj, destination_path=destination_path, overwrite_existing=True, delete_on_failure=True)\n self.assertTrue(result)\n obj.delete()\n container.delete()\n self.remove_tmp_file(tmppath)\n os.unlink(destination_path)\n", "method_code": " def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True):\n \"\"\"\n Download an object to the specified destination path.\n \n @param obj: Object instance.\n @type obj: L{Object}\n \n @param destination_path: Full path to a file or a directory where the\n incoming file will be saved.\n @type destination_path: C{str}\n \n @param overwrite_existing: True to overwrite an existing file,\n defaults to False.\n @type overwrite_existing: C{bool}\n \n @param delete_on_failure: True to delete a partially downloaded file if\n the download was not successful (hash mismatch / file size).\n @type delete_on_failure: C{bool}\n \n @return: True if an object has been successfully downloaded, False\n otherwise.\n @rtype: C{bool}\n \"\"\"\n obj_path = self.get_object_cdn_url(obj)\n base_name = os.path.basename(destination_path)\n if not base_name and (not os.path.exists(destination_path)):\n raise LibcloudError(value='Path %s does not exist' % destination_path, driver=self)\n if not base_name:\n file_path = os.path.join(destination_path, obj.name)\n else:\n file_path = destination_path\n if os.path.exists(file_path) and (not overwrite_existing):\n raise LibcloudError(value='File %s already exists, but ' % file_path + 'overwrite_existing=False', driver=self)\n try:\n shutil.copy(obj_path, file_path)\n except IOError:\n if delete_on_failure:\n try:\n os.unlink(file_path)\n except Exception:\n pass\n return False\n return True\n ", "context": "class LocalStorageDriver(StorageDriver):\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None, **kwargs): ...\n def _make_path(self, path, ignore_existing=True): ...\n def _check_container_name(self, container_name): ...\n def _make_container(self, container_name): ...\n def _make_object(self, container, object_name): ...\n def iterate_containers(self): ...\n def _get_objects(self, container): ...\n def iterate_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_container_cdn_url(self, container, check=False): ...\n def get_object(self, container_name, object_name): ...\n def get_object_cdn_url(self, obj): ...\n def enable_container_cdn(self, container): ...\n def enable_object_cdn(self, obj): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def delete_object(self, obj): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n\n self.base_path = key\n\n connectionCls = Connection\n name = 'Local Storage'\n website = 'http://example.com'\n hash_type = 'md5'\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_download_object_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000903.py"} {"focal_file": "libcloud/storage/drivers/local.py", "focal_class": null, "focal_method": "download_object_as_stream", "tests": "import unittest\n\nclass Test_download_object_as_stream(unittest.TestCase):\n def test_download_object_as_stream_success(self):\n tmppath = self.make_tmp_file()\n container = self.driver.create_container('test6')\n obj = container.upload_object(tmppath, 'test')\n stream = self.driver.download_object_as_stream(obj=obj, chunk_size=1024)\n self.assertTrue(hasattr(stream, '__iter__'))\n data = ''\n for buff in stream:\n data += buff.decode('utf-8')\n self.assertTrue(len(data), 4096)\n obj.delete()\n container.delete()\n self.remove_tmp_file(tmppath)\n", "method_code": " def download_object_as_stream(self, obj, chunk_size=None):\n \"\"\"\n Return a generator which yields object data.\n \n @param obj: Object instance\n @type obj: L{Object}\n \n @param chunk_size: Optional chunk size (in bytes).\n @type chunk_size: C{int}\n \n @rtype: C{object}\n \"\"\"\n path = self.get_object_cdn_url(obj)\n with open(path) as obj_file:\n for data in read_in_chunks(obj_file, chunk_size=chunk_size):\n yield data\n ", "context": "class LocalStorageDriver(StorageDriver):\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def __init__(self, key, secret=None, secure=True, host=None, port=None, **kwargs): ...\n def _make_path(self, path, ignore_existing=True): ...\n def _check_container_name(self, container_name): ...\n def _make_container(self, container_name): ...\n def _make_object(self, container, object_name): ...\n def iterate_containers(self): ...\n def _get_objects(self, container): ...\n def iterate_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_container_cdn_url(self, container, check=False): ...\n def get_object(self, container_name, object_name): ...\n def get_object_cdn_url(self, obj): ...\n def enable_container_cdn(self, container): ...\n def enable_object_cdn(self, obj): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None): ...\n def delete_object(self, obj): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n\n self.base_path = key\n\n connectionCls = Connection\n name = 'Local Storage'\n website = 'http://example.com'\n hash_type = 'md5'\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_download_object_as_stream_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000904.py"} {"focal_file": "libcloud/storage/drivers/s3.py", "focal_class": null, "focal_method": "get_container", "tests": "import unittest\n\nclass Test_get_container(unittest.TestCase):\n def test_get_container_success(self):\n self.mock_response_klass.type = 'list_containers'\n container = self.driver.get_container(container_name='test1')\n self.assertTrue(container.name, 'test1')\n", "method_code": " def get_container(self, container_name):\n containers = self.list_containers()\n try:\n container = [c for c in containers if c.name == container_name][0]\n except IndexError:\n raise ContainerDoesNotExistError(value=None, driver=self, container_name=container_name)\n return container\n ", "context": "class S3StorageDriver(StorageDriver):\n def get_container(self, container_name): ...\n def iterate_containers(self): ...\n def iterate_container_objects(self, container): ...\n def get_object(self, container_name, object_name): ...\n def _get_container_path(self, container): ...\n def _get_object_path(self, container, object_name): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True, ex_storage_class=None): ...\n def _upload_multipart(self, response, data, iterator, container, object_name, calculate_hash=True): ...\n def _upload_from_iterator(self, iterator, object_path, upload_id, calculate_hash=True): ...\n def _commit_multipart(self, object_path, upload_id, chunks): ...\n def _abort_multipart(self, object_path, upload_id): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None, ex_storage_class=None): ...\n def delete_object(self, obj): ...\n def ex_iterate_multipart_uploads(self, container, prefix=None, delimiter=None): ...\n def ex_cleanup_all_multipart_uploads(self, container, prefix=None): ...\n def _clean_object_name(self, name): ...\n def _put_object(self, container, object_name, upload_func, upload_func_kwargs, method='PUT', query_args=None, extra=None, file_path=None, iterator=None, verify_hash=True, storage_class=None): ...\n def _to_containers(self, obj, xpath): ...\n def _to_objs(self, obj, xpath, container): ...\n def _to_container(self, element): ...\n def _headers_to_object(self, object_name, container, headers): ...\n def _to_obj(self, element, container): ...\n\n name = 'Amazon S3 (standard)'\n website = 'http://aws.amazon.com/s3/'\n connectionCls = S3Connection\n hash_type = 'md5'\n supports_chunked_encoding = False\n supports_s3_multipart_upload = True\n ex_location_name = ''\n namespace = NAMESPACE\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_get_container_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/storage/drivers/s3.py", "focal_class": null, "focal_method": "create_container", "tests": "import unittest\n\nclass Test_create_container(unittest.TestCase):\n def test_create_container_invalid_name(self):\n self.mock_response_klass.type = 'INVALID_NAME'\n try:\n self.driver.create_container(container_name='new_container')\n except InvalidContainerNameError:\n pass\n else:\n self.fail('Exception was not thrown')\n\n def test_create_container_already_exists(self):\n self.mock_response_klass.type = 'ALREADY_EXISTS'\n try:\n self.driver.create_container(container_name='new-container')\n except InvalidContainerNameError:\n pass\n else:\n self.fail('Exception was not thrown')\n\n def test_create_container_success(self):\n self.mock_response_klass.type = None\n name = 'new_container'\n container = self.driver.create_container(container_name=name)\n self.assertEqual(container.name, name)\n", "method_code": " def create_container(self, container_name):\n if self.ex_location_name:\n root = Element('CreateBucketConfiguration')\n child = SubElement(root, 'LocationConstraint')\n child.text = self.ex_location_name\n data = tostring(root)\n else:\n data = ''\n response = self.connection.request('/%s' % container_name, data=data, method='PUT')\n if response.status == httplib.OK:\n container = Container(name=container_name, extra=None, driver=self)\n return container\n elif response.status == httplib.CONFLICT:\n raise InvalidContainerNameError(value='Container with this name already exists. The name must be unique among all the containers in the system', container_name=container_name, driver=self)\n elif response.status == httplib.BAD_REQUEST:\n raise InvalidContainerNameError(value='Container name contains ' + 'invalid characters.', container_name=container_name, driver=self)\n raise LibcloudError('Unexpected status code: %s' % response.status, driver=self)\n ", "context": "class S3StorageDriver(StorageDriver):\n def create_container(self, container_name): ...\n def iterate_containers(self): ...\n def iterate_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def _get_container_path(self, container): ...\n def _get_object_path(self, container, object_name): ...\n def delete_container(self, container): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True, ex_storage_class=None): ...\n def _upload_multipart(self, response, data, iterator, container, object_name, calculate_hash=True): ...\n def _upload_from_iterator(self, iterator, object_path, upload_id, calculate_hash=True): ...\n def _commit_multipart(self, object_path, upload_id, chunks): ...\n def _abort_multipart(self, object_path, upload_id): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None, ex_storage_class=None): ...\n def delete_object(self, obj): ...\n def ex_iterate_multipart_uploads(self, container, prefix=None, delimiter=None): ...\n def ex_cleanup_all_multipart_uploads(self, container, prefix=None): ...\n def _clean_object_name(self, name): ...\n def _put_object(self, container, object_name, upload_func, upload_func_kwargs, method='PUT', query_args=None, extra=None, file_path=None, iterator=None, verify_hash=True, storage_class=None): ...\n def _to_containers(self, obj, xpath): ...\n def _to_objs(self, obj, xpath, container): ...\n def _to_container(self, element): ...\n def _headers_to_object(self, object_name, container, headers): ...\n def _to_obj(self, element, container): ...\n\n name = 'Amazon S3 (standard)'\n website = 'http://aws.amazon.com/s3/'\n connectionCls = S3Connection\n hash_type = 'md5'\n supports_chunked_encoding = False\n supports_s3_multipart_upload = True\n ex_location_name = ''\n namespace = NAMESPACE\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_create_container_invalid_name", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000906.py"} {"focal_file": "libcloud/storage/drivers/s3.py", "focal_class": null, "focal_method": "delete_container", "tests": "import unittest\n\nclass Test_delete_container(unittest.TestCase):\n def test_delete_container_doesnt_exist(self):\n container = Container(name='new_container', extra=None, driver=self.driver)\n self.mock_response_klass.type = 'DOESNT_EXIST'\n try:\n self.driver.delete_container(container=container)\n except ContainerDoesNotExistError:\n pass\n else:\n self.fail('Exception was not thrown')\n\n def test_delete_container_not_empty(self):\n container = Container(name='new_container', extra=None, driver=self.driver)\n self.mock_response_klass.type = 'NOT_EMPTY'\n try:\n self.driver.delete_container(container=container)\n except ContainerIsNotEmptyError:\n pass\n else:\n self.fail('Exception was not thrown')\n self.mock_response_klass.type = None\n self.assertTrue(self.driver.delete_container(container=container))\n\n def test_delete_container_not_found(self):\n self.mock_response_klass.type = 'NOT_FOUND'\n container = Container(name='foo_bar_container', extra={}, driver=self.driver)\n try:\n self.driver.delete_container(container=container)\n except ContainerDoesNotExistError:\n pass\n else:\n self.fail('Container does not exist but an exception was not' + 'thrown')\n\n def test_delete_container_success(self):\n self.mock_response_klass.type = None\n container = Container(name='new_container', extra=None, driver=self.driver)\n self.assertTrue(self.driver.delete_container(container=container))\n", "method_code": " def delete_container(self, container):\n response = self.connection.request('/%s' % container.name, method='DELETE')\n if response.status == httplib.NO_CONTENT:\n return True\n elif response.status == httplib.CONFLICT:\n raise ContainerIsNotEmptyError(value='Container must be empty before it can be deleted.', container_name=container.name, driver=self)\n elif response.status == httplib.NOT_FOUND:\n raise ContainerDoesNotExistError(value=None, driver=self, container_name=container.name)\n return False\n ", "context": "class S3StorageDriver(StorageDriver):\n def delete_container(self, container): ...\n def iterate_containers(self): ...\n def iterate_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def _get_container_path(self, container): ...\n def _get_object_path(self, container, object_name): ...\n def create_container(self, container_name): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True, ex_storage_class=None): ...\n def _upload_multipart(self, response, data, iterator, container, object_name, calculate_hash=True): ...\n def _upload_from_iterator(self, iterator, object_path, upload_id, calculate_hash=True): ...\n def _commit_multipart(self, object_path, upload_id, chunks): ...\n def _abort_multipart(self, object_path, upload_id): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None, ex_storage_class=None): ...\n def delete_object(self, obj): ...\n def ex_iterate_multipart_uploads(self, container, prefix=None, delimiter=None): ...\n def ex_cleanup_all_multipart_uploads(self, container, prefix=None): ...\n def _clean_object_name(self, name): ...\n def _put_object(self, container, object_name, upload_func, upload_func_kwargs, method='PUT', query_args=None, extra=None, file_path=None, iterator=None, verify_hash=True, storage_class=None): ...\n def _to_containers(self, obj, xpath): ...\n def _to_objs(self, obj, xpath, container): ...\n def _to_container(self, element): ...\n def _headers_to_object(self, object_name, container, headers): ...\n def _to_obj(self, element, container): ...\n\n name = 'Amazon S3 (standard)'\n website = 'http://aws.amazon.com/s3/'\n connectionCls = S3Connection\n hash_type = 'md5'\n supports_chunked_encoding = False\n supports_s3_multipart_upload = True\n ex_location_name = ''\n namespace = NAMESPACE\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_delete_container_doesnt_exist", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000907.py"} {"focal_file": "libcloud/storage/drivers/s3.py", "focal_class": null, "focal_method": "download_object", "tests": "import unittest\n\nclass Test_download_object(unittest.TestCase):\n def test_download_object_success(self):\n container = Container(name='foo_bar_container', extra={}, driver=self.driver)\n obj = Object(name='foo_bar_object', size=1000, hash=None, extra={}, container=container, meta_data=None, driver=self.driver_type)\n destination_path = os.path.abspath(__file__) + '.temp'\n result = self.driver.download_object(obj=obj, destination_path=destination_path, overwrite_existing=False, delete_on_failure=True)\n self.assertTrue(result)\n", "method_code": " def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True):\n obj_path = self._get_object_path(obj.container, obj.name)\n response = self.connection.request(obj_path, method='GET', raw=True)\n return self._get_object(obj=obj, callback=self._save_object, response=response, callback_kwargs={'obj': obj, 'response': response.response, 'destination_path': destination_path, 'overwrite_existing': overwrite_existing, 'delete_on_failure': delete_on_failure}, success_status_code=httplib.OK)\n ", "context": "class S3StorageDriver(StorageDriver):\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def iterate_containers(self): ...\n def iterate_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def _get_container_path(self, container): ...\n def _get_object_path(self, container, object_name): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True, ex_storage_class=None): ...\n def _upload_multipart(self, response, data, iterator, container, object_name, calculate_hash=True): ...\n def _upload_from_iterator(self, iterator, object_path, upload_id, calculate_hash=True): ...\n def _commit_multipart(self, object_path, upload_id, chunks): ...\n def _abort_multipart(self, object_path, upload_id): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None, ex_storage_class=None): ...\n def delete_object(self, obj): ...\n def ex_iterate_multipart_uploads(self, container, prefix=None, delimiter=None): ...\n def ex_cleanup_all_multipart_uploads(self, container, prefix=None): ...\n def _clean_object_name(self, name): ...\n def _put_object(self, container, object_name, upload_func, upload_func_kwargs, method='PUT', query_args=None, extra=None, file_path=None, iterator=None, verify_hash=True, storage_class=None): ...\n def _to_containers(self, obj, xpath): ...\n def _to_objs(self, obj, xpath, container): ...\n def _to_container(self, element): ...\n def _headers_to_object(self, object_name, container, headers): ...\n def _to_obj(self, element, container): ...\n\n name = 'Amazon S3 (standard)'\n website = 'http://aws.amazon.com/s3/'\n connectionCls = S3Connection\n hash_type = 'md5'\n supports_chunked_encoding = False\n supports_s3_multipart_upload = True\n ex_location_name = ''\n namespace = NAMESPACE\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_download_object_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/storage/drivers/s3.py", "focal_class": null, "focal_method": "download_object_as_stream", "tests": "import unittest\n\nclass Test_download_object_as_stream(unittest.TestCase):\n def test_download_object_as_stream_success(self):\n container = Container(name='foo_bar_container', extra={}, driver=self.driver)\n obj = Object(name='foo_bar_object', size=1000, hash=None, extra={}, container=container, meta_data=None, driver=self.driver_type)\n stream = self.driver.download_object_as_stream(obj=obj, chunk_size=None)\n self.assertTrue(hasattr(stream, '__iter__'))\n", "method_code": " def download_object_as_stream(self, obj, chunk_size=None):\n obj_path = self._get_object_path(obj.container, obj.name)\n response = self.connection.request(obj_path, method='GET', raw=True)\n return self._get_object(obj=obj, callback=read_in_chunks, response=response, callback_kwargs={'iterator': response.response, 'chunk_size': chunk_size}, success_status_code=httplib.OK)\n ", "context": "class S3StorageDriver(StorageDriver):\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def iterate_containers(self): ...\n def iterate_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def _get_container_path(self, container): ...\n def _get_object_path(self, container, object_name): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True, ex_storage_class=None): ...\n def _upload_multipart(self, response, data, iterator, container, object_name, calculate_hash=True): ...\n def _upload_from_iterator(self, iterator, object_path, upload_id, calculate_hash=True): ...\n def _commit_multipart(self, object_path, upload_id, chunks): ...\n def _abort_multipart(self, object_path, upload_id): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None, ex_storage_class=None): ...\n def delete_object(self, obj): ...\n def ex_iterate_multipart_uploads(self, container, prefix=None, delimiter=None): ...\n def ex_cleanup_all_multipart_uploads(self, container, prefix=None): ...\n def _clean_object_name(self, name): ...\n def _put_object(self, container, object_name, upload_func, upload_func_kwargs, method='PUT', query_args=None, extra=None, file_path=None, iterator=None, verify_hash=True, storage_class=None): ...\n def _to_containers(self, obj, xpath): ...\n def _to_objs(self, obj, xpath, container): ...\n def _to_container(self, element): ...\n def _headers_to_object(self, object_name, container, headers): ...\n def _to_obj(self, element, container): ...\n\n name = 'Amazon S3 (standard)'\n website = 'http://aws.amazon.com/s3/'\n connectionCls = S3Connection\n hash_type = 'md5'\n supports_chunked_encoding = False\n supports_s3_multipart_upload = True\n ex_location_name = ''\n namespace = NAMESPACE\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_download_object_as_stream_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [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": "libcloud/storage/drivers/s3.py", "focal_class": null, "focal_method": "upload_object", "tests": "import unittest\n\nclass Test_upload_object(unittest.TestCase):\n def test_upload_object_success(self):\n\n def upload_file(self, response, file_path, chunked=False, calculate_hash=True):\n return (True, '0cc175b9c0f1b6a831c399e269772661', 1000)\n old_func = self.driver_type._upload_file\n self.driver_type._upload_file = upload_file\n file_path = os.path.abspath(__file__)\n container = Container(name='foo_bar_container', extra={}, driver=self.driver)\n object_name = 'foo_test_upload'\n extra = {'meta_data': {'some-value': 'foobar'}}\n obj = self.driver.upload_object(file_path=file_path, container=container, object_name=object_name, extra=extra, verify_hash=True)\n self.assertEqual(obj.name, 'foo_test_upload')\n self.assertEqual(obj.size, 1000)\n self.assertTrue('some-value' in obj.meta_data)\n self.driver_type._upload_file = old_func\n", "method_code": " def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True, ex_storage_class=None):\n \"\"\"\n @inherits: L{StorageDriver.upload_object}\n \n @param ex_storage_class: Storage class\n @type ex_storage_class: C{str}\n \"\"\"\n upload_func = self._upload_file\n upload_func_kwargs = {'file_path': file_path}\n return self._put_object(container=container, object_name=object_name, upload_func=upload_func, upload_func_kwargs=upload_func_kwargs, extra=extra, file_path=file_path, verify_hash=verify_hash, storage_class=ex_storage_class)\n ", "context": "class S3StorageDriver(StorageDriver):\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True, ex_storage_class=None): ...\n def iterate_containers(self): ...\n def iterate_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def _get_container_path(self, container): ...\n def _get_object_path(self, container, object_name): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def _upload_multipart(self, response, data, iterator, container, object_name, calculate_hash=True): ...\n def _upload_from_iterator(self, iterator, object_path, upload_id, calculate_hash=True): ...\n def _commit_multipart(self, object_path, upload_id, chunks): ...\n def _abort_multipart(self, object_path, upload_id): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None, ex_storage_class=None): ...\n def delete_object(self, obj): ...\n def ex_iterate_multipart_uploads(self, container, prefix=None, delimiter=None): ...\n def ex_cleanup_all_multipart_uploads(self, container, prefix=None): ...\n def _clean_object_name(self, name): ...\n def _put_object(self, container, object_name, upload_func, upload_func_kwargs, method='PUT', query_args=None, extra=None, file_path=None, iterator=None, verify_hash=True, storage_class=None): ...\n def _to_containers(self, obj, xpath): ...\n def _to_objs(self, obj, xpath, container): ...\n def _to_container(self, element): ...\n def _headers_to_object(self, object_name, container, headers): ...\n def _to_obj(self, element, container): ...\n\n name = 'Amazon S3 (standard)'\n website = 'http://aws.amazon.com/s3/'\n connectionCls = S3Connection\n hash_type = 'md5'\n supports_chunked_encoding = False\n supports_s3_multipart_upload = True\n ex_location_name = ''\n namespace = NAMESPACE\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_upload_object_success", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000910.py"} {"focal_file": "libcloud/storage/drivers/s3.py", "focal_class": null, "focal_method": "upload_object_via_stream", "tests": "import unittest\n\nclass Test_upload_object_via_stream(unittest.TestCase):\n def test_upload_small_object_via_stream(self):\n if self.driver.supports_s3_multipart_upload:\n self.mock_raw_response_klass.type = 'MULTIPART'\n self.mock_response_klass.type = 'MULTIPART'\n else:\n self.mock_raw_response_klass.type = None\n self.mock_response_klass.type = None\n container = Container(name='foo_bar_container', extra={}, driver=self.driver)\n object_name = 'foo_test_stream_data'\n iterator = DummyIterator(data=['2', '3', '5'])\n extra = {'content_type': 'text/plain'}\n obj = self.driver.upload_object_via_stream(container=container, object_name=object_name, iterator=iterator, extra=extra)\n self.assertEqual(obj.name, object_name)\n self.assertEqual(obj.size, 3)\n\n def test_upload_big_object_via_stream(self):\n if self.driver.supports_s3_multipart_upload:\n self.mock_raw_response_klass.type = 'MULTIPART'\n self.mock_response_klass.type = 'MULTIPART'\n else:\n self.mock_raw_response_klass.type = None\n self.mock_response_klass.type = None\n container = Container(name='foo_bar_container', extra={}, driver=self.driver)\n object_name = 'foo_test_stream_data'\n iterator = DummyIterator(data=['2' * CHUNK_SIZE, '3' * CHUNK_SIZE, '5'])\n extra = {'content_type': 'text/plain'}\n obj = self.driver.upload_object_via_stream(container=container, object_name=object_name, iterator=iterator, extra=extra)\n self.assertEqual(obj.name, object_name)\n self.assertEqual(obj.size, CHUNK_SIZE * 2 + 1)\n\n def test_upload_object_via_stream_abort(self):\n if not self.driver.supports_s3_multipart_upload:\n return\n self.mock_raw_response_klass.type = 'MULTIPART'\n self.mock_response_klass.type = 'MULTIPART'\n\n def _faulty_iterator():\n for i in range(0, 5):\n yield str(i)\n raise RuntimeError('Error in fetching data')\n container = Container(name='foo_bar_container', extra={}, driver=self.driver)\n object_name = 'foo_test_stream_data'\n iterator = _faulty_iterator()\n extra = {'content_type': 'text/plain'}\n try:\n obj = self.driver.upload_object_via_stream(container=container, object_name=object_name, iterator=iterator, extra=extra)\n except Exception:\n pass\n return\n", "method_code": " def upload_object_via_stream(self, iterator, container, object_name, extra=None, ex_storage_class=None):\n \"\"\"\n @inherits: L{StorageDriver.upload_object_via_stream}\n \n @param ex_storage_class: Storage class\n @type ex_storage_class: C{str}\n \"\"\"\n method = 'PUT'\n params = None\n if self.supports_s3_multipart_upload:\n upload_func = self._upload_multipart\n upload_func_kwargs = {'iterator': iterator, 'container': container, 'object_name': object_name}\n method = 'POST'\n iterator = iter('')\n params = 'uploads'\n elif self.supports_chunked_encoding:\n upload_func = self._stream_data\n upload_func_kwargs = {'iterator': iterator}\n else:\n upload_func = self._upload_data\n upload_func_kwargs = {}\n return self._put_object(container=container, object_name=object_name, upload_func=upload_func, upload_func_kwargs=upload_func_kwargs, extra=extra, method=method, query_args=params, iterator=iterator, verify_hash=False, storage_class=ex_storage_class)\n ", "context": "class S3StorageDriver(StorageDriver):\n def upload_object_via_stream(self, iterator, container, object_name, extra=None, ex_storage_class=None): ...\n def iterate_containers(self): ...\n def iterate_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def _get_container_path(self, container): ...\n def _get_object_path(self, container, object_name): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True, ex_storage_class=None): ...\n def _upload_multipart(self, response, data, iterator, container, object_name, calculate_hash=True): ...\n def _upload_from_iterator(self, iterator, object_path, upload_id, calculate_hash=True): ...\n def _commit_multipart(self, object_path, upload_id, chunks): ...\n def _abort_multipart(self, object_path, upload_id): ...\n def delete_object(self, obj): ...\n def ex_iterate_multipart_uploads(self, container, prefix=None, delimiter=None): ...\n def ex_cleanup_all_multipart_uploads(self, container, prefix=None): ...\n def _clean_object_name(self, name): ...\n def _put_object(self, container, object_name, upload_func, upload_func_kwargs, method='PUT', query_args=None, extra=None, file_path=None, iterator=None, verify_hash=True, storage_class=None): ...\n def _to_containers(self, obj, xpath): ...\n def _to_objs(self, obj, xpath, container): ...\n def _to_container(self, element): ...\n def _headers_to_object(self, object_name, container, headers): ...\n def _to_obj(self, element, container): ...\n\n name = 'Amazon S3 (standard)'\n website = 'http://aws.amazon.com/s3/'\n connectionCls = S3Connection\n hash_type = 'md5'\n supports_chunked_encoding = False\n supports_s3_multipart_upload = True\n ex_location_name = ''\n namespace = NAMESPACE\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_upload_small_object_via_stream", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000911.py"} {"focal_file": "libcloud/storage/drivers/s3.py", "focal_class": null, "focal_method": "ex_iterate_multipart_uploads", "tests": "import unittest\n\nclass Test_ex_iterate_multipart_uploads(unittest.TestCase):\n def test_s3_list_multipart_uploads(self):\n if not self.driver.supports_s3_multipart_upload:\n return\n self.mock_response_klass.type = 'LIST_MULTIPART'\n S3StorageDriver.RESPONSES_PER_REQUEST = 2\n container = Container(name='foo_bar_container', extra={}, driver=self.driver)\n for upload in self.driver.ex_iterate_multipart_uploads(container):\n self.assertNotEqual(upload.key, None)\n self.assertNotEqual(upload.id, None)\n self.assertNotEqual(upload.created_at, None)\n self.assertNotEqual(upload.owner, None)\n self.assertNotEqual(upload.initiator, None)\n", "method_code": " def ex_iterate_multipart_uploads(self, container, prefix=None, delimiter=None):\n \"\"\"\n Extension method for listing all in-progress S3 multipart uploads.\n \n Each multipart upload which has not been committed or aborted is\n considered in-progress.\n \n @param container: The container holding the uploads\n @type container: L{Container}\n \n @keyword prefix: Print only uploads of objects with this prefix\n @type prefix: C{str}\n \n @keyword delimiter: The object/key names are grouped based on\n being split by this delimiter\n @type delimiter: C{str}\n \n @return: A generator of S3MultipartUpload instances.\n @rtype: C{generator} of L{S3MultipartUpload}\n \"\"\"\n if not self.supports_s3_multipart_upload:\n raise LibcloudError('Feature not supported', driver=self)\n request_path = '%s/?uploads' % self._get_container_path(container)\n params = {'max-uploads': RESPONSES_PER_REQUEST}\n if prefix:\n params['prefix'] = prefix\n if delimiter:\n params['delimiter'] = delimiter\n finder = lambda node, text: node.findtext(fixxpath(xpath=text, namespace=self.namespace))\n while True:\n response = self.connection.request(request_path, params=params)\n if response.status != httplib.OK:\n raise LibcloudError('Error fetching multipart uploads. Got code: %s' % response.status, driver=self)\n body = response.parse_body()\n for node in body.findall(fixxpath(xpath='Upload', namespace=self.namespace)):\n initiator = node.find(fixxpath(xpath='Initiator', namespace=self.namespace))\n owner = node.find(fixxpath(xpath='Owner', namespace=self.namespace))\n key = finder(node, 'Key')\n upload_id = finder(node, 'UploadId')\n created_at = finder(node, 'Initiated')\n initiator = finder(initiator, 'DisplayName')\n owner = finder(owner, 'DisplayName')\n yield S3MultipartUpload(key, upload_id, created_at, initiator, owner)\n is_truncated = body.findtext(fixxpath(xpath='IsTruncated', namespace=self.namespace))\n if is_truncated.lower() == 'false':\n break\n upload_marker = body.findtext(fixxpath(xpath='NextUploadIdMarker', namespace=self.namespace))\n key_marker = body.findtext(fixxpath(xpath='NextKeyMarker', namespace=self.namespace))\n params['key-marker'] = key_marker\n params['upload-id-marker'] = upload_marker\n ", "context": "class S3StorageDriver(StorageDriver):\n def ex_iterate_multipart_uploads(self, container, prefix=None, delimiter=None): ...\n def iterate_containers(self): ...\n def iterate_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def _get_container_path(self, container): ...\n def _get_object_path(self, container, object_name): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True, ex_storage_class=None): ...\n def _upload_multipart(self, response, data, iterator, container, object_name, calculate_hash=True): ...\n def _upload_from_iterator(self, iterator, object_path, upload_id, calculate_hash=True): ...\n def _commit_multipart(self, object_path, upload_id, chunks): ...\n def _abort_multipart(self, object_path, upload_id): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None, ex_storage_class=None): ...\n def delete_object(self, obj): ...\n def ex_cleanup_all_multipart_uploads(self, container, prefix=None): ...\n def _clean_object_name(self, name): ...\n def _put_object(self, container, object_name, upload_func, upload_func_kwargs, method='PUT', query_args=None, extra=None, file_path=None, iterator=None, verify_hash=True, storage_class=None): ...\n def _to_containers(self, obj, xpath): ...\n def _to_objs(self, obj, xpath, container): ...\n def _to_container(self, element): ...\n def _headers_to_object(self, object_name, container, headers): ...\n def _to_obj(self, element, container): ...\n\n name = 'Amazon S3 (standard)'\n website = 'http://aws.amazon.com/s3/'\n connectionCls = S3Connection\n hash_type = 'md5'\n supports_chunked_encoding = False\n supports_s3_multipart_upload = True\n ex_location_name = ''\n namespace = NAMESPACE\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_s3_list_multipart_uploads", "smells": [1, 0, 0, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000912.py"} {"focal_file": "libcloud/storage/drivers/s3.py", "focal_class": null, "focal_method": "ex_cleanup_all_multipart_uploads", "tests": "import unittest\n\nclass Test_ex_cleanup_all_multipart_uploads(unittest.TestCase):\n def test_s3_abort_multipart_uploads(self):\n if not self.driver.supports_s3_multipart_upload:\n return\n self.mock_response_klass.type = 'LIST_MULTIPART'\n S3StorageDriver.RESPONSES_PER_REQUEST = 2\n container = Container(name='foo_bar_container', extra={}, driver=self.driver)\n self.driver.ex_cleanup_all_multipart_uploads(container)\n", "method_code": " def ex_cleanup_all_multipart_uploads(self, container, prefix=None):\n \"\"\"\n Extension method for removing all partially completed S3 multipart\n uploads.\n \n @param container: The container holding the uploads\n @type container: L{Container}\n \n @keyword prefix: Delete only uploads of objects with this prefix\n @type prefix: C{str}\n \"\"\"\n for upload in self.ex_iterate_multipart_uploads(container, prefix, delimiter=None):\n object_path = '/%s/%s' % (container.name, upload.key)\n self._abort_multipart(object_path, upload.id)\n ", "context": "class S3StorageDriver(StorageDriver):\n def ex_cleanup_all_multipart_uploads(self, container, prefix=None): ...\n def iterate_containers(self): ...\n def iterate_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def _get_container_path(self, container): ...\n def _get_object_path(self, container, object_name): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True, ex_storage_class=None): ...\n def _upload_multipart(self, response, data, iterator, container, object_name, calculate_hash=True): ...\n def _upload_from_iterator(self, iterator, object_path, upload_id, calculate_hash=True): ...\n def _commit_multipart(self, object_path, upload_id, chunks): ...\n def _abort_multipart(self, object_path, upload_id): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None, ex_storage_class=None): ...\n def delete_object(self, obj): ...\n def ex_iterate_multipart_uploads(self, container, prefix=None, delimiter=None): ...\n def _clean_object_name(self, name): ...\n def _put_object(self, container, object_name, upload_func, upload_func_kwargs, method='PUT', query_args=None, extra=None, file_path=None, iterator=None, verify_hash=True, storage_class=None): ...\n def _to_containers(self, obj, xpath): ...\n def _to_objs(self, obj, xpath, container): ...\n def _to_container(self, element): ...\n def _headers_to_object(self, object_name, container, headers): ...\n def _to_obj(self, element, container): ...\n\n name = 'Amazon S3 (standard)'\n website = 'http://aws.amazon.com/s3/'\n connectionCls = S3Connection\n hash_type = 'md5'\n supports_chunked_encoding = False\n supports_s3_multipart_upload = True\n ex_location_name = ''\n namespace = NAMESPACE\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_s3_abort_multipart_uploads", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000913.py"} {"focal_file": "libcloud/storage/drivers/s3.py", "focal_class": null, "focal_method": "delete_object", "tests": "import unittest\n\nclass Test_delete_object(unittest.TestCase):\n def test_delete_object_not_found(self):\n self.mock_response_klass.type = 'NOT_FOUND'\n container = Container(name='foo_bar_container', extra={}, driver=self.driver)\n obj = Object(name='foo_bar_object', size=1234, hash=None, extra=None, meta_data=None, container=container, driver=self.driver)\n try:\n self.driver.delete_object(obj=obj)\n except ObjectDoesNotExistError:\n pass\n else:\n self.fail('Exception was not thrown')\n\n def test_delete_object_success(self):\n container = Container(name='foo_bar_container', extra={}, driver=self.driver)\n obj = Object(name='foo_bar_object', size=1234, hash=None, extra=None, meta_data=None, container=container, driver=self.driver)\n result = self.driver.delete_object(obj=obj)\n self.assertTrue(result)\n", "method_code": " def delete_object(self, obj):\n object_path = self._get_object_path(obj.container, obj.name)\n response = self.connection.request(object_path, method='DELETE')\n if response.status == httplib.NO_CONTENT:\n return True\n elif response.status == httplib.NOT_FOUND:\n raise ObjectDoesNotExistError(value=None, driver=self, object_name=obj.name)\n return False\n ", "context": "class S3StorageDriver(StorageDriver):\n def delete_object(self, obj): ...\n def iterate_containers(self): ...\n def iterate_container_objects(self, container): ...\n def get_container(self, container_name): ...\n def get_object(self, container_name, object_name): ...\n def _get_container_path(self, container): ...\n def _get_object_path(self, container, object_name): ...\n def create_container(self, container_name): ...\n def delete_container(self, container): ...\n def download_object(self, obj, destination_path, overwrite_existing=False, delete_on_failure=True): ...\n def download_object_as_stream(self, obj, chunk_size=None): ...\n def upload_object(self, file_path, container, object_name, extra=None, verify_hash=True, ex_storage_class=None): ...\n def _upload_multipart(self, response, data, iterator, container, object_name, calculate_hash=True): ...\n def _upload_from_iterator(self, iterator, object_path, upload_id, calculate_hash=True): ...\n def _commit_multipart(self, object_path, upload_id, chunks): ...\n def _abort_multipart(self, object_path, upload_id): ...\n def upload_object_via_stream(self, iterator, container, object_name, extra=None, ex_storage_class=None): ...\n def ex_iterate_multipart_uploads(self, container, prefix=None, delimiter=None): ...\n def ex_cleanup_all_multipart_uploads(self, container, prefix=None): ...\n def _clean_object_name(self, name): ...\n def _put_object(self, container, object_name, upload_func, upload_func_kwargs, method='PUT', query_args=None, extra=None, file_path=None, iterator=None, verify_hash=True, storage_class=None): ...\n def _to_containers(self, obj, xpath): ...\n def _to_objs(self, obj, xpath, container): ...\n def _to_container(self, element): ...\n def _headers_to_object(self, object_name, container, headers): ...\n def _to_obj(self, element, container): ...\n\n name = 'Amazon S3 (standard)'\n website = 'http://aws.amazon.com/s3/'\n connectionCls = S3Connection\n hash_type = 'md5'\n supports_chunked_encoding = False\n supports_s3_multipart_upload = True\n ex_location_name = ''\n namespace = NAMESPACE\n", "repository": "connectthefuture/debpkg_libcloud", "test_name": "test_delete_object_not_found", "smells": [1, 0, 0, 0, 0, 0, 1, 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": [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000914.py"} {"focal_file": "awsmanagement/client.py", "focal_class": "Client", "focal_method": "get_app_session", "tests": "import unittest\n\nclass Test_Client_get_app_session(unittest.TestCase):\n @patch('botocore.session')\n def test_get_ec2_session(self, Mock):\n my_client = Client(aws_access_key_id='test', aws_secret_access_key='test', aws_region='test')\n app_session = my_client.get_app_session()\n ec2_session = my_client.get_ec2_session(app_session)\n self.assertIsInstance(app_session, boto3.session.Session)\n", "method_code": " def get_app_session(self, aws_access_key_id, aws_secret_access_key, aws_region):\n self.log.info('Getting AWS app session')\n app_session = Session(aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, region_name=aws_region)\n return app_session\n ", "context": "class Client(object):\n def get_app_session(self, aws_access_key_id, aws_secret_access_key, aws_region): ...\n def __init__(self, aws_access_key_id, aws_secret_access_key, aws_region, verify=False): ...\n def get_ec2_resource(self): ...\n def ec2_client(self): ...\n def ec2_subnet_resource(self, subnet_id): ...\n def ec2_tag(self, resource_id, key, value): ...\n def ec2_volume(self, volume_id): ...\n def ec2_vpc(self, vpc_id): ...\n def ec2_keypair(self, keypair_name): ...\n def ec2_image(self, image_id): ...\n def ec2_instance(self, instance_id): ...\n def get_s3_resource(self): ...\n def get_instances_by_subnet(subnet_id): ...\n\n self.app_session = self.get_app_session(aws_access_key_id, aws_secret_access_key, aws_region)\n self.ec2_resource = self.get_ec2_resource()\n self.s3_resource = self.get_s3_resource()\n\n log = logging.getLogger(__name__)\n", "repository": "gobins/awsmanagement", "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_000915.py"} {"focal_file": "stix_shifter/stix_transmission/stix_transmission.py", "focal_class": null, "focal_method": "is_async", "tests": "import unittest\n\nclass Test_is_async(unittest.TestCase):\n def test_is_async(self):\n entry_point = EntryPoint(CONNECTION, CONFIG)\n check_async = entry_point.is_async()\n self.assertFalse(check_async)\n\n def test_is_async(self, mock_api_client):\n mock_api_client.return_value = None\n entry_point = EntryPoint()\n config = {'auth': {'sec': 'bla'}}\n connection = {'host': 'hostbla', 'port': 8080, 'selfSignedCert': 'cert'}\n check_async = entry_point.is_async()\n assert check_async\n\n def test_is_async(self, mock_api_client):\n mock_api_client.return_value = None\n config = {'auth': {'username': '', 'password': ''}}\n connection = {'host': 'host', 'port': 8080}\n entry_point = EntryPoint(connection, config)\n check_async = entry_point.is_async()\n assert check_async\n\n @staticmethod\n def test_is_async():\n entry_point = EntryPoint()\n check_async = entry_point.is_async()\n assert check_async\n\n def test_is_async(self):\n entry_point = EntryPoint()\n check_async = entry_point.is_async()\n assert check_async == False\n\n def test_is_async(self, mock_api_client):\n mock_api_client.return_value = None\n entry_point = EntryPoint()\n check_async = entry_point.is_async()\n assert check_async is False\n", "method_code": " def is_async(self):\n try:\n if self.init_error:\n raise self.init_error\n return self.entry_point.is_async()\n except Exception as ex:\n return_obj = dict()\n ErrorResponder.fill_error(return_obj, error=ex)\n return return_obj\n ", "context": "class StixTransmission():\n def is_async(self): ...\n def __init__(self, module, connection, configuration): ...\n def query(self, query): ...\n def status(self, search_id): ...\n def results(self, search_id, offset, length): ...\n def results_stix(self, search_id, offset, length, data_source): ...\n def delete(self, search_id): ...\n def ping(self): ...\n\n init_error = None\n", "repository": "opencybersecurityalliance/stix-shifter", "test_name": "test_is_async", "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_000916.py"} {"focal_file": "stix_shifter/stix_transmission/stix_transmission.py", "focal_class": "StixTransmission", "focal_method": "ping", "tests": "import unittest\n\nclass Test_StixTransmission_ping(unittest.TestCase):\n @patch('stix_shifter_utils.stix_transmission.utils.RestApiClient.RestApiClient.call_api')\n def test_ping(self, mock_ping):\n response = {'data': [{'modelId': 'modelId', 'name': 'name', 'enabled': False}]}\n mock_ping.side_effect = [MockResponse(200, json.dumps(response))]\n transmission = StixTransmission('trendmicro_vision_one', CONNECTION, CONFIG)\n ping_response = transmission.ping()\n self.assertTrue(ping_response['success'])\n", "method_code": " def ping(self):\n try:\n if self.init_error:\n raise self.init_error\n return self.entry_point.ping_connection()\n except Exception as ex:\n return_obj = dict()\n ErrorResponder.fill_error(return_obj, error=ex)\n return return_obj\n ", "context": "class StixTransmission():\n def ping(self): ...\n def __init__(self, module, connection, configuration): ...\n def query(self, query): ...\n def status(self, search_id): ...\n def results(self, search_id, offset, length): ...\n def results_stix(self, search_id, offset, length, data_source): ...\n def delete(self, search_id): ...\n def is_async(self): ...\n\n init_error = None\n", "repository": "opencybersecurityalliance/stix-shifter", "test_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_000917.py"} {"focal_file": "stix_shifter/stix_transmission/stix_transmission.py", "focal_class": "StixTransmission", "focal_method": "query", "tests": "import unittest\n\nclass Test_StixTransmission_query(unittest.TestCase):\n @patch('stix_shifter_utils.stix_transmission.utils.RestApiClient.RestApiClient.call_api')\n def test_query(self, mock_query):\n mock_query.side_effect = [MockResponse(200, self._get_query())]\n transmission = StixTransmission('trendmicro_vision_one', CONNECTION, CONFIG)\n query_response = transmission.query(self._get_query())\n self.assertTrue(query_response['success'])\n self.assertEqual(query_response['search_id'], self._get_query())\n", "method_code": " def query(self, query):\n try:\n if self.init_error:\n raise self.init_error\n return self.entry_point.create_query_connection(query)\n except Exception as ex:\n return_obj = dict()\n ErrorResponder.fill_error(return_obj, error=ex)\n return return_obj\n ", "context": "class StixTransmission():\n def query(self, query): ...\n def __init__(self, module, connection, configuration): ...\n def status(self, search_id): ...\n def results(self, search_id, offset, length): ...\n def results_stix(self, search_id, offset, length, data_source): ...\n def delete(self, search_id): ...\n def ping(self): ...\n def is_async(self): ...\n\n init_error = None\n", "repository": "opencybersecurityalliance/stix-shifter", "test_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": [1, 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": "stix_shifter/stix_transmission/stix_transmission.py", "focal_class": "StixTransmission", "focal_method": "status", "tests": "import unittest\n\nclass Test_StixTransmission_status(unittest.TestCase):\n def test_status(self):\n transmission = StixTransmission('trendmicro_vision_one', CONNECTION, CONFIG)\n status_response = transmission.status('search_id')\n self.assertTrue(status_response['success'])\n self.assertEqual(status_response['status'], 'COMPLETED')\n self.assertEqual(status_response['progress'], 100)\n", "method_code": " def status(self, search_id):\n try:\n if self.init_error:\n raise self.init_error\n return self.entry_point.create_status_connection(search_id)\n except Exception as ex:\n return_obj = dict()\n ErrorResponder.fill_error(return_obj, error=ex)\n return return_obj\n ", "context": "class StixTransmission():\n def status(self, search_id): ...\n def __init__(self, module, connection, configuration): ...\n def query(self, query): ...\n def results(self, search_id, offset, length): ...\n def results_stix(self, search_id, offset, length, data_source): ...\n def delete(self, search_id): ...\n def ping(self): ...\n def is_async(self): ...\n\n init_error = None\n", "repository": "opencybersecurityalliance/stix-shifter", "test_name": "test_status", "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_000919.py"} {"focal_file": "stix_shifter/stix_transmission/stix_transmission.py", "focal_class": "StixTransmission", "focal_method": "delete", "tests": "import unittest\n\nclass Test_StixTransmission_delete(unittest.TestCase):\n def test_delete(self):\n transmission = StixTransmission('trendmicro_vision_one', CONNECTION, CONFIG)\n status_response = transmission.delete('search_id')\n self.assertTrue(status_response['success'])\n", "method_code": " def delete(self, search_id):\n try:\n if self.init_error:\n raise self.init_error\n return self.entry_point.delete_query_connection(search_id)\n except Exception as ex:\n return_obj = dict()\n ErrorResponder.fill_error(return_obj, error=ex)\n return return_obj\n ", "context": "class StixTransmission():\n def delete(self, search_id): ...\n def __init__(self, module, connection, configuration): ...\n def query(self, query): ...\n def status(self, search_id): ...\n def results(self, search_id, offset, length): ...\n def results_stix(self, search_id, offset, length, data_source): ...\n def ping(self): ...\n def is_async(self): ...\n\n init_error = None\n", "repository": "opencybersecurityalliance/stix-shifter", "test_name": "test_delete", "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_000920.py"} {"focal_file": "stix_shifter_modules/carbonblack/stix_transmission/event_parser.py", "focal_class": null, "focal_method": "parse_raw_event_to_obj", "tests": "import unittest\n\nclass Test_parse_raw_event_to_obj(unittest.TestCase):\n def test_parse_raw_event(self):\n raw_event_obj = None\n assert parse_raw_event_to_obj('netconn', raw_event_obj) is None\n raw_event_str = ''\n assert parse_raw_event_to_obj('unknown', raw_event_str) is None\n unknown_event = create_event_obj(process_response, {'parsed_event_data': None})\n assert unknown_event is None\n raw_event_obj = events_response['process']['netconn_complete'][0]\n event_obj = parse_raw_event_to_obj('netconn', raw_event_obj)\n timestamp = get_timestamp_by_event_type(event_obj=event_obj, event_type='netconn')\n assert event_obj == raw_event_obj\n event_obj['parsed_timestamp'] = format_timestamp(timestamp)\n netconn_event = create_event_obj(process_response, {'event_type': 'netconn', 'parsed_event_data': event_obj})\n assert netconn_event.get('process_name') == 'wermgr.exe'\n assert netconn_event.get('domain') == 'resources.jetbrains.com'\n assert netconn_event.get('netconn_remote_port') == 443\n assert netconn_event.get('netconn_remote_ipv4') == '99.86.3.45'\n assert netconn_event.get('netconn_local_port') == 58380\n assert netconn_event.get('netconn_local_ipv4') == '192.168.14.18'\n assert netconn_event.get('event_timestamp') == '2021-04-04T18:10:24.835000Z'\n raw_event_obj = events_response['process']['childproc_complete'][0]\n event_obj = parse_raw_event_to_obj('childproc', raw_event_obj)\n timestamp = get_timestamp_by_event_type(event_obj=event_obj, event_type='childproc')\n assert event_obj == raw_event_obj\n event_obj['parsed_timestamp'] = format_timestamp(timestamp)\n childproc_event = create_event_obj(process_response, {'event_type': 'childproc', 'parsed_event_data': event_obj})\n assert childproc_event.get('process_name') == 'wermgr.exe'\n assert childproc_event.get('childproc_name') == 'c:\\\\program files\\\\jetbrains\\\\pycharm community edition 2020.1\\\\bin\\\\runnerw64.exe'\n assert childproc_event.get('childproc_md5') == 'b3c9a18f42d7ce1c170f25aaeabeeed9'\n assert childproc_event.get('childproc_sha256') == '2dc52cc1954d40065f80526bacb24c34914a89b3e5c56d095728d8e9bc88ea09'\n assert childproc_event.get('childproc_cmdline') == ''\n assert childproc_event.get('childproc_username') == ''\n assert childproc_event.get('childproc_pid') == 10412\n assert childproc_event.get('event_timestamp') == '2021-04-04T18:10:08.548000Z'\n raw_event_str = events_response['process']['regmod_complete'][0]\n event_obj = TestCarbonBlackEventParser.check_str_event('regmod', raw_event_str)\n timestamp = get_timestamp_by_event_type(event_obj=event_obj, event_type='regmod')\n event_obj['parsed_timestamp'] = format_timestamp(timestamp)\n regmod_event = create_event_obj(process_response, {'event_type': 'regmod', 'parsed_event_data': event_obj})\n assert regmod_event.get('process_name') == 'wermgr.exe'\n assert regmod_event.get('regmod_name') == '\\\\\\\\registry\\\\\\\\machine\\\\\\\\software\\\\\\\\microsoft\\\\\\\\windows advanced threat protection\\\\\\\\crashheartbeat'\n assert regmod_event.get('regmod_action') == 'First wrote to the registry key'\n assert regmod_event.get('event_timestamp') == '2021-04-04T18:11:40.309000Z'\n raw_event_str = events_response['process']['modload_complete'][0]\n event_obj = TestCarbonBlackEventParser.check_str_event('modload', raw_event_str)\n timestamp = get_timestamp_by_event_type(event_obj=event_obj, event_type='modload')\n event_obj['parsed_timestamp'] = format_timestamp(timestamp)\n modload_event = create_event_obj(process_response, {'event_type': 'modload', 'parsed_event_data': event_obj})\n assert modload_event.get('process_name') == 'wermgr.exe'\n assert modload_event.get('modload_name') == 'c:\\\\windows\\\\system32\\\\wbem\\\\wbemdisp.dll'\n assert modload_event.get('modload_md5') == '756df8beaf018e982e2383702d905729'\n assert modload_event.get('event_timestamp') == '2021-04-04T18:11:41.244000Z'\n raw_event_str = events_response['process']['crossproc_complete'][0]\n event_obj = TestCarbonBlackEventParser.check_str_event('crossproc', raw_event_str)\n timestamp = get_timestamp_by_event_type(event_obj=event_obj, event_type='crossproc')\n event_obj['parsed_timestamp'] = format_timestamp(timestamp)\n crossproc_event = create_event_obj(process_response, {'event_type': 'crossproc', 'parsed_event_data': event_obj})\n assert crossproc_event.get('process_name') == 'wermgr.exe'\n assert crossproc_event.get('crossproc_name') == 'c:\\\\windows\\\\system32\\\\svchost.exe'\n assert crossproc_event.get('crossproc_action') == 'ProcessOpen'\n assert crossproc_event.get('crossproc_md5') == 'f586835082f632dc8d9404d83bc16316'\n assert crossproc_event.get('event_timestamp') == '2021-04-04T18:11:31.938000Z'\n raw_event_str = events_response['process']['filemod_complete'][0]\n event_obj = TestCarbonBlackEventParser.check_str_event('filemod', raw_event_str)\n timestamp = get_timestamp_by_event_type(event_obj=event_obj, event_type='filemod')\n event_obj['parsed_timestamp'] = format_timestamp(timestamp)\n filemod_event = create_event_obj(process_response, {'event_type': 'filemod', 'parsed_event_data': event_obj})\n assert filemod_event.get('process_name') == 'wermgr.exe'\n assert filemod_event.get('filemod_name') == 'c:\\\\programdata\\\\microsoft\\\\windows\\\\wer\\\\temp\\\\7fb39f69-3a0a-4b59-8afb-0bd9667730d1'\n assert filemod_event.get('filemod_action') == 'Created the file'\n assert filemod_event.get('filemod_md5') == ''\n assert filemod_event.get('event_timestamp') == '2021-04-04T20:17:38.590000Z'\n unknown_event = create_event_obj(process_response, {'event_type': 'unknown', 'parsed_event_data': event_obj})\n assert unknown_event is None\n", "method_code": "def parse_raw_event_to_obj(event_type, raw_event_data):\n if raw_event_data:\n if isinstance(raw_event_data, dict):\n return raw_event_data\n if isinstance(raw_event_data, str):\n return _raw_event_str_to_obj(event_type, raw_event_data)\n return None", "context": "def parse_raw_event_to_obj(event_type, raw_event_data): ...\ndef parse_raw_event_to_obj(event_type, raw_event_data): ...\ndef _raw_event_str_to_obj(event_type, raw_event_data): ...\ndef format_timestamp(timestamp): ...\ndef extract_time_window(query): ...\ndef get_timestamp_by_event_type(event_obj, event_type): ...\ndef is_timestamp_in_window(timestamp, time_window): ...\ndef get_common_fields_as_dict(cbr_process): ...\ndef create_regmod_obj(event_dict, event_type, cbr_event): ...\ndef create_crossproc_obj(event_dict, event_type, cbr_event): ...\ndef create_modload_obj(event_dict, event_type, cbr_event): ...\ndef create_filemod_obj(event_dict, event_type, cbr_event): ...\ndef create_childproc_obj(event_dict, event_type, cbr_event): ...\ndef create_netconn_obj(event_dict, event_type, cbr_event): ...\ndef create_event_obj(process, event): ...\n", "repository": "opencybersecurityalliance/stix-shifter", "test_name": "test_parse_raw_event", "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, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000921.py"} {"focal_file": "stix_shifter_modules/carbonblack/stix_transmission/event_parser.py", "focal_class": null, "focal_method": "format_timestamp", "tests": "import unittest\n\nclass Test_format_timestamp(unittest.TestCase):\n def test_format_timestamp(self):\n input_timestamp = None\n assert format_timestamp(input_timestamp) is None\n input_timestamp = 'not-datetime'\n assert format_timestamp(input_timestamp) == 'not-datetime'\n input_timestamp = datetime.strptime('2021-04-04T20:17:38.59', '%Y-%m-%dT%H:%M:%S.%f')\n assert format_timestamp(input_timestamp) == '2021-04-04T20:17:38.590000Z'\n", "method_code": "def format_timestamp(timestamp):\n \"\"\"\n to TZ format\n :param timestamp: datetime object\n :return: 2021-03-14T13:17:07.716000Z\n \"\"\"\n if not timestamp:\n return timestamp\n try:\n return timestamp.isoformat() + 'Z'\n except Exception:\n pass\n return timestamp", "context": "def format_timestamp(timestamp): ...\ndef parse_raw_event_to_obj(event_type, raw_event_data): ...\ndef _raw_event_str_to_obj(event_type, raw_event_data): ...\ndef format_timestamp(timestamp): ...\ndef extract_time_window(query): ...\ndef get_timestamp_by_event_type(event_obj, event_type): ...\ndef is_timestamp_in_window(timestamp, time_window): ...\ndef get_common_fields_as_dict(cbr_process): ...\ndef create_regmod_obj(event_dict, event_type, cbr_event): ...\ndef create_crossproc_obj(event_dict, event_type, cbr_event): ...\ndef create_modload_obj(event_dict, event_type, cbr_event): ...\ndef create_filemod_obj(event_dict, event_type, cbr_event): ...\ndef create_childproc_obj(event_dict, event_type, cbr_event): ...\ndef create_netconn_obj(event_dict, event_type, cbr_event): ...\ndef create_event_obj(process, event): ...\n", "repository": "opencybersecurityalliance/stix-shifter", "test_name": "test_format_timestamp", "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_000922.py"} {"focal_file": "stix_shifter_modules/carbonblack/stix_transmission/event_parser.py", "focal_class": null, "focal_method": "extract_time_window", "tests": "import unittest\n\nclass Test_extract_time_window(unittest.TestCase):\n def test_extract_time_window(self):\n query = '(process_name:erl.exe)'\n time_window = extract_time_window(query)\n assert time_window is None\n query = '(process_name:erl.exe) and last_update:[2021-04-22T11:09:00 TO 2021-04-22T11:39:00]'\n time_window = extract_time_window(query)\n assert len(time_window) == 2\n assert time_window[0] == datetime(2021, 4, 22, 11, 9)\n assert time_window[1] == datetime(2021, 4, 22, 11, 39)\n query = '((process_name:erl.exe) and last_update:-5m)'\n time_window = extract_time_window(query)\n time_diff: timedelta = time_window[1] - time_window[0]\n assert len(time_window) == 2\n assert time_diff.total_seconds() == 5 * 60\n", "method_code": "def extract_time_window(query):\n if re.search('last_update:\\\\[(.*?)]', query):\n last_update_arr = re.findall('last_update:\\\\[(.*?)]', query)\n if len(last_update_arr) > 0:\n time_window = last_update_arr[0].split(' TO ')\n if len(time_window) == 2:\n return [datetime.strptime(time_window[0], '%Y-%m-%dT%H:%M:%S'), datetime.strptime(time_window[1], '%Y-%m-%dT%H:%M:%S')]\n elif re.search('last_update:-(\\\\d*)m', query):\n last_update_arr = re.findall('last_update:-(\\\\d*)m', query)\n if len(last_update_arr) > 0:\n last_minutes = float(last_update_arr[0])\n end_time = datetime.now(timezone.utc)\n start_time = end_time - timedelta(minutes=last_minutes)\n return [start_time.replace(tzinfo=None), end_time.replace(tzinfo=None)]\n return None", "context": "def extract_time_window(query): ...\ndef parse_raw_event_to_obj(event_type, raw_event_data): ...\ndef _raw_event_str_to_obj(event_type, raw_event_data): ...\ndef format_timestamp(timestamp): ...\ndef extract_time_window(query): ...\ndef get_timestamp_by_event_type(event_obj, event_type): ...\ndef is_timestamp_in_window(timestamp, time_window): ...\ndef get_common_fields_as_dict(cbr_process): ...\ndef create_regmod_obj(event_dict, event_type, cbr_event): ...\ndef create_crossproc_obj(event_dict, event_type, cbr_event): ...\ndef create_modload_obj(event_dict, event_type, cbr_event): ...\ndef create_filemod_obj(event_dict, event_type, cbr_event): ...\ndef create_childproc_obj(event_dict, event_type, cbr_event): ...\ndef create_netconn_obj(event_dict, event_type, cbr_event): ...\ndef create_event_obj(process, event): ...\n", "repository": "opencybersecurityalliance/stix-shifter", "test_name": "test_extract_time_window", "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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000923.py"} {"focal_file": "stix_shifter_modules/carbonblack/stix_transmission/event_parser.py", "focal_class": null, "focal_method": "get_timestamp_by_event_type", "tests": "import unittest\n\nclass Test_get_timestamp_by_event_type(unittest.TestCase):\n def test_get_timestamp_by_event_type(self):\n netconn_event = {'timestamp': '2021-04-04T18:10:24.835Z'}\n timestamp = get_timestamp_by_event_type(netconn_event, 'w00t')\n assert timestamp is None\n timestamp = get_timestamp_by_event_type(netconn_event, 'netconn')\n assert timestamp == datetime(2021, 4, 4, 18, 10, 24, 835000)\n childproc_event = {'end': '2021-04-04T18:10:24.835Z', 'type': 'end'}\n timestamp = get_timestamp_by_event_type(childproc_event, 'childproc')\n assert timestamp == datetime(2021, 4, 4, 18, 10, 24, 835000)\n childproc_event = {'end': '2021-04-04T18:10:24Z', 'type': 'end'}\n timestamp = get_timestamp_by_event_type(childproc_event, 'childproc')\n assert timestamp == datetime(2021, 4, 4, 18, 10, 24)\n childproc_event = {'end': 'not-datetime', 'type': 'end'}\n timestamp = get_timestamp_by_event_type(childproc_event, 'childproc')\n assert timestamp is None\n regmod_event = {'event_time': '2021-04-04 18:11:40.309'}\n timestamp = get_timestamp_by_event_type(regmod_event, 'regmod')\n assert timestamp == datetime(2021, 4, 4, 18, 11, 40, 309000)\n", "method_code": "def get_timestamp_by_event_type(event_obj, event_type):\n try:\n if event_type in str_event_fields.keys():\n timestamp = event_obj.get('event_time')\n return datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S.%f')\n elif event_type == 'netconn':\n timestamp = event_obj.get('timestamp')\n return datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.%fZ')\n elif event_type == 'childproc':\n action_type = event_obj.get('type')\n if action_type:\n timestamp = event_obj.get(action_type)\n try:\n return datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%SZ')\n except ValueError:\n pass\n try:\n return datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.%fZ')\n except ValueError:\n pass\n except Exception as ex:\n logger.warning('Failed to parse timestamp for {} event, skipping, {}'.format(event_type, str(ex)))\n return None", "context": "def get_timestamp_by_event_type(event_obj, event_type): ...\ndef parse_raw_event_to_obj(event_type, raw_event_data): ...\ndef _raw_event_str_to_obj(event_type, raw_event_data): ...\ndef format_timestamp(timestamp): ...\ndef extract_time_window(query): ...\ndef get_timestamp_by_event_type(event_obj, event_type): ...\ndef is_timestamp_in_window(timestamp, time_window): ...\ndef get_common_fields_as_dict(cbr_process): ...\ndef create_regmod_obj(event_dict, event_type, cbr_event): ...\ndef create_crossproc_obj(event_dict, event_type, cbr_event): ...\ndef create_modload_obj(event_dict, event_type, cbr_event): ...\ndef create_filemod_obj(event_dict, event_type, cbr_event): ...\ndef create_childproc_obj(event_dict, event_type, cbr_event): ...\ndef create_netconn_obj(event_dict, event_type, cbr_event): ...\ndef create_event_obj(process, event): ...\n", "repository": "opencybersecurityalliance/stix-shifter", "test_name": "test_get_timestamp_by_event_type", "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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000924.py"} {"focal_file": "stix_shifter_modules/carbonblack/stix_transmission/event_parser.py", "focal_class": null, "focal_method": "is_timestamp_in_window", "tests": "import unittest\n\nclass Test_is_timestamp_in_window(unittest.TestCase):\n def test_is_timestamp_in_window(self):\n query = '(process_name:erl.exe) and last_update:[2021-04-22T11:09:00 TO 2021-04-22T11:10:00]'\n time_window = extract_time_window(query)\n timestamp = datetime(2021, 4, 22, 11, 9, 40)\n assert is_timestamp_in_window(timestamp, time_window) is True\n timestamp = datetime(2021, 4, 22, 11, 5, 40)\n assert is_timestamp_in_window(timestamp, time_window) is False\n assert is_timestamp_in_window(timestamp, None) is False\n assert is_timestamp_in_window(None, time_window) is False\n", "method_code": "def is_timestamp_in_window(timestamp, time_window):\n try:\n return time_window[0] <= timestamp <= time_window[1]\n except Exception as ex:\n logger.warning('Failed to check if timestamp in time_window, {}'.format(str(ex)))\n return False", "context": "def is_timestamp_in_window(timestamp, time_window): ...\ndef parse_raw_event_to_obj(event_type, raw_event_data): ...\ndef _raw_event_str_to_obj(event_type, raw_event_data): ...\ndef format_timestamp(timestamp): ...\ndef extract_time_window(query): ...\ndef get_timestamp_by_event_type(event_obj, event_type): ...\ndef is_timestamp_in_window(timestamp, time_window): ...\ndef get_common_fields_as_dict(cbr_process): ...\ndef create_regmod_obj(event_dict, event_type, cbr_event): ...\ndef create_crossproc_obj(event_dict, event_type, cbr_event): ...\ndef create_modload_obj(event_dict, event_type, cbr_event): ...\ndef create_filemod_obj(event_dict, event_type, cbr_event): ...\ndef create_childproc_obj(event_dict, event_type, cbr_event): ...\ndef create_netconn_obj(event_dict, event_type, cbr_event): ...\ndef create_event_obj(process, event): ...\n", "repository": "opencybersecurityalliance/stix-shifter", "test_name": "test_is_timestamp_in_window", "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_000925.py"} {"focal_file": "stix_shifter_modules/carbonblack/stix_transmission/event_parser.py", "focal_class": null, "focal_method": "get_common_fields_as_dict", "tests": "import unittest\n\nclass Test_get_common_fields_as_dict(unittest.TestCase):\n def test_get_process_common_fields(self):\n common_fields = get_common_fields_as_dict(process_response)\n assert isinstance(common_fields, dict)\n assert 'device_os' in common_fields\n assert 'device_name' in common_fields\n assert 'host_type' in common_fields\n assert 'process_pid' in common_fields\n assert 'process_name' in common_fields\n assert 'parent_pid' in common_fields\n assert 'parent_name' in common_fields\n assert 'process_cmdline' in common_fields\n assert 'interface_ip' in common_fields\n assert 'device_external_ip' in common_fields\n assert 'provider' in common_fields\n", "method_code": "def get_common_fields_as_dict(cbr_process):\n common_fields = {'device_os': cbr_process.get('os_type'), 'device_name': cbr_process.get('hostname'), 'host_type': cbr_process.get('host_type'), 'process_pid': cbr_process.get('process_pid'), 'process_name': cbr_process.get('process_name'), 'parent_pid': cbr_process.get('parent_pid'), 'parent_name': cbr_process.get('parent_name'), 'process_cmdline': cbr_process.get('cmdline'), 'interface_ip': cbr_process.get('interface_ip'), 'device_external_ip': cbr_process.get('comms_ip'), 'provider': CB_PROVIDER}\n return common_fields", "context": "def get_common_fields_as_dict(cbr_process): ...\ndef parse_raw_event_to_obj(event_type, raw_event_data): ...\ndef _raw_event_str_to_obj(event_type, raw_event_data): ...\ndef format_timestamp(timestamp): ...\ndef extract_time_window(query): ...\ndef get_timestamp_by_event_type(event_obj, event_type): ...\ndef is_timestamp_in_window(timestamp, time_window): ...\ndef get_common_fields_as_dict(cbr_process): ...\ndef create_regmod_obj(event_dict, event_type, cbr_event): ...\ndef create_crossproc_obj(event_dict, event_type, cbr_event): ...\ndef create_modload_obj(event_dict, event_type, cbr_event): ...\ndef create_filemod_obj(event_dict, event_type, cbr_event): ...\ndef create_childproc_obj(event_dict, event_type, cbr_event): ...\ndef create_netconn_obj(event_dict, event_type, cbr_event): ...\ndef create_event_obj(process, event): ...\n", "repository": "opencybersecurityalliance/stix-shifter", "test_name": "test_get_process_common_fields", "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_000926.py"} {"focal_file": "stix_shifter_modules/msatp/stix_translation/query_constructor.py", "focal_class": null, "focal_method": "construct_and_op_map", "tests": "import unittest\n\nclass Test_construct_and_op_map(unittest.TestCase):\n def test_construct_and_op_map(self):\n test_mep_01 = {'DeviceNetworkEvents': 'DeviceName =~ \"2.client-channel.google.com\"', 'DeviceProcessEvents': 'InitiatingProcessFileName =~ \"WmiPrvSE.exe\"'}\n test_map_02 = {'DeviceNetworkEvents': 'InitiatingProcessFileName =~ \"demo-gthread-3.6.dll\"'}\n expected_res = {'DeviceNetworkEvents': '(InitiatingProcessFileName =~ \"demo-gthread-3.6.dll\") and (DeviceName =~ \"2.client-channel.google.com\")'}\n self.assertDictEqual(QueryStringPatternTranslator.construct_and_op_map(test_mep_01, test_map_02), expected_res, 'incorrect result')\n", "method_code": " def construct_and_op_map(exp_map_01, exp_map_02):\n merged_map = QueryStringPatternTranslator.construct_intesec_map(exp_map_01, exp_map_02)\n for table in merged_map:\n if len(merged_map[table]) > 1:\n merged_query = '({})'.format(list(merged_map[table])[0])\n for query in merged_map[table][1:]:\n merged_map[table] = merged_query + ' and ({})'.format(query)\n return merged_map\n ", "context": "class QueryStringPatternTranslator():\n @staticmethod\n def construct_and_op_map(exp_map_01, exp_map_02): ...\n def __init__(self, pattern: Pattern, data_model_mapper, time_range): ...\n def _format_equality(value, comparator) -> str: ...\n def _format_set(value) -> str: ...\n def _format_like(value, comparator) -> str: ...\n def _format_matches(value) -> str: ...\n def _format_datetime(value, expression) -> str: ...\n def _negate_comparison(comparison_string): ...\n def _check_value_type(value, expression): ...\n def _parse_time_range(qualifier, time_range): ...\n def _parse_mapped_fields(expression, value, comparator, mapped_fields_array): ...\n def clean_format_string(format_string): ...\n def _lookup_comparison_operator(self, expression_operator): ...\n def __eval_comparison_exp_map(self, expression): ...\n def mergeDict(dict1, dict2): ...\n def _parse_expression(self, expression, qualifier=None): ...\n def construct_op_map(exp_map_01, exp_map_02, operator): ...\n def construct_intesec_map(exp_map_01, exp_map_02): ...\n def construct_query_from_map(self, map_kusto_query): ...\n def parse_expression(self, pattern: Pattern): ...\n def __eval_comparison_value(self, expression, comparator): ...\n\n self.dmm = data_model_mapper\n self._time_range = time_range\n self.qualified_queries = []\n self.qualifier_string = ''\n self.lookup_table_object = None\n self._is_mac = None\n\n comparator_lookup = {ComparisonExpressionOperators.And: 'and', ComparisonExpressionOperators.Or: 'or', ComparisonComparators.Equal: '==', ComparisonComparators.NotEqual: '!=', ComparisonComparators.Like: 'contains', ComparisonComparators.Matches: 'matches', ComparisonComparators.GreaterThan: '>', ComparisonComparators.GreaterThanOrEqual: '>=', ComparisonComparators.LessThan: '<', ComparisonComparators.LessThanOrEqual: '<=', ComparisonComparators.In: 'in~', ObservationOperators.Or: 'or', ObservationOperators.And: 'or'}\n join_query = ' | join kind= inner (DeviceNetworkInfo {qualifier_string}{floor_time}| mvexpand parse_json(IPAddresses) | extend IP = IPAddresses.IPAddress | project Timestamp ,DeviceId , MacAddress, IP, FormattedTimeKey) on DeviceId, $left.FormattedTimeKey == $right.FormattedTimeKey | where LocalIP == IP | where {mac_query} | order by Timestamp desc'\n", "repository": "opencybersecurityalliance/stix-shifter", "test_name": "test_construct_and_op_map", "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_000927.py"} {"focal_file": "stem/version.py", "focal_class": null, "focal_method": "get_system_tor_version", "tests": "import unittest\n\nclass Test_get_system_tor_version(unittest.TestCase):\n @test.require.command('tor')\n def test_get_system_tor_version(self):\n \"\"\"\n Basic verification checks for the get_system_tor_version() function.\n \"\"\"\n stem.version.get_system_tor_version()\n self.assertRaises(IOError, stem.version.get_system_tor_version, 'ls')\n self.assertRaises(IOError, stem.version.get_system_tor_version, 'blarg')\n\n @patch('stem.util.system.call')\n @patch.dict(stem.version.VERSION_CACHE)\n def test_get_system_tor_version(self, call_mock):\n call_mock.return_value = TOR_VERSION_OUTPUT.splitlines()\n version = stem.version.get_system_tor_version('tor_unit')\n self.assert_versions_match(version, 0, 2, 2, 35, None, 'git-73ff13ab3cc9570d')\n self.assertEqual('73ff13ab3cc9570d', version.git_commit)\n call_mock.assert_called_once_with('tor_unit --version')\n self.assertEqual(stem.version.VERSION_CACHE['tor_unit'], version)\n\n @patch('stem.util.system.call', Mock(return_value=TOR_VERSION_EXTRA_LINES.splitlines()))\n @patch.dict(stem.version.VERSION_CACHE)\n def test_get_system_tor_version_extra_lines(self):\n \"\"\"\n Include extra text before and after the version.\n \"\"\"\n version = stem.version.get_system_tor_version('tor_unit')\n self.assert_versions_match(version, 0, 2, 2, 35, None, 'git-73ff13ab3cc9570d')\n", "method_code": "def get_system_tor_version(tor_cmd='tor'):\n \"\"\"\n Queries tor for its version. This is os dependent, only working on linux,\n osx, and bsd.\n\n :param str tor_cmd: command used to run tor\n\n :returns: :class:`~stem.version.Version` provided by the tor command\n\n :raises: **IOError** if unable to query or parse the version\n \"\"\"\n if tor_cmd not in VERSION_CACHE:\n version_cmd = '%s --version' % tor_cmd\n try:\n version_output = stem.util.system.call(version_cmd)\n except OSError as exc:\n if 'No such file or directory' in str(exc):\n if os.path.isabs(tor_cmd):\n exc = \"Unable to check tor's version. '%s' doesn't exist.\" % tor_cmd\n else:\n exc = \"Unable to run '%s'. Maybe tor isn't in your PATH?\" % version_cmd\n raise IOError(exc)\n for line in version_output:\n if line.startswith('Tor version ') and line.endswith('.'):\n try:\n version_str = line[12:-1]\n VERSION_CACHE[tor_cmd] = Version(version_str)\n break\n except ValueError as exc:\n raise IOError(exc)\n if tor_cmd not in VERSION_CACHE:\n raise IOError(\"'%s' didn't provide a parseable version:\\n\\n%s\" % (version_cmd, '\\n'.join(version_output)))\n return VERSION_CACHE[tor_cmd]", "context": "def get_system_tor_version(tor_cmd='tor'): ...\ndef get_system_tor_version(tor_cmd='tor'): ...\ndef _get_version(version_str): ...\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 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": "stem/process.py", "focal_class": null, "focal_method": "launch_tor_with_config", "tests": "import unittest\n\nclass Test_launch_tor_with_config(unittest.TestCase):\n @asynchronous\n def test_launch_tor_with_config_via_file(tor_cmd):\n \"\"\"\n Exercises launch_tor_with_config when we write a torrc to disk.\n \"\"\"\n with tmp_directory() as data_directory:\n control_port = random_port()\n control_socket, tor_process = (None, None)\n try:\n with patch('stem.version.get_system_tor_version', Mock(return_value=stem.version.Version('0.0.0.1'))):\n tor_process = stem.process.launch_tor_with_config(tor_cmd=tor_cmd, config={'SocksPort': random_port(), 'ControlPort': control_port, 'DataDirectory': data_directory}, completion_percent=5)\n control_socket = stem.socket.ControlPort(port=int(control_port))\n stem.connection.authenticate(control_socket)\n control_socket.send('GETCONF ControlPort')\n getconf_response = control_socket.recv()\n assert_equal('ControlPort=%s' % control_port, str(getconf_response))\n finally:\n if control_socket:\n control_socket.close()\n if tor_process:\n tor_process.kill()\n tor_process.wait()\n\n @asynchronous\n def test_launch_tor_with_config_via_stdin(tor_cmd):\n \"\"\"\n Exercises launch_tor_with_config when we provide our torrc via stdin.\n \"\"\"\n if test.tor_version() < stem.version.Requirement.TORRC_VIA_STDIN:\n skip('(requires %s)' % stem.version.Requirement.TORRC_VIA_STDIN)\n with tmp_directory() as data_directory:\n control_port = random_port()\n control_socket, tor_process = (None, None)\n try:\n tor_process = stem.process.launch_tor_with_config(tor_cmd=tor_cmd, config={'SocksPort': random_port(), 'ControlPort': control_port, 'DataDirectory': data_directory}, completion_percent=5)\n control_socket = stem.socket.ControlPort(port=int(control_port))\n stem.connection.authenticate(control_socket)\n control_socket.send('GETCONF ControlPort')\n getconf_response = control_socket.recv()\n assert_equal('ControlPort=%s' % control_port, str(getconf_response))\n finally:\n if control_socket:\n control_socket.close()\n if tor_process:\n tor_process.kill()\n tor_process.wait()\n\n @asynchronous\n def test_with_invalid_config(tor_cmd):\n \"\"\"\n Spawn a tor process with a configuration that should make it dead on arrival.\n \"\"\"\n with tmp_directory() as data_directory:\n both_ports = random_port()\n try:\n stem.process.launch_tor_with_config(tor_cmd=tor_cmd, config={'SocksPort': both_ports, 'ControlPort': both_ports, 'DataDirectory': data_directory})\n raise AssertionError('Tor should fail to launch')\n except OSError as exc:\n assert_equal('Process terminated: Failed to bind one of the listener ports.', str(exc))\n\n def test_launch_tor_with_timeout(self):\n \"\"\"\n Runs launch_tor where it times out before completing.\n \"\"\"\n with tmp_directory() as data_directory:\n start_time = time.time()\n try:\n stem.process.launch_tor_with_config(tor_cmd=TOR_CMD, timeout=0.05, config={'SocksPort': random_port(), 'DataDirectory': data_directory})\n raise AssertionError('Tor should fail to launch')\n except OSError:\n runtime = time.time() - start_time\n if not (runtime > 0.05 and runtime < 3):\n raise AssertionError('Test should have taken 0.05-3 seconds, took %0.1f instead' % runtime)\n", "method_code": "def launch_tor_with_config(config, tor_cmd='tor', completion_percent=100, init_msg_handler=None, timeout=DEFAULT_INIT_TIMEOUT, take_ownership=False, close_output=True):\n \"\"\"\n Initializes a tor process, like :func:`~stem.process.launch_tor`, but with a\n customized configuration. This writes a temporary torrc to disk, launches\n tor, then deletes the torrc.\n\n For example...\n\n ::\n\n tor_process = stem.process.launch_tor_with_config(\n config = {\n 'ControlPort': '2778',\n 'Log': [\n 'NOTICE stdout',\n 'ERR file /tmp/tor_error_log',\n ],\n },\n )\n\n .. versionchanged:: 1.7.0\n Added the **close_output** argument.\n\n :param dict config: configuration options, such as \"{'ControlPort': '9051'}\",\n values can either be a **str** or **list of str** if for multiple values\n :param str tor_cmd: command for starting tor\n :param int completion_percent: percent of bootstrap completion at which\n this'll return\n :param functor init_msg_handler: optional functor that will be provided with\n tor's initialization stdout as we get it\n :param int timeout: time after which the attempt to start tor is aborted, no\n timeouts are applied if **None**\n :param bool take_ownership: asserts ownership over the tor process so it\n aborts if this python process terminates or a :class:`~stem.control.Controller`\n we establish to it disconnects\n :param bool close_output: closes tor's stdout and stderr streams when\n bootstrapping is complete if true\n\n :returns: **subprocess.Popen** instance for the tor subprocess\n\n :raises: **OSError** if we either fail to create the tor process or reached a\n timeout without success\n \"\"\"\n try:\n use_stdin = stem.version.get_system_tor_version(tor_cmd) >= stem.version.Requirement.TORRC_VIA_STDIN\n except IOError:\n use_stdin = False\n if 'Log' in config:\n stdout_options = ['DEBUG stdout', 'INFO stdout', 'NOTICE stdout']\n if isinstance(config['Log'], str):\n config['Log'] = [config['Log']]\n has_stdout = False\n for log_config in config['Log']:\n if log_config in stdout_options:\n has_stdout = True\n break\n if not has_stdout:\n config['Log'].append('NOTICE stdout')\n config_str = ''\n for key, values in list(config.items()):\n if isinstance(values, str):\n config_str += '%s %s\\n' % (key, values)\n else:\n for value in values:\n config_str += '%s %s\\n' % (key, value)\n if use_stdin:\n return launch_tor(tor_cmd, ['-f', '-'], None, completion_percent, init_msg_handler, timeout, take_ownership, close_output, stdin=config_str)\n else:\n torrc_descriptor, torrc_path = tempfile.mkstemp(prefix='torrc-', text=True)\n try:\n with open(torrc_path, 'w') as torrc_file:\n torrc_file.write(config_str)\n args = ['__ReloadTorrcOnSIGHUP', '0']\n return launch_tor(tor_cmd, args, torrc_path, completion_percent, init_msg_handler, timeout, take_ownership)\n finally:\n try:\n os.close(torrc_descriptor)\n os.remove(torrc_path)\n except:\n pass", "context": "def launch_tor_with_config(config, tor_cmd='tor', completion_percent=100, init_msg_handler=None, timeout=DEFAULT_INIT_TIMEOUT, take_ownership=False, close_output=True): ...\ndef launch_tor(tor_cmd='tor', args=None, torrc_path=None, completion_percent=100, init_msg_handler=None, timeout=DEFAULT_INIT_TIMEOUT, take_ownership=False, close_output=True, stdin=None): ...\ndef launch_tor_with_config(config, tor_cmd='tor', completion_percent=100, init_msg_handler=None, timeout=DEFAULT_INIT_TIMEOUT, take_ownership=False, close_output=True): ...\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000929.py"} {"focal_file": "stem/manual.py", "focal_class": null, "focal_method": "_get_categories", "tests": "import unittest\n\nclass Test_get_categories(unittest.TestCase):\n def test_has_all_categories(self):\n \"\"\"\n Check that the categories in tor's manual matches what we expect. If these\n change then we likely want to add/remove attributes from Stem's Manual\n class to match.\n \"\"\"\n if self.requires_downloaded_manual():\n return\n categories = stem.manual._get_categories(self.man_content)\n present = set(categories.keys())\n missing_categories = EXPECTED_CATEGORIES.difference(present)\n extra_categories = present.difference(EXPECTED_CATEGORIES)\n if missing_categories:\n self.fail(\"Changed tor's man page? We expected the %s man page sections but they're no longer around. Might need to update our Manual class.\" % ', '.join(missing_categories))\n elif extra_categories:\n self.fail(\"Changed tor's man page? We weren't expecting the %s man page sections. Might need to update our Manual class.\" % ', '.join(extra_categories))\n self.assertEqual(['tor - The second-generation onion router'], categories['NAME'])\n self.assertEqual(['tor [OPTION value]...'], categories['SYNOPSIS'])\n", "method_code": "def _get_categories(content):\n \"\"\"\n The man page is headers followed by an indented section. First pass gets\n the mapping of category titles to their lines.\n \"\"\"\n if content and 'TOR(1)' in content[0]:\n content = content[1:]\n if content and content[-1].startswith('Tor'):\n content = content[:-1]\n categories = OrderedDict()\n category, lines = (None, [])\n for line in content:\n char_for = chr if stem.prereq.is_python_3() else unichr\n line = line.replace(char_for(8217), \"'\").replace(char_for(8212), '-').replace(char_for(183), '*')\n if line and (not line.startswith(' ')):\n if category:\n if lines and lines[-1] == '':\n lines = lines[:-1]\n categories[category] = lines\n category, lines = (line.strip(), [])\n else:\n if line.startswith(' '):\n line = line[7:]\n lines.append(line)\n if category:\n categories[category] = lines\n return categories", "context": "def _get_categories(content): ...\ndef query(query, *param): ...\ndef _config(lowercase=True): ...\ndef _manual_differences(previous_manual, new_manual): ...\ndef is_important(option): ...\ndef download_man_page(path=None, file_handle=None, url=GITWEB_MANUAL_URL, timeout=20): ...\ndef _get_categories(content): ...\ndef _get_indented_descriptions(lines): ...\ndef _add_config_options(config_options, category, lines): ...\ndef _join_lines(lines): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_has_all_categories", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000930.py"} {"focal_file": "stem/connection.py", "focal_class": null, "focal_method": "get_protocolinfo", "tests": "import unittest\n\nclass Test_get_protocolinfo(unittest.TestCase):\n @test.require.controller\n @patch('stem.util.proc.is_available', Mock(return_value=False))\n @patch('stem.util.system.is_available', Mock(return_value=True))\n def test_get_protocolinfo_path_expansion(self):\n \"\"\"\n If we're running with the 'RELATIVE' target then test_parsing() will\n exercise cookie path expansion when we're able to query the pid by our\n prcess name. This test selectively disables system.call() so we exercise\n the expansion via our control port or socket file.\n\n This test is largely redundant with test_parsing() if we aren't running\n with the 'RELATIVE' target.\n \"\"\"\n if test.runner.Torrc.PORT in test.runner.get_runner().get_options():\n lookup_prefixes = (stem.util.system.GET_PID_BY_PORT_NETSTAT, stem.util.system.GET_PID_BY_PORT_SOCKSTAT % '', stem.util.system.GET_PID_BY_PORT_LSOF, stem.util.system.GET_CWD_PWDX % '', 'lsof -a -p ')\n control_socket = stem.socket.ControlPort(port=test.runner.CONTROL_PORT)\n else:\n lookup_prefixes = (stem.util.system.GET_PID_BY_FILE_LSOF % '', stem.util.system.GET_CWD_PWDX % '', 'lsof -a -p ')\n control_socket = stem.socket.ControlSocketFile(test.runner.CONTROL_SOCKET_PATH)\n call_replacement = test.integ.util.system.filter_system_call(lookup_prefixes)\n with patch('stem.util.system.call') as call_mock:\n call_mock.side_effect = call_replacement\n protocolinfo_response = stem.connection.get_protocolinfo(control_socket)\n self.assert_matches_test_config(protocolinfo_response)\n self.assertTrue(control_socket.is_alive())\n control_socket.close()\n\n @test.require.controller\n def test_multiple_protocolinfo_calls(self):\n \"\"\"\n Tests making repeated PROTOCOLINFO queries. This use case is interesting\n because tor will shut down the socket and stem should transparently\n re-establish it.\n \"\"\"\n with test.runner.get_runner().get_tor_socket(False) as control_socket:\n for _ in range(5):\n protocolinfo_response = stem.connection.get_protocolinfo(control_socket)\n self.assert_matches_test_config(protocolinfo_response)\n", "method_code": "def get_protocolinfo(controller):\n \"\"\"\n Issues a PROTOCOLINFO query to a control socket, getting information about\n the tor process running on it. If the socket is already closed then it is\n first reconnected.\n\n This can authenticate to either a :class:`~stem.control.BaseController` or\n :class:`~stem.socket.ControlSocket`.\n\n :param controller: tor controller or socket to be queried\n\n :returns: :class:`~stem.response.protocolinfo.ProtocolInfoResponse` provided by tor\n\n :raises:\n * :class:`stem.ProtocolError` if the PROTOCOLINFO response is\n malformed\n * :class:`stem.SocketError` if problems arise in establishing or\n using the socket\n \"\"\"\n try:\n protocolinfo_response = _msg(controller, 'PROTOCOLINFO 1')\n except:\n protocolinfo_response = None\n if not protocolinfo_response or str(protocolinfo_response) == 'Authentication required.':\n controller.connect()\n try:\n protocolinfo_response = _msg(controller, 'PROTOCOLINFO 1')\n except stem.SocketClosed as exc:\n raise stem.SocketError(exc)\n stem.response.convert('PROTOCOLINFO', protocolinfo_response)\n return protocolinfo_response", "context": "def get_protocolinfo(controller): ...\ndef connect(control_port=('127.0.0.1', 'default'), control_socket='/var/run/tor/control', password=None, password_prompt=False, chroot_path=None, controller=stem.control.Controller): ...\ndef connect_port(address='127.0.0.1', port=9051, password=None, chroot_path=None, controller=stem.control.Controller): ...\ndef connect_socket_file(path='/var/run/tor/control', password=None, chroot_path=None, controller=stem.control.Controller): ...\ndef _connect_auth(control_socket, password, password_prompt, chroot_path, controller): ...\ndef authenticate(controller, password=None, chroot_path=None, protocolinfo_response=None): ...\ndef authenticate_none(controller, suppress_ctl_errors=True): ...\ndef authenticate_password(controller, password, suppress_ctl_errors=True): ...\ndef authenticate_cookie(controller, cookie_path, suppress_ctl_errors=True): ...\ndef authenticate_safecookie(controller, cookie_path, suppress_ctl_errors=True): ...\ndef get_protocolinfo(controller): ...\ndef _msg(controller, message): ...\ndef _connection_for_default_port(address): ...\ndef _read_cookie(cookie_path, is_safecookie): ...\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000931.py"} {"focal_file": "stem/socket.py", "focal_class": null, "focal_method": "connection_time", "tests": "import unittest\n\nclass Test_connection_time(unittest.TestCase):\n @test.require.controller\n def test_connection_time(self):\n \"\"\"\n Checks that our connection_time method tracks when our state's changed.\n \"\"\"\n test_start = time.time()\n runner = test.runner.get_runner()\n with runner.get_tor_socket() as control_socket:\n connection_time = control_socket.connection_time()\n self.assertTrue(test_start <= connection_time <= time.time())\n time.sleep(0.001)\n self.assertEqual(connection_time, control_socket.connection_time())\n control_socket.close()\n disconnection_time = control_socket.connection_time()\n self.assertTrue(connection_time < disconnection_time <= time.time())\n time.sleep(0.001)\n control_socket.connect()\n reconnection_time = control_socket.connection_time()\n self.assertTrue(disconnection_time < reconnection_time <= time.time())\n", "method_code": " def connection_time(self):\n \"\"\"\n Provides the unix timestamp for when our socket was either connected or\n disconnected. That is to say, the time we connected if we're currently\n connected and the time we disconnected if we're not connected.\n \n .. versionadded:: 1.3.0\n \n :returns: **float** for when we last connected or disconnected, zero if\n we've never connected\n \"\"\"\n return self._connection_time\n ", "context": "class BaseSocket(object):\n def connection_time(self): ...\n def __init__(self): ...\n def is_alive(self): ...\n def is_localhost(self): ...\n def connect(self): ...\n def close(self): ...\n def _send(self, message, handler): ...\n def _recv(self, handler): ...\n def _get_send_lock(self): ...\n def __enter__(self): ...\n def __exit__(self, exit_type, value, traceback): ...\n def _connect(self): ...\n def _close(self): ...\n def _make_socket(self): ...\n\n self._socket, self._socket_file = (None, None)\n self._is_alive = False\n self._connection_time = 0.0\n self._send_lock = threading.RLock()\n self._recv_lock = threading.RLock()\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000932.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "get_latest_heartbeat", "tests": "import unittest\n\nclass Test_get_latest_heartbeat(unittest.TestCase):\n @test.require.controller\n def test_get_latest_heartbeat(self):\n \"\"\"\n Basic check for get_latest_heartbeat().\n \"\"\"\n with test.runner.get_runner().get_tor_socket() as control_socket:\n controller = stem.control.BaseController(control_socket)\n controller.msg('GETINFO version')\n self.assertTrue(time.time() - controller.get_latest_heartbeat() < 5)\n", "method_code": " def get_latest_heartbeat(self):\n \"\"\"\n Provides the unix timestamp for when we last heard from tor. This is zero\n if we've never received a message.\n \n :returns: float for the unix timestamp of when we last heard from tor\n \"\"\"\n return self._last_heartbeat\n ", "context": "class BaseController(object):\n def get_latest_heartbeat(self): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def msg(self, message): ...\n def is_alive(self): ...\n def is_localhost(self): ...\n def connection_time(self): ...\n def is_authenticated(self): ...\n def connect(self): ...\n def close(self): ...\n def get_socket(self): ...\n def add_status_listener(self, callback, spawn=True): ...\n def remove_status_listener(self, callback): ...\n def __enter__(self): ...\n def __exit__(self, exit_type, value, traceback): ...\n def _handle_event(self, event_message): ...\n def _connect(self): ...\n def _close(self): ...\n def _post_authentication(self): ...\n def _notify_status_listeners(self, state): ...\n def _launch_threads(self): ...\n def _reader_loop(self): ...\n def _event_loop(self): ...\n\n self._socket = control_socket\n self._msg_lock = threading.RLock()\n self._status_listeners = []\n self._status_listeners_lock = threading.RLock()\n self._reply_queue = queue.Queue()\n self._event_queue = queue.Queue()\n self._reader_thread = None\n self._event_notice = threading.Event()\n self._event_thread = None\n self._socket_connect = self._socket._connect\n self._socket_close = self._socket._close\n self._socket._connect = self._connect\n self._socket._close = self._close\n self._last_heartbeat = 0.0\n self._is_authenticated = False\n self._state_change_threads = []\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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, 1, 0, 0], "pynose_source_file": "test_000933.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "from_port", "tests": "import unittest\n\nclass Test_from_port(unittest.TestCase):\n def test_from_port(self):\n \"\"\"\n Basic sanity check for the from_port constructor.\n \"\"\"\n if test.runner.Torrc.PORT in test.runner.get_runner().get_options():\n with stem.control.Controller.from_port(port=test.runner.CONTROL_PORT) as controller:\n self.assertTrue(isinstance(controller, stem.control.Controller))\n else:\n self.assertRaises(stem.SocketError, stem.control.Controller.from_port, '127.0.0.1', test.runner.CONTROL_PORT)\n", "method_code": " def from_port(address='127.0.0.1', port='default'):\n \"\"\"\n Constructs a :class:`~stem.socket.ControlPort` based Controller.\n \n If the **port** is **'default'** then this checks on both 9051 (default\n for relays) and 9151 (default for the Tor Browser). This default may change\n in the future.\n \n .. versionchanged:: 1.5.0\n Use both port 9051 and 9151 by default.\n \n :param str address: ip address of the controller\n :param int port: port number of the controller\n \n :returns: :class:`~stem.control.Controller` attached to the given port\n \n :raises: :class:`stem.SocketError` if we're unable to establish a connection\n \"\"\"\n import stem.connection\n if not stem.util.connection.is_valid_ipv4_address(address):\n raise ValueError('Invalid IP address: %s' % address)\n elif port != 'default' and (not stem.util.connection.is_valid_port(port)):\n raise ValueError('Invalid port: %s' % port)\n if port == 'default':\n control_port = stem.connection._connection_for_default_port(address)\n else:\n control_port = stem.socket.ControlPort(address, port)\n return Controller(control_port)\n ", "context": "class Controller(BaseController):\n @staticmethod\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "test_from_port", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000934.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "from_socket_file", "tests": "import unittest\n\nclass Test_from_socket_file(unittest.TestCase):\n def test_from_socket_file(self):\n \"\"\"\n Basic sanity check for the from_socket_file constructor.\n \"\"\"\n if test.runner.Torrc.SOCKET in test.runner.get_runner().get_options():\n with stem.control.Controller.from_socket_file(path=test.runner.CONTROL_SOCKET_PATH) as controller:\n self.assertTrue(isinstance(controller, stem.control.Controller))\n else:\n self.assertRaises(stem.SocketError, stem.control.Controller.from_socket_file, test.runner.CONTROL_SOCKET_PATH)\n", "method_code": " def from_socket_file(path='/var/run/tor/control'):\n \"\"\"\n Constructs a :class:`~stem.socket.ControlSocketFile` based Controller.\n \n :param str path: path where the control socket is located\n \n :returns: :class:`~stem.control.Controller` attached to the given socket file\n \n :raises: :class:`stem.SocketError` if we're unable to establish a connection\n \"\"\"\n control_socket = stem.socket.ControlSocketFile(path)\n return Controller(control_socket)\n ", "context": "class Controller(BaseController):\n @staticmethod\n def from_socket_file(path='/var/run/tor/control'): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "test_from_socket_file", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000935.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "add_event_listener", "tests": "import unittest\n\nclass Test_add_event_listener(unittest.TestCase):\n @test.require.controller\n def test_reattaching_listeners(self):\n \"\"\"\n Checks that event listeners are re-attached when a controller disconnects\n then reconnects to tor.\n \"\"\"\n event_notice = threading.Event()\n event_buffer = []\n\n def listener(event):\n event_buffer.append(event)\n event_notice.set()\n runner = test.runner.get_runner()\n with runner.get_tor_controller() as controller:\n controller.add_event_listener(listener, EventType.CONF_CHANGED)\n controller.set_conf('NodeFamily', 'FD4CC275C5AA4D27A487C6CA29097900F85E2C33')\n event_notice.wait(4)\n self.assertTrue(len(event_buffer) >= 1)\n controller.close()\n event_notice.clear()\n event_buffer = []\n controller.connect()\n controller.authenticate(password=test.runner.CONTROL_PASSWORD)\n self.assertTrue(len(event_buffer) == 0)\n controller.set_conf('NodeFamily', 'A82F7EFDB570F6BC801805D0328D30A99403C401')\n event_notice.wait(4)\n self.assertTrue(len(event_buffer) >= 1)\n controller.reset_conf('NodeFamily')\n\n @patch('stem.control.Controller.is_authenticated', Mock(return_value=True))\n @patch('stem.control.Controller._attach_listeners', Mock(return_value=([], [])))\n @patch('stem.control.Controller.get_version')\n def test_add_event_listener(self, get_version_mock):\n \"\"\"\n Exercises the add_event_listener and remove_event_listener methods.\n \"\"\"\n get_version_mock.return_value = stem.version.Version('0.1.0.14')\n self.assertRaises(InvalidRequest, self.controller.add_event_listener, Mock(), EventType.BW)\n get_version_mock.return_value = stem.version.Version('0.2.0.35')\n self.controller.add_event_listener(Mock(), EventType.BW)\n self.assertRaises(InvalidRequest, self.controller.add_event_listener, Mock(), EventType.SIGNAL)\n", "method_code": " def add_event_listener(self, listener, *events):\n \"\"\"\n Directs further tor controller events to a given function. The function is\n expected to take a single argument, which is a\n :class:`~stem.response.events.Event` subclass. For instance the following\n would print the bytes sent and received by tor over five seconds...\n \n ::\n \n import time\n from stem.control import Controller, EventType\n \n def print_bw(event):\n print('sent: %i, received: %i' % (event.written, event.read))\n \n with Controller.from_port(port = 9051) as controller:\n controller.authenticate()\n controller.add_event_listener(print_bw, EventType.BW)\n time.sleep(5)\n \n If a new control connection is initialized then this listener will be\n reattached.\n \n If tor emits a malformed event it can be received by listening for the\n stem.control.MALFORMED_EVENTS constant.\n \n .. versionchanged:: 1.7.0\n Listener exceptions and malformed events no longer break further event\n processing. Added the **MALFORMED_EVENTS** constant.\n \n :param functor listener: function to be called when an event is received\n :param stem.control.EventType events: event types to be listened for\n \n :raises: :class:`stem.ProtocolError` if unable to set the events\n \"\"\"\n with self._event_listeners_lock:\n if self.is_authenticated():\n for event_type in events:\n event_type = stem.response.events.EVENT_TYPE_TO_CLASS.get(event_type)\n if event_type and self.get_version() < event_type._VERSION_ADDED:\n raise stem.InvalidRequest(552, '%s event requires Tor version %s or later' % (event_type, event_type._VERSION_ADDED))\n for event_type in events:\n self._event_listeners.setdefault(event_type, []).append(listener)\n failed_events = self._attach_listeners()[1]\n failed_events = set(failed_events).intersection(set(events))\n if failed_events:\n raise stem.ProtocolError('SETEVENTS rejected %s' % ', '.join(failed_events))\n ", "context": "class Controller(BaseController):\n def add_event_listener(self, listener, *events): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000936.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "get_info", "tests": "import unittest\n\nclass Test_get_info(unittest.TestCase):\n @test.require.controller\n def test_getinfo(self):\n \"\"\"\n Exercises GETINFO with valid and invalid queries.\n \"\"\"\n runner = test.runner.get_runner()\n with runner.get_tor_controller() as controller:\n torrc_path = runner.get_torrc_path()\n self.assertEqual(torrc_path, controller.get_info('config-file'))\n self.assertEqual(torrc_path, controller.get_info('config-file', 'ho hum'))\n expected = {'config-file': torrc_path}\n self.assertEqual(expected, controller.get_info(['config-file']))\n self.assertEqual(expected, controller.get_info(['config-file'], 'ho hum'))\n getinfo_params = set(['version', 'config-file', 'config/names'])\n self.assertEqual(getinfo_params, set(controller.get_info(['version', 'config-file', 'config/names']).keys()))\n self.assertRaises(stem.ControllerError, controller.get_info, 'blarg')\n self.assertEqual('ho hum', controller.get_info('blarg', 'ho hum'))\n self.assertRaises(stem.ControllerError, controller.get_info, '')\n self.assertEqual('ho hum', controller.get_info('', 'ho hum'))\n self.assertEqual({}, controller.get_info([]))\n self.assertEqual({}, controller.get_info([], {}))\n\n @patch('stem.control.Controller.msg')\n def test_get_info(self, msg_mock):\n msg_mock.return_value = ControlMessage.from_str('250-hello=hi right back!\\r\\n250 OK\\r\\n', 'GETINFO')\n self.assertEqual('hi right back!', self.controller.get_info('hello'))\n", "method_code": " def get_info(self, params, default=UNDEFINED, get_bytes=False):\n \"\"\"\n get_info(params, default = UNDEFINED, get_bytes = False)\n \n Queries the control socket for the given GETINFO option. If provided a\n default then that's returned if the GETINFO option is undefined or the\n call fails for any reason (error response, control port closed, initiated,\n etc).\n \n .. versionchanged:: 1.1.0\n Added the get_bytes argument.\n \n .. versionchanged:: 1.7.0\n Errors commonly provided a :class:`stem.ProtocolError` when we should\n raise a :class:`stem.OperationFailed`.\n \n :param str,list params: GETINFO option or options to be queried\n :param object default: response if the query fails\n :param bool get_bytes: provides **bytes** values rather than a **str** under python 3.x\n \n :returns:\n Response depends upon how we were called as follows...\n \n * **str** with the response if our param was a **str**\n * **dict** with the 'param => response' mapping if our param was a **list**\n * default if one was provided and our call failed\n \n :raises:\n * :class:`stem.ControllerError` if the call fails and we weren't\n provided a default response\n * :class:`stem.InvalidArguments` if the 'params' requested was\n invalid\n * :class:`stem.ProtocolError` if the geoip database is unavailable\n \"\"\"\n start_time = time.time()\n reply = {}\n if stem.util._is_str(params):\n is_multiple = False\n params = set([params])\n else:\n if not params:\n return {}\n is_multiple = True\n params = set(params)\n for param in params:\n if param.startswith('ip-to-country/') and param != 'ip-to-country/0.0.0.0' and self.is_geoip_unavailable():\n raise stem.ProtocolError('Tor geoip database is unavailable')\n elif param == 'address' and self._last_address_exc:\n raise self._last_address_exc\n elif param == 'fingerprint' and self._last_fingerprint_exc and (self.get_conf('ORPort', None) is None):\n raise self._last_fingerprint_exc\n from_cache = [param.lower() for param in params]\n cached_results = self._get_cache_map(from_cache, 'getinfo')\n for key in cached_results:\n user_expected_key = _case_insensitive_lookup(params, key)\n reply[user_expected_key] = cached_results[key]\n params.remove(user_expected_key)\n if not params:\n if LOG_CACHE_FETCHES:\n log.trace('GETINFO %s (cache fetch)' % ' '.join(reply.keys()))\n if is_multiple:\n return reply\n else:\n return list(reply.values())[0]\n try:\n response = self.msg('GETINFO %s' % ' '.join(params))\n stem.response.convert('GETINFO', response)\n response._assert_matches(params)\n if stem.prereq.is_python_3() and (not get_bytes):\n response.entries = dict(((k, stem.util.str_tools._to_unicode(v)) for k, v in response.entries.items()))\n reply.update(response.entries)\n if self.is_caching_enabled():\n to_cache = {}\n for key, value in response.entries.items():\n key = key.lower()\n if key in CACHEABLE_GETINFO_PARAMS or key in CACHEABLE_GETINFO_PARAMS_UNTIL_SETCONF:\n to_cache[key] = value\n elif key.startswith('ip-to-country/'):\n to_cache[key] = value\n self._set_cache(to_cache, 'getinfo')\n if 'address' in params:\n self._last_address_exc = None\n if 'fingerprint' in params:\n self._last_fingerprint_exc = None\n log.debug('GETINFO %s (runtime: %0.4f)' % (' '.join(params), time.time() - start_time))\n if is_multiple:\n return reply\n else:\n return list(reply.values())[0]\n except stem.ControllerError as exc:\n if 'address' in params:\n self._last_address_exc = exc\n if 'fingerprint' in params:\n self._last_fingerprint_exc = exc\n log.debug('GETINFO %s (failed: %s)' % (' '.join(params), exc))\n raise\n ", "context": "class Controller(BaseController):\n @with_default()\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000937.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "get_version", "tests": "import unittest\n\nclass Test_get_version(unittest.TestCase):\n @test.require.controller\n def test_get_version(self):\n \"\"\"\n Test that the convenient method get_version() works.\n \"\"\"\n runner = test.runner.get_runner()\n with runner.get_tor_controller() as controller:\n version = controller.get_version()\n self.assertTrue(isinstance(version, stem.version.Version))\n self.assertEqual(version, test.tor_version())\n\n @patch('stem.control.Controller.get_info')\n def test_get_version(self, get_info_mock):\n \"\"\"\n Exercises the get_version() method.\n \"\"\"\n try:\n version_2_1 = '0.2.1.32'\n version_2_1_object = stem.version.Version(version_2_1)\n get_info_mock.return_value = version_2_1\n self.assertEqual(version_2_1_object, self.controller.get_version())\n version_2_2 = '0.2.2.39'\n version_2_2_object = stem.version.Version(version_2_2)\n get_info_mock.return_value = version_2_2\n self.assertEqual(version_2_1_object, self.controller.get_version())\n self.controller._is_caching_enabled = False\n self.assertEqual(version_2_2_object, self.controller.get_version())\n get_info_mock.return_value = 'Tor 0.2.1.32'\n self.assertEqual(version_2_1_object, self.controller.get_version())\n get_info_mock.side_effect = InvalidArguments\n self.assertEqual('default returned', self.controller.get_version(default='default returned'))\n self.assertRaises(InvalidArguments, self.controller.get_version)\n version_A_42 = '0.A.42.spam'\n get_info_mock.return_value = version_A_42\n get_info_mock.side_effect = None\n self.assertRaises(ValueError, self.controller.get_version)\n finally:\n self.controller._is_caching_enabled = True\n", "method_code": " def get_version(self, default=UNDEFINED):\n \"\"\"\n get_version(default = UNDEFINED)\n \n A convenience method to get tor version that current controller is\n connected to.\n \n :param object default: response if the query fails\n \n :returns: :class:`~stem.version.Version` of the tor instance that we're\n connected to\n \n :raises:\n * :class:`stem.ControllerError` if unable to query the version\n * **ValueError** if unable to parse the version\n \n An exception is only raised if we weren't provided a default response.\n \"\"\"\n version = self._get_cache('version')\n if not version:\n version_str = self.get_info('version')\n version = stem.version.Version(version_str[4:] if version_str.startswith('Tor ') else version_str)\n self._set_cache({'version': version})\n return version\n ", "context": "class Controller(BaseController):\n @with_default()\n def get_version(self, default=UNDEFINED): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000938.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "get_exit_policy", "tests": "import unittest\n\nclass Test_get_exit_policy(unittest.TestCase):\n @test.require.controller\n def test_get_exit_policy(self):\n \"\"\"\n Sanity test for get_exit_policy(). Our 'ExitRelay 0' torrc entry causes us\n to have a simple reject-all policy.\n \"\"\"\n with test.runner.get_runner().get_tor_controller() as controller:\n self.assertEqual(ExitPolicy('reject *:*'), controller.get_exit_policy())\n\n @patch('stem.control.Controller.get_info')\n def test_get_exit_policy(self, get_info_mock):\n \"\"\"\n Exercises the get_exit_policy() method.\n \"\"\"\n get_info_mock.side_effect = lambda param, default=None: {'exit-policy/full': 'reject *:25,reject *:119,reject *:135-139,reject *:445,reject *:563,reject *:1214,reject *:4661-4666,reject *:6346-6429,reject *:6699,reject *:6881-6999,accept *:*'}[param]\n expected = ExitPolicy('reject *:25', 'reject *:119', 'reject *:135-139', 'reject *:445', 'reject *:563', 'reject *:1214', 'reject *:4661-4666', 'reject *:6346-6429', 'reject *:6699', 'reject *:6881-6999', 'accept *:*')\n self.assertEqual(str(expected), str(self.controller.get_exit_policy()))\n\n @patch('stem.control.Controller.get_info')\n @patch('stem.control.Controller.get_conf')\n def test_get_exit_policy_if_not_relaying(self, get_conf_mock, get_info_mock):\n get_conf_mock.side_effect = lambda param, **kwargs: {'ExitRelay': '1', 'ExitPolicyRejectPrivate': '1', 'ExitPolicy': ['accept *:80, accept *:443', 'accept 43.5.5.5,reject *:22']}[param]\n expected = ExitPolicy('reject 0.0.0.0/8:*', 'reject 169.254.0.0/16:*', 'reject 127.0.0.0/8:*', 'reject 192.168.0.0/16:*', 'reject 10.0.0.0/8:*', 'reject 172.16.0.0/12:*', 'reject 1.2.3.4:*', 'accept *:80', 'accept *:443', 'accept 43.5.5.5:*', 'reject *:22')\n exit_policy_exception = None\n\n def getinfo_response(param, default=None):\n if param == 'address':\n return '1.2.3.4'\n elif param == 'exit-policy/default':\n return ''\n elif param == 'exit-policy/full' and exit_policy_exception:\n raise exit_policy_exception\n else:\n raise ValueError(\"Unmocked request for 'GETINFO %s'\" % param)\n get_info_mock.side_effect = getinfo_response\n exit_policy_exception = stem.OperationFailed('552', 'Not running in server mode')\n self.assertEqual(str(expected), str(self.controller.get_exit_policy()))\n exit_policy_exception = stem.OperationFailed('551', 'Descriptor still rebuilding - not ready yet')\n self.assertEqual(str(expected), str(self.controller.get_exit_policy()))\n", "method_code": " def get_exit_policy(self, default=UNDEFINED):\n \"\"\"\n get_exit_policy(default = UNDEFINED)\n \n Effective ExitPolicy for our relay.\n \n .. versionchanged:: 1.7.0\n Policies retrieved through 'GETINFO exit-policy/full' rather than\n parsing the user's torrc entries. This should be more reliable for\n some edge cases. (:trac:`25739`)\n \n :param object default: response if the query fails\n \n :returns: :class:`~stem.exit_policy.ExitPolicy` of the tor instance that\n we're connected to\n \n :raises:\n * :class:`stem.ControllerError` if unable to query the policy\n * **ValueError** if unable to parse the policy\n \n An exception is only raised if we weren't provided a default response.\n \"\"\"\n policy = self._get_cache('exit_policy')\n if not policy:\n try:\n policy = stem.exit_policy.ExitPolicy(*self.get_info('exit-policy/full').splitlines())\n self._set_cache({'exit_policy': policy})\n except stem.OperationFailed:\n rules = []\n if self.get_conf('ExitRelay') == '0':\n rules.append('reject *:*')\n if self.get_conf('ExitPolicyRejectPrivate') == '1':\n rules.append('reject private:*')\n for policy_line in self.get_conf('ExitPolicy', multiple=True):\n rules += policy_line.split(',')\n rules += self.get_info('exit-policy/default').split(',')\n policy = stem.exit_policy.get_config_policy(rules, self.get_info('address', None))\n return policy\n ", "context": "class Controller(BaseController):\n @with_default()\n def get_exit_policy(self, default=UNDEFINED): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000939.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "authenticate", "tests": "import unittest\n\nclass Test_authenticate(unittest.TestCase):\n @test.require.controller\n def test_authenticate(self):\n \"\"\"\n Test that the convenient method authenticate() works.\n \"\"\"\n runner = test.runner.get_runner()\n with runner.get_tor_controller(False) as controller:\n controller.authenticate(test.runner.CONTROL_PASSWORD)\n test.runner.exercise_controller(self, controller)\n", "method_code": " def authenticate(self, *args, **kwargs):\n \"\"\"\n A convenience method to authenticate the controller. This is just a\n pass-through to :func:`stem.connection.authenticate`.\n \"\"\"\n import stem.connection\n stem.connection.authenticate(self, *args, **kwargs)\n ", "context": "class Controller(BaseController):\n def authenticate(self, *args, **kwargs): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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, 1], "pynose_source_file": "test_000940.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "get_protocolinfo", "tests": "import unittest\n\nclass Test_get_protocolinfo(unittest.TestCase):\n @test.require.controller\n def test_protocolinfo(self):\n \"\"\"\n Test that the convenient method protocolinfo() works.\n \"\"\"\n runner = test.runner.get_runner()\n with runner.get_tor_controller(False) as controller:\n protocolinfo = controller.get_protocolinfo()\n self.assertTrue(isinstance(protocolinfo, stem.response.protocolinfo.ProtocolInfoResponse))\n tor_options = runner.get_options()\n auth_methods = []\n if test.runner.Torrc.COOKIE in tor_options:\n auth_methods.append(stem.response.protocolinfo.AuthMethod.COOKIE)\n if test.tor_version() >= stem.version.Requirement.AUTH_SAFECOOKIE:\n auth_methods.append(stem.response.protocolinfo.AuthMethod.SAFECOOKIE)\n if test.runner.Torrc.PASSWORD in tor_options:\n auth_methods.append(stem.response.protocolinfo.AuthMethod.PASSWORD)\n if not auth_methods:\n auth_methods.append(stem.response.protocolinfo.AuthMethod.NONE)\n self.assertEqual(tuple(auth_methods), protocolinfo.auth_methods)\n\n @patch('stem.connection.get_protocolinfo')\n def test_get_protocolinfo(self, get_protocolinfo_mock):\n \"\"\"\n Exercises the get_protocolinfo() method.\n \"\"\"\n protocolinfo_msg = ControlMessage.from_str('250-PROTOCOLINFO 1\\r\\n250 OK\\r\\n', 'PROTOCOLINFO')\n get_protocolinfo_mock.return_value = protocolinfo_msg\n self.assertEqual(str(protocolinfo_msg), str(self.controller.get_protocolinfo()))\n get_protocolinfo_mock.side_effect = ProtocolError\n self.assertEqual('default returned', self.controller.get_protocolinfo(default='default returned'))\n self.assertRaises(ProtocolError, self.controller.get_protocolinfo)\n", "method_code": " def get_protocolinfo(self, default=UNDEFINED):\n \"\"\"\n get_protocolinfo(default = UNDEFINED)\n \n A convenience method to get the protocol info of the controller.\n \n :param object default: response if the query fails\n \n :returns: :class:`~stem.response.protocolinfo.ProtocolInfoResponse` provided by tor\n \n :raises:\n * :class:`stem.ProtocolError` if the PROTOCOLINFO response is\n malformed\n * :class:`stem.SocketError` if problems arise in establishing or\n using the socket\n \n An exception is only raised if we weren't provided a default response.\n \"\"\"\n import stem.connection\n return stem.connection.get_protocolinfo(self)\n ", "context": "class Controller(BaseController):\n @with_default()\n def get_protocolinfo(self, default=UNDEFINED): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000941.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "get_conf", "tests": "import unittest\n\nclass Test_get_conf(unittest.TestCase):\n @test.require.controller\n def test_getconf(self):\n \"\"\"\n Exercises GETCONF with valid and invalid queries.\n \"\"\"\n runner = test.runner.get_runner()\n with runner.get_tor_controller() as controller:\n control_socket = controller.get_socket()\n if isinstance(control_socket, stem.socket.ControlPort):\n connection_value = str(control_socket.port)\n config_key = 'ControlPort'\n elif isinstance(control_socket, stem.socket.ControlSocketFile):\n connection_value = control_socket.path\n config_key = 'ControlSocket'\n self.assertEqual(connection_value, controller.get_conf(config_key))\n self.assertEqual(connection_value, controller.get_conf(config_key, 'la-di-dah'))\n expected = {config_key: [connection_value]}\n self.assertEqual(expected, controller.get_conf_map([config_key]))\n self.assertEqual(expected, controller.get_conf_map([config_key], 'la-di-dah'))\n request_params = ['ControlPORT', 'dirport', 'datadirectory']\n reply_params = controller.get_conf_map(request_params, multiple=False).keys()\n self.assertEqual(set(request_params), set(reply_params))\n self.assertEqual(None, controller.get_conf('HTTPSProxy'))\n self.assertEqual('la-di-dah', controller.get_conf('HTTPSProxy', 'la-di-dah'))\n self.assertEqual([], controller.get_conf('HTTPSProxy', [], multiple=True))\n self.assertRaises(stem.InvalidArguments, controller.get_conf, 'blarg')\n self.assertEqual('la-di-dah', controller.get_conf('blarg', 'la-di-dah'))\n self.assertRaises(stem.InvalidArguments, controller.get_conf_map, 'blarg')\n self.assertEqual({'blarg': 'la-di-dah'}, controller.get_conf_map('blarg', 'la-di-dah'))\n self.assertRaises(stem.InvalidRequest, controller.get_conf_map, ['blarg', 'huadf'], multiple=True)\n self.assertEqual({'erfusdj': 'la-di-dah', 'afiafj': 'la-di-dah'}, controller.get_conf_map(['erfusdj', 'afiafj'], 'la-di-dah', multiple=True))\n nodefamilies = [('abc', 'xyz', 'pqrs'), ('mno', 'tuv', 'wxyz')]\n controller.msg('SETCONF %s' % ' '.join(['nodefamily=\"' + ','.join(x) + '\"' for x in nodefamilies]))\n self.assertEqual([','.join(n) for n in nodefamilies], controller.get_conf('nodefamily', multiple=True))\n controller.msg('RESETCONF NodeFamily')\n self.assertEqual(None, controller.get_conf(''))\n self.assertEqual({}, controller.get_conf_map([]))\n self.assertEqual({}, controller.get_conf_map(['']))\n self.assertEqual(None, controller.get_conf(' '))\n self.assertEqual({}, controller.get_conf_map([' ', ' ']))\n self.assertEqual('la-di-dah', controller.get_conf('', 'la-di-dah'))\n self.assertEqual({}, controller.get_conf_map('', 'la-di-dah'))\n self.assertEqual({}, controller.get_conf_map([], 'la-di-dah'))\n", "method_code": " def get_conf(self, param, default=UNDEFINED, multiple=False):\n \"\"\"\n get_conf(param, default = UNDEFINED, multiple = False)\n \n Queries the current value for a configuration option. Some configuration\n options (like the ExitPolicy) can have multiple values. This provides a\n **list** with all of the values if **multiple** is **True**. Otherwise this\n will be a **str** with the first value.\n \n If provided with a **default** then that is provided if the configuration\n option was unset or the query fails (invalid configuration option, error\n response, control port closed, initiated, etc).\n \n If the configuration value is unset and no **default** was given then this\n provides **None** if **multiple** was **False** and an empty list if it was\n **True**.\n \n :param str param: configuration option to be queried\n :param object default: response if the option is unset or the query fails\n :param bool multiple: if **True** then provides a list with all of the\n present values (this is an empty list if the config option is unset)\n \n :returns:\n Response depends upon how we were called as follows...\n \n * **str** with the configuration value if **multiple** was **False**,\n **None** if it was unset\n * **list** with the response strings if multiple was **True**\n * default if one was provided and the configuration option was either\n unset or our call failed\n \n :raises:\n * :class:`stem.ControllerError` if the call fails and we weren't\n provided a default response\n * :class:`stem.InvalidArguments` if the configuration option\n requested was invalid\n \"\"\"\n param = param.lower().strip()\n if not param:\n return default if default != UNDEFINED else None\n entries = self.get_conf_map(param, default, multiple)\n return _case_insensitive_lookup(entries, param, default)\n ", "context": "class Controller(BaseController):\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000942.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "is_set", "tests": "import unittest\n\nclass Test_is_set(unittest.TestCase):\n @test.require.controller\n def test_is_set(self):\n \"\"\"\n Exercises our is_set() method.\n \"\"\"\n runner = test.runner.get_runner()\n with runner.get_tor_controller() as controller:\n custom_options = controller._get_custom_options()\n self.assertTrue('ControlPort' in custom_options or 'ControlSocket' in custom_options)\n self.assertEqual('1', custom_options['DownloadExtraInfo'])\n self.assertEqual('1112', custom_options['SocksPort'])\n self.assertTrue(controller.is_set('DownloadExtraInfo'))\n self.assertTrue(controller.is_set('SocksPort'))\n self.assertFalse(controller.is_set('CellStatistics'))\n self.assertFalse(controller.is_set('ConnLimit'))\n controller.set_conf('ConnLimit', '1005')\n self.assertTrue(controller.is_set('ConnLimit'))\n controller.reset_conf('ConnLimit')\n self.assertFalse(controller.is_set('ConnLimit'))\n", "method_code": " def is_set(self, param, default=UNDEFINED):\n \"\"\"\n is_set(param, default = UNDEFINED)\n \n Checks if a configuration option differs from its default or not.\n \n .. versionadded:: 1.5.0\n \n :param str param: configuration option to check\n :param object default: response if the query fails\n \n :returns: **True** if option differs from its default and **False**\n otherwise\n \n :raises: :class:`stem.ControllerError` if the call fails and we weren't\n provided a default response\n \"\"\"\n return param in self._get_custom_options()\n ", "context": "class Controller(BaseController):\n @with_default()\n def is_set(self, param, default=UNDEFINED): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000943.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "set_hidden_service_conf", "tests": "import unittest\n\nclass Test_set_hidden_service_conf(unittest.TestCase):\n @test.require.controller\n def test_hidden_services_conf(self):\n \"\"\"\n Exercises the hidden service family of methods (get_hidden_service_conf,\n set_hidden_service_conf, create_hidden_service, and remove_hidden_service).\n \"\"\"\n runner = test.runner.get_runner()\n test_dir = runner.get_test_dir()\n service1_path = os.path.join(test_dir, 'test_hidden_service1')\n service2_path = os.path.join(test_dir, 'test_hidden_service2')\n service3_path = os.path.join(test_dir, 'test_hidden_service3')\n service4_path = os.path.join(test_dir, 'test_hidden_service4')\n with runner.get_tor_controller() as controller:\n try:\n self.assertEqual({}, controller.get_hidden_service_conf())\n controller.set_hidden_service_conf({})\n self.assertEqual({}, controller.get_hidden_service_conf())\n initialconf = {service1_path: {'HiddenServicePort': [(8020, '127.0.0.1', 8020), (8021, '127.0.0.1', 8021)], 'HiddenServiceVersion': '2'}, service2_path: {'HiddenServiceVersion': '2', 'HiddenServiceAuthorizeClient': 'stealth a, b', 'HiddenServicePort': [(8030, '127.0.0.1', 8030), (8031, '127.0.0.1', 8031), (8032, '127.0.0.1', 8032)]}}\n controller.set_hidden_service_conf(initialconf)\n self.assertEqual(initialconf, controller.get_hidden_service_conf())\n self.assertEqual(None, controller.create_hidden_service(service1_path, 8020))\n self.assertEqual(None, controller.create_hidden_service(service1_path, 8021, target_port=8021))\n self.assertEqual(initialconf, controller.get_hidden_service_conf())\n hs_path = os.path.join(os.getcwd(), service3_path)\n hs_address1 = controller.create_hidden_service(hs_path, 8888).hostname\n hs_address2 = controller.create_hidden_service(hs_path, 8989, target_port=8021).hostname\n self.assertEqual(hs_address1, hs_address2)\n self.assertTrue(hs_address1.endswith('.onion'))\n conf = controller.get_hidden_service_conf()\n self.assertEqual(3, len(conf))\n self.assertEqual(2, len(conf[hs_path]['HiddenServicePort']))\n controller.remove_hidden_service(hs_path, 8888)\n self.assertEqual(3, len(controller.get_hidden_service_conf()))\n controller.remove_hidden_service(hs_path, 8989)\n self.assertEqual(2, len(controller.get_hidden_service_conf()))\n hs_path = os.path.join(os.getcwd(), service4_path)\n hs_attributes = controller.create_hidden_service(hs_path, 8888, auth_type='basic', client_names=['c1', 'c2'])\n self.assertEqual(2, len(hs_attributes.hostname.splitlines()))\n self.assertEqual(2, len(hs_attributes.hostname_for_client))\n self.assertTrue(hs_attributes.hostname_for_client['c1'].endswith('.onion'))\n self.assertTrue(hs_attributes.hostname_for_client['c2'].endswith('.onion'))\n conf = controller.get_hidden_service_conf()\n self.assertEqual(3, len(conf))\n self.assertEqual(1, len(conf[hs_path]['HiddenServicePort']))\n controller.remove_hidden_service(hs_path, 8888)\n self.assertEqual(2, len(controller.get_hidden_service_conf()))\n finally:\n controller.set_hidden_service_conf({})\n for path in (service1_path, service2_path, service3_path, service4_path):\n try:\n shutil.rmtree(path)\n except:\n pass\n", "method_code": " def set_hidden_service_conf(self, conf):\n \"\"\"\n Update all the configured hidden services from a dictionary having\n the same format as\n :func:`~stem.control.Controller.get_hidden_service_conf`.\n \n For convenience the HiddenServicePort entries can be an integer, string, or\n tuple. If an **int** then we treat it as just a port. If a **str** we pass\n that directly as the HiddenServicePort. And finally, if a **tuple** then\n it's expected to be the **(port, target_address, target_port)** as provided\n by :func:`~stem.control.Controller.get_hidden_service_conf`.\n \n This is to say the following three are equivalent...\n \n ::\n \n \"HiddenServicePort\": [\n 80,\n '80 127.0.0.1:80',\n (80, '127.0.0.1', 80),\n ]\n \n .. versionadded:: 1.3.0\n \n :param dict conf: configuration dictionary\n \n :raises:\n * :class:`stem.ControllerError` if the call fails\n * :class:`stem.InvalidArguments` if configuration options\n requested was invalid\n * :class:`stem.InvalidRequest` if the configuration setting is\n impossible or if there's a syntax error in the configuration values\n \"\"\"\n if not conf:\n self.reset_conf('HiddenServiceDir')\n return\n hidden_service_options = []\n for directory in conf:\n hidden_service_options.append(('HiddenServiceDir', directory))\n for k, v in list(conf[directory].items()):\n if k == 'HiddenServicePort':\n for entry in v:\n if isinstance(entry, int):\n entry = '%s 127.0.0.1:%s' % (entry, entry)\n elif isinstance(entry, str):\n pass\n elif isinstance(entry, tuple):\n port, target_address, target_port = entry\n entry = '%s %s:%s' % (port, target_address, target_port)\n hidden_service_options.append(('HiddenServicePort', entry))\n else:\n hidden_service_options.append((k, str(v)))\n self.set_options(hidden_service_options)\n ", "context": "class Controller(BaseController):\n def set_hidden_service_conf(self, conf): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000944.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "list_ephemeral_hidden_services", "tests": "import unittest\n\nclass Test_list_ephemeral_hidden_services(unittest.TestCase):\n @test.require.controller\n @test.require.version(Requirement.ADD_ONION)\n def test_without_ephemeral_hidden_services(self):\n \"\"\"\n Exercises ephemeral hidden service methods when none are present.\n \"\"\"\n with test.runner.get_runner().get_tor_controller() as controller:\n self.assertEqual([], controller.list_ephemeral_hidden_services())\n self.assertEqual([], controller.list_ephemeral_hidden_services(detached=True))\n self.assertEqual(False, controller.remove_ephemeral_hidden_service('gfzprpioee3hoppz'))\n\n @test.require.controller\n @test.require.version(Requirement.ADD_ONION)\n def test_ephemeral_hidden_services_v2(self):\n \"\"\"\n Exercises creating v2 ephemeral hidden services.\n \"\"\"\n runner = test.runner.get_runner()\n with runner.get_tor_controller() as controller:\n response = controller.create_ephemeral_hidden_service(4567, key_content='RSA1024')\n self.assertEqual([response.service_id], controller.list_ephemeral_hidden_services())\n self.assertTrue(response.private_key is not None)\n self.assertEqual('RSA1024', response.private_key_type)\n self.assertEqual({}, response.client_auth)\n self.assertEqual(True, controller.remove_ephemeral_hidden_service(response.service_id))\n self.assertEqual([], controller.list_ephemeral_hidden_services())\n recreate_response = controller.create_ephemeral_hidden_service(4567, key_type=response.private_key_type, key_content=response.private_key)\n self.assertEqual([response.service_id], controller.list_ephemeral_hidden_services())\n self.assertEqual(response.service_id, recreate_response.service_id)\n self.assertEqual(None, recreate_response.private_key)\n self.assertEqual(None, recreate_response.private_key_type)\n response = controller.create_ephemeral_hidden_service(4568, key_content='RSA1024', discard_key=True)\n self.assertTrue(response.service_id in controller.list_ephemeral_hidden_services())\n self.assertEqual(None, response.private_key)\n self.assertEqual(None, response.private_key_type)\n with runner.get_tor_controller() as second_controller:\n self.assertEqual(2, len(controller.list_ephemeral_hidden_services()))\n self.assertEqual(0, len(second_controller.list_ephemeral_hidden_services()))\n\n @test.require.controller\n @test.require.version(Requirement.HIDDEN_SERVICE_V3)\n def test_ephemeral_hidden_services_v3(self):\n \"\"\"\n Exercises creating v3 ephemeral hidden services.\n \"\"\"\n runner = test.runner.get_runner()\n with runner.get_tor_controller() as controller:\n response = controller.create_ephemeral_hidden_service(4567, key_content='ED25519-V3')\n self.assertEqual([response.service_id], controller.list_ephemeral_hidden_services())\n self.assertTrue(response.private_key is not None)\n self.assertEqual('ED25519-V3', response.private_key_type)\n self.assertEqual({}, response.client_auth)\n self.assertEqual(True, controller.remove_ephemeral_hidden_service(response.service_id))\n self.assertEqual([], controller.list_ephemeral_hidden_services())\n recreate_response = controller.create_ephemeral_hidden_service(4567, key_type=response.private_key_type, key_content=response.private_key)\n self.assertEqual([response.service_id], controller.list_ephemeral_hidden_services())\n self.assertEqual(response.service_id, recreate_response.service_id)\n self.assertEqual(None, recreate_response.private_key)\n self.assertEqual(None, recreate_response.private_key_type)\n response = controller.create_ephemeral_hidden_service(4568, key_content='ED25519-V3', discard_key=True)\n self.assertTrue(response.service_id in controller.list_ephemeral_hidden_services())\n self.assertEqual(None, response.private_key)\n self.assertEqual(None, response.private_key_type)\n with runner.get_tor_controller() as second_controller:\n self.assertEqual(2, len(controller.list_ephemeral_hidden_services()))\n self.assertEqual(0, len(second_controller.list_ephemeral_hidden_services()))\n\n @test.require.controller\n @test.require.version(Requirement.ADD_ONION_BASIC_AUTH)\n def test_with_ephemeral_hidden_services_basic_auth(self):\n \"\"\"\n Exercises creating ephemeral hidden services that uses basic authentication.\n \"\"\"\n runner = test.runner.get_runner()\n with runner.get_tor_controller() as controller:\n response = controller.create_ephemeral_hidden_service(4567, basic_auth={'alice': 'nKwfvVPmTNr2k2pG0pzV4g', 'bob': None})\n self.assertEqual([response.service_id], controller.list_ephemeral_hidden_services())\n self.assertTrue(response.private_key is not None)\n self.assertEqual(['bob'], list(response.client_auth.keys()))\n self.assertEqual(True, controller.remove_ephemeral_hidden_service(response.service_id))\n self.assertEqual([], controller.list_ephemeral_hidden_services())\n\n @test.require.controller\n @test.require.version(Requirement.ADD_ONION)\n def test_with_detached_ephemeral_hidden_services(self):\n \"\"\"\n Exercises creating detached ephemeral hidden services and methods when\n they're present.\n \"\"\"\n runner = test.runner.get_runner()\n with runner.get_tor_controller() as controller:\n response = controller.create_ephemeral_hidden_service(4567, detached=True)\n self.assertEqual([], controller.list_ephemeral_hidden_services())\n self.assertEqual([response.service_id], controller.list_ephemeral_hidden_services(detached=True))\n self.assertEqual(True, controller.remove_ephemeral_hidden_service(response.service_id))\n self.assertEqual([], controller.list_ephemeral_hidden_services(detached=True))\n controller.create_ephemeral_hidden_service(4567, key_type=response.private_key_type, key_content=response.private_key, detached=True)\n self.assertEqual([response.service_id], controller.list_ephemeral_hidden_services(detached=True))\n with runner.get_tor_controller() as second_controller:\n self.assertEqual([response.service_id], second_controller.list_ephemeral_hidden_services(detached=True))\n self.assertEqual(True, second_controller.remove_ephemeral_hidden_service(response.service_id))\n self.assertEqual([], controller.list_ephemeral_hidden_services(detached=True))\n response = second_controller.create_ephemeral_hidden_service(4567, detached=True)\n self.assertEqual([response.service_id], controller.list_ephemeral_hidden_services(detached=True))\n controller.remove_ephemeral_hidden_service(response.service_id)\n", "method_code": " def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False):\n \"\"\"\n list_ephemeral_hidden_services(default = UNDEFINED, our_services = True, detached = False)\n \n Lists hidden service addresses created by\n :func:`~stem.control.Controller.create_ephemeral_hidden_service`.\n \n .. versionadded:: 1.4.0\n \n .. versionchanged:: 1.6.0\n Tor change caused this to start providing empty strings if unset\n (:trac:`21329`).\n \n :param object default: response if the query fails\n :param bool our_services: include services created with this controller\n that weren't flagged as 'detached'\n :param bool detached: include services whos contiuation isn't tied to a\n controller\n \n :returns: **list** of hidden service addresses without their '.onion'\n suffix\n \n :raises: :class:`stem.ControllerError` if the call fails and we weren't\n provided a default response\n \"\"\"\n if self.get_version() < stem.version.Requirement.ADD_ONION:\n raise stem.UnsatisfiableRequest(message='Ephemeral hidden services were added in tor version %s' % stem.version.Requirement.ADD_ONION)\n result = []\n if our_services:\n try:\n result += self.get_info('onions/current').split('\\n')\n except stem.ProtocolError as exc:\n if 'No onion services of the specified type.' not in str(exc):\n raise\n if detached:\n try:\n result += self.get_info('onions/detached').split('\\n')\n except stem.ProtocolError as exc:\n if 'No onion services of the specified type.' not in str(exc):\n raise\n return [r for r in result if r]\n ", "context": "class Controller(BaseController):\n @with_default()\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000945.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "set_conf", "tests": "import unittest\n\nclass Test_set_conf(unittest.TestCase):\n @test.require.controller\n def test_set_conf(self):\n \"\"\"\n Exercises set_conf(), reset_conf(), and set_options() methods with valid\n and invalid requests.\n \"\"\"\n runner = test.runner.get_runner()\n tmpdir = tempfile.mkdtemp()\n with runner.get_tor_controller() as controller:\n try:\n connlimit = int(controller.get_conf('ConnLimit'))\n controller.set_conf('connlimit', str(connlimit - 1))\n self.assertEqual(connlimit - 1, int(controller.get_conf('ConnLimit')))\n exit_policy = ['accept *:7777', 'reject *:*']\n controller.set_conf('ExitPolicy', exit_policy)\n self.assertEqual(exit_policy, controller.get_conf('ExitPolicy', multiple=True))\n try:\n controller.set_conf('invalidkeyboo', 'abcde')\n self.fail()\n except stem.InvalidArguments as exc:\n self.assertEqual(['invalidkeyboo'], exc.arguments)\n controller.reset_conf('ConnLimit', 'ExitPolicy')\n self.assertEqual(connlimit, int(controller.get_conf('ConnLimit')))\n self.assertEqual(None, controller.get_conf('ExitPolicy'))\n controller.set_options({'connlimit': str(connlimit - 2), 'contactinfo': 'stem@testing'})\n self.assertEqual(connlimit - 2, int(controller.get_conf('ConnLimit')))\n self.assertEqual('stem@testing', controller.get_conf('contactinfo'))\n try:\n controller.set_options({'contactinfo': 'stem@testing', 'bombay': 'vadapav'})\n self.fail()\n except stem.InvalidArguments as exc:\n self.assertEqual(['bombay'], exc.arguments)\n controller.set_options((('HiddenServiceDir', tmpdir), ('HiddenServicePort', '17234 127.0.0.1:17235')))\n self.assertEqual(tmpdir, controller.get_conf('HiddenServiceDir'))\n self.assertEqual('17234 127.0.0.1:17235', controller.get_conf('HiddenServicePort'))\n finally:\n controller.set_options((('ExitPolicy', 'reject *:*'), ('ConnLimit', None), ('ContactInfo', None), ('HiddenServiceDir', None), ('HiddenServicePort', None)), reset=True)\n shutil.rmtree(tmpdir)\n", "method_code": " def set_conf(self, param, value):\n \"\"\"\n Changes the value of a tor configuration option. Our value can be any of\n the following...\n \n * a string to set a single value\n * a list of strings to set a series of values (for instance the ExitPolicy)\n * None to either set the value to 0/NULL\n \n :param str param: configuration option to be set\n :param str,list value: value to set the parameter to\n \n :raises:\n * :class:`stem.ControllerError` if the call fails\n * :class:`stem.InvalidArguments` if configuration options\n requested was invalid\n * :class:`stem.InvalidRequest` if the configuration setting is\n impossible or if there's a syntax error in the configuration values\n \"\"\"\n self.set_options({param: value}, False)\n ", "context": "class Controller(BaseController):\n def set_conf(self, param, value): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000946.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "load_conf", "tests": "import unittest\n\nclass Test_load_conf(unittest.TestCase):\n @test.require.controller\n @test.require.version(Requirement.LOADCONF)\n def test_loadconf(self):\n \"\"\"\n Exercises Controller.load_conf with valid and invalid requests.\n \"\"\"\n runner = test.runner.get_runner()\n with runner.get_tor_controller() as controller:\n oldconf = runner.get_torrc_contents()\n try:\n self.assertRaises(stem.InvalidRequest, controller.load_conf, 'ContactInfo confloaded')\n try:\n controller.load_conf('Blahblah blah')\n self.fail()\n except stem.InvalidArguments as exc:\n self.assertEqual(['Blahblah'], exc.arguments)\n controller.load_conf(runner.get_torrc_contents() + '\\nContactInfo confloaded\\n')\n self.assertEqual('confloaded', controller.get_conf('ContactInfo'))\n finally:\n controller.load_conf(oldconf)\n controller.reset_conf('__OwningControllerProcess')\n", "method_code": " def load_conf(self, configtext):\n \"\"\"\n Sends the configuration text to Tor and loads it as if it has been read from\n the torrc.\n \n :param str configtext: the configuration text\n \n :raises: :class:`stem.ControllerError` if the call fails\n \"\"\"\n response = self.msg('LOADCONF\\n%s' % configtext)\n stem.response.convert('SINGLELINE', response)\n if response.code in ('552', '553'):\n if response.code == '552' and response.message.startswith('Invalid config file: Failed to parse/validate config: Unknown option'):\n raise stem.InvalidArguments(response.code, response.message, [response.message[70:response.message.find('.', 70) - 1]])\n raise stem.InvalidRequest(response.code, response.message)\n elif not response.is_ok():\n raise stem.ProtocolError('+LOADCONF Received unexpected response\\n%s' % str(response))\n ", "context": "class Controller(BaseController):\n def load_conf(self, configtext): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000947.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "save_conf", "tests": "import unittest\n\nclass Test_save_conf(unittest.TestCase):\n @test.require.controller\n def test_saveconf(self):\n runner = test.runner.get_runner()\n with runner.get_tor_controller() as controller:\n oldconf = runner.get_torrc_contents()\n try:\n controller.set_conf('ContactInfo', 'confsaved')\n controller.save_conf()\n with open(runner.get_torrc_path()) as torrcfile:\n self.assertTrue('\\nContactInfo confsaved\\n' in torrcfile.read())\n finally:\n controller.load_conf(oldconf)\n controller.save_conf()\n controller.reset_conf('__OwningControllerProcess')\n", "method_code": " def save_conf(self, force=False):\n \"\"\"\n Saves the current configuration options into the active torrc file.\n \n .. versionchanged:: 1.6.0\n Added the force argument.\n \n :param bool force: overwrite the configuration even if it includes a\n '%include' clause, this is ignored if tor doesn't support it\n \n :raises:\n * :class:`stem.ControllerError` if the call fails\n * :class:`stem.OperationFailed` if the client is unable to save\n the configuration file\n \"\"\"\n if self.get_version() < stem.version.Requirement.SAVECONF_FORCE:\n force = False\n response = self.msg('SAVECONF FORCE' if force else 'SAVECONF')\n stem.response.convert('SINGLELINE', response)\n if response.is_ok():\n return True\n elif response.code == '551':\n raise stem.OperationFailed(response.code, response.message)\n else:\n raise stem.ProtocolError('SAVECONF returned unexpected response code')\n ", "context": "class Controller(BaseController):\n def save_conf(self, force=False): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000948.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "get_ports", "tests": "import unittest\n\nclass Test_get_ports(unittest.TestCase):\n @test.require.controller\n def test_get_ports(self):\n \"\"\"\n Test Controller.get_ports against a running tor instance.\n \"\"\"\n runner = test.runner.get_runner()\n with runner.get_tor_controller() as controller:\n self.assertEqual([test.runner.ORPORT], controller.get_ports(Listener.OR))\n self.assertEqual([], controller.get_ports(Listener.DIR))\n self.assertEqual([test.runner.SOCKS_PORT], controller.get_ports(Listener.SOCKS))\n self.assertEqual([], controller.get_ports(Listener.TRANS))\n self.assertEqual([], controller.get_ports(Listener.NATD))\n self.assertEqual([], controller.get_ports(Listener.DNS))\n if test.runner.Torrc.PORT in runner.get_options():\n self.assertEqual([test.runner.CONTROL_PORT], controller.get_ports(Listener.CONTROL))\n else:\n self.assertEqual([], controller.get_ports(Listener.CONTROL))\n\n @patch('stem.control.Controller.get_info')\n @patch('stem.control.Controller.get_conf')\n def test_get_ports(self, get_conf_mock, get_info_mock):\n \"\"\"\n Exercises the get_ports() and get_listeners() methods.\n \"\"\"\n get_info_mock.side_effect = InvalidArguments\n get_conf_mock.side_effect = lambda param, **kwargs: {'ControlPort': '9050', 'ControlListenAddress': ['127.0.0.1']}[param]\n self.assertEqual([('127.0.0.1', 9050)], self.controller.get_listeners(Listener.CONTROL))\n self.assertEqual([9050], self.controller.get_ports(Listener.CONTROL))\n self.controller.clear_cache()\n get_conf_mock.side_effect = lambda param, **kwargs: {'ControlPort': '9050', 'ControlListenAddress': ['27.4.4.1']}[param]\n self.assertEqual([('27.4.4.1', 9050)], self.controller.get_listeners(Listener.CONTROL))\n self.assertEqual([], self.controller.get_ports(Listener.CONTROL))\n self.controller.clear_cache()\n get_info_mock.side_effect = None\n get_info_mock.return_value = '\"127.0.0.1:1112\" \"127.0.0.1:1114\"'\n self.assertEqual([('127.0.0.1', 1112), ('127.0.0.1', 1114)], self.controller.get_listeners(Listener.CONTROL))\n self.assertEqual([1112, 1114], self.controller.get_ports(Listener.CONTROL))\n self.controller.clear_cache()\n get_info_mock.side_effect = None\n get_info_mock.return_value = '\"27.4.4.1:1113\" \"127.0.0.5:1114\" \"0.0.0.0:1115\" \"[::]:1116\" \"[::1]:1117\" \"[10::]:1118\"'\n self.assertEqual([1114, 1115, 1116, 1117], self.controller.get_ports(Listener.OR))\n self.controller.clear_cache()\n get_info_mock.return_value = '\"0.0.0.0:9001\" \"[fe80:0000:0000:0000:0202:b3ff:fe1e:8329]:9001\"'\n self.assertEqual([('0.0.0.0', 9001), ('fe80:0000:0000:0000:0202:b3ff:fe1e:8329', 9001)], self.controller.get_listeners(Listener.CONTROL))\n self.controller.clear_cache()\n get_info_mock.return_value = '\"unix:/tmp/tor/socket\"'\n self.assertEqual([], self.controller.get_listeners(Listener.CONTROL))\n self.assertEqual([], self.controller.get_ports(Listener.CONTROL))\n", "method_code": " def get_ports(self, listener_type, default=UNDEFINED):\n \"\"\"\n get_ports(listener_type, default = UNDEFINED)\n \n Provides the local ports where tor is listening for the given type of\n connections. This is similar to\n :func:`~stem.control.Controller.get_listeners`, but doesn't provide\n addresses nor include non-local endpoints.\n \n .. versionadded:: 1.2.0\n \n :param stem.control.Listener listener_type: connection type being handled\n by the ports we return\n :param object default: response if the query fails\n \n :returns: **list** of **ints** for the local ports where tor handles\n connections of the given type\n \n :raises: :class:`stem.ControllerError` if unable to determine the ports\n and no default was provided\n \"\"\"\n \n def is_localhost(address):\n if stem.util.connection.is_valid_ipv4_address(address):\n return address == '0.0.0.0' or address.startswith('127.')\n elif stem.util.connection.is_valid_ipv6_address(address):\n return stem.util.connection.expand_ipv6_address(address) in ('0000:0000:0000:0000:0000:0000:0000:0000', '0000:0000:0000:0000:0000:0000:0000:0001')\n else:\n log.info(\"Request for %s ports got an address that's neither IPv4 or IPv6: %s\" % (listener_type, address))\n return False\n return [port for addr, port in self.get_listeners(listener_type) if is_localhost(addr)]\n ", "context": "class Controller(BaseController):\n @with_default()\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000949.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "get_listeners", "tests": "import unittest\n\nclass Test_get_listeners(unittest.TestCase):\n @test.require.controller\n def test_get_listeners(self):\n \"\"\"\n Test Controller.get_listeners against a running tor instance.\n \"\"\"\n runner = test.runner.get_runner()\n with runner.get_tor_controller() as controller:\n self.assertEqual([('0.0.0.0', test.runner.ORPORT)], controller.get_listeners(Listener.OR))\n self.assertEqual([], controller.get_listeners(Listener.DIR))\n self.assertEqual([('127.0.0.1', test.runner.SOCKS_PORT)], controller.get_listeners(Listener.SOCKS))\n self.assertEqual([], controller.get_listeners(Listener.TRANS))\n self.assertEqual([], controller.get_listeners(Listener.NATD))\n self.assertEqual([], controller.get_listeners(Listener.DNS))\n if test.runner.Torrc.PORT in runner.get_options():\n self.assertEqual([('127.0.0.1', test.runner.CONTROL_PORT)], controller.get_listeners(Listener.CONTROL))\n else:\n self.assertEqual([], controller.get_listeners(Listener.CONTROL))\n", "method_code": " def get_listeners(self, listener_type, default=UNDEFINED):\n \"\"\"\n get_listeners(listener_type, default = UNDEFINED)\n \n Provides the addresses and ports where tor is listening for connections of\n the given type. This is similar to\n :func:`~stem.control.Controller.get_ports` but includes listener addresses\n and non-local endpoints.\n \n .. versionadded:: 1.2.0\n \n .. versionchanged:: 1.5.0\n Recognize listeners with IPv6 addresses.\n \n :param stem.control.Listener listener_type: connection type being handled\n by the listeners we return\n :param object default: response if the query fails\n \n :returns: **list** of **(address, port)** tuples for the available\n listeners\n \n :raises: :class:`stem.ControllerError` if unable to determine the listeners\n and no default was provided\n \"\"\"\n listeners = self._get_cache(listener_type, 'listeners')\n if listeners is None:\n proxy_addrs = []\n query = 'net/listeners/%s' % listener_type.lower()\n try:\n for listener in self.get_info(query).split():\n if not (listener.startswith('\"') and listener.endswith('\"')):\n raise stem.ProtocolError(\"'GETINFO %s' responses are expected to be quoted: %s\" % (query, listener))\n elif ':' not in listener:\n raise stem.ProtocolError(\"'GETINFO %s' had a listener without a colon: %s\" % (query, listener))\n listener = listener[1:-1]\n addr, port = listener.rsplit(':', 1)\n if addr == 'unix':\n continue\n if addr.startswith('[') and addr.endswith(']'):\n addr = addr[1:-1]\n proxy_addrs.append((addr, port))\n except stem.InvalidArguments:\n port_option = {Listener.OR: 'ORPort', Listener.DIR: 'DirPort', Listener.SOCKS: 'SocksPort', Listener.TRANS: 'TransPort', Listener.NATD: 'NatdPort', Listener.DNS: 'DNSPort', Listener.CONTROL: 'ControlPort'}[listener_type]\n listener_option = {Listener.OR: 'ORListenAddress', Listener.DIR: 'DirListenAddress', Listener.SOCKS: 'SocksListenAddress', Listener.TRANS: 'TransListenAddress', Listener.NATD: 'NatdListenAddress', Listener.DNS: 'DNSListenAddress', Listener.CONTROL: 'ControlListenAddress'}[listener_type]\n port_value = self.get_conf(port_option).split()[0]\n for listener in self.get_conf(listener_option, multiple=True):\n if ':' in listener:\n addr, port = listener.rsplit(':', 1)\n if addr.startswith('[') and addr.endswith(']'):\n addr = addr[1:-1]\n proxy_addrs.append((addr, port))\n else:\n proxy_addrs.append((listener, port_value))\n for addr, port in proxy_addrs:\n if not stem.util.connection.is_valid_ipv4_address(addr) and (not stem.util.connection.is_valid_ipv6_address(addr)):\n raise stem.ProtocolError('Invalid address for a %s listener: %s' % (listener_type, addr))\n elif not stem.util.connection.is_valid_port(port):\n raise stem.ProtocolError('Invalid port for a %s listener: %s' % (listener_type, port))\n listeners = [(addr, int(port)) for addr, port in proxy_addrs]\n self._set_cache({listener_type: listeners}, 'listeners')\n return listeners\n ", "context": "class Controller(BaseController):\n @with_default()\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000950.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "get_socks_listeners", "tests": "import unittest\n\nclass Test_get_socks_listeners(unittest.TestCase):\n @test.require.controller\n def test_get_socks_listeners(self):\n \"\"\"\n Test Controller.get_socks_listeners against a running tor instance.\n \"\"\"\n with test.runner.get_runner().get_tor_controller() as controller:\n self.assertEqual([('127.0.0.1', 1112)], controller.get_socks_listeners())\n\n @patch('stem.control.Controller.get_info')\n @patch('stem.control.Controller.get_conf')\n def test_get_socks_listeners_old(self, get_conf_mock, get_info_mock):\n \"\"\"\n Exercises the get_socks_listeners() method as though talking to an old tor\n instance.\n \"\"\"\n get_info_mock.side_effect = InvalidArguments\n get_conf_mock.side_effect = lambda param, **kwargs: {'SocksPort': '9050', 'SocksListenAddress': ['127.0.0.1']}[param]\n self.assertEqual([('127.0.0.1', 9050)], self.controller.get_socks_listeners())\n self.controller.clear_cache()\n get_conf_mock.side_effect = lambda param, **kwargs: {'SocksPort': '9050', 'SocksListenAddress': ['127.0.0.1:1112']}[param]\n self.assertEqual([('127.0.0.1', 1112)], self.controller.get_socks_listeners())\n self.controller.clear_cache()\n get_conf_mock.side_effect = lambda param, **kwargs: {'SocksPort': '9050', 'SocksListenAddress': ['127.0.0.1:1112', '127.0.0.1:1114']}[param]\n self.assertEqual([('127.0.0.1', 1112), ('127.0.0.1', 1114)], self.controller.get_socks_listeners())\n self.controller.clear_cache()\n get_conf_mock.side_effect = lambda param, **kwargs: {'SocksPort': '0', 'SocksListenAddress': []}[param]\n self.assertEqual([], self.controller.get_socks_listeners())\n self.controller.clear_cache()\n get_conf_mock.side_effect = lambda param, **kwargs: {'SocksPort': 'blarg', 'SocksListenAddress': ['127.0.0.1']}[param]\n self.assertRaises(stem.ProtocolError, self.controller.get_socks_listeners)\n get_conf_mock.side_effect = lambda param, **kwargs: {'SocksPort': '0', 'SocksListenAddress': ['127.0.0.1:abc']}[param]\n self.assertRaises(stem.ProtocolError, self.controller.get_socks_listeners)\n get_conf_mock.side_effect = lambda param, **kwargs: {'SocksPort': '40', 'SocksListenAddress': ['500.0.0.1']}[param]\n self.assertRaises(stem.ProtocolError, self.controller.get_socks_listeners)\n\n @patch('stem.control.Controller.get_info')\n def test_get_socks_listeners_new(self, get_info_mock):\n \"\"\"\n Exercises the get_socks_listeners() method as if talking to a newer tor\n instance.\n \"\"\"\n get_info_mock.return_value = '\"127.0.0.1:1112\" \"127.0.0.1:1114\"'\n self.assertEqual([('127.0.0.1', 1112), ('127.0.0.1', 1114)], self.controller.get_socks_listeners())\n self.controller.clear_cache()\n get_info_mock.return_value = ''\n self.assertEqual([], self.controller.get_socks_listeners())\n invalid_responses = ('\"127.0.0.1\"', '\"1112\"', '\"5127.0.0.1:1112\"', '\"127.0.0.1:991112\"')\n for response in invalid_responses:\n self.controller.clear_cache()\n get_info_mock.return_value = response\n self.assertRaises(stem.ProtocolError, self.controller.get_socks_listeners)\n", "method_code": " def get_socks_listeners(self, default=UNDEFINED):\n \"\"\"\n Provides the SOCKS **(address, port)** tuples that tor has open.\n \n .. deprecated:: 1.2.0\n Use :func:`~stem.control.Controller.get_listeners` with\n **Listener.SOCKS** instead.\n \n :param object default: response if the query fails\n \n :returns: list of **(address, port)** tuples for the available SOCKS\n listeners\n \n :raises: :class:`stem.ControllerError` if unable to determine the listeners\n and no default was provided\n \"\"\"\n return self.get_listeners(Listener.SOCKS, default)\n ", "context": "class Controller(BaseController):\n def get_socks_listeners(self, default=UNDEFINED): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000951.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "enable_feature", "tests": "import unittest\n\nclass Test_enable_feature(unittest.TestCase):\n @test.require.controller\n @test.require.online\n @test.require.version(stem.version.Version('0.1.2.2-alpha'))\n def test_enable_feature(self):\n \"\"\"\n Test Controller.enable_feature with valid and invalid inputs.\n \"\"\"\n runner = test.runner.get_runner()\n with runner.get_tor_controller() as controller:\n self.assertTrue(controller.is_feature_enabled('VERBOSE_NAMES'))\n self.assertTrue('VERBOSE_NAMES' in controller._enabled_features)\n self.assertRaises(stem.InvalidArguments, controller.enable_feature, ['NOT', 'A', 'FEATURE'])\n try:\n controller.enable_feature(['NOT', 'A', 'FEATURE'])\n except stem.InvalidArguments as exc:\n self.assertEqual(['NOT'], exc.arguments)\n else:\n self.fail()\n", "method_code": " def enable_feature(self, features):\n \"\"\"\n Enables features that are disabled by default to maintain backward\n compatibility. Once enabled, a feature cannot be disabled and a new\n control connection must be opened to get a connection with the feature\n disabled. Feature names are case-insensitive.\n \n The following features are currently accepted:\n \n * EXTENDED_EVENTS - Requests the extended event syntax\n * VERBOSE_NAMES - Replaces ServerID with LongName in events and GETINFO results\n \n :param str,list features: a single feature or a list of features to be enabled\n \n :raises:\n * :class:`stem.ControllerError` if the call fails\n * :class:`stem.InvalidArguments` if features passed were invalid\n \"\"\"\n if stem.util._is_str(features):\n features = [features]\n response = self.msg('USEFEATURE %s' % ' '.join(features))\n stem.response.convert('SINGLELINE', response)\n if not response.is_ok():\n if response.code == '552':\n invalid_feature = []\n if response.message.startswith('Unrecognized feature \"'):\n invalid_feature = [response.message[22:response.message.find('\"', 22)]]\n raise stem.InvalidArguments(response.code, response.message, invalid_feature)\n raise stem.ProtocolError('USEFEATURE provided an invalid response code: %s' % response.code)\n self._enabled_features += [entry.upper() for entry in features]\n ", "context": "class Controller(BaseController):\n def enable_feature(self, features): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000952.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "signal", "tests": "import unittest\n\nclass Test_signal(unittest.TestCase):\n @test.require.controller\n def test_signal(self):\n \"\"\"\n Test controller.signal with valid and invalid signals.\n \"\"\"\n with test.runner.get_runner().get_tor_controller() as controller:\n controller.signal('CLEARDNSCACHE')\n self.assertRaises(stem.InvalidArguments, controller.signal, 'FOOBAR')\n", "method_code": " def signal(self, signal):\n \"\"\"\n Sends a signal to the Tor client.\n \n :param stem.Signal signal: type of signal to be sent\n \n :raises:\n * :class:`stem.ControllerError` if sending the signal failed\n * :class:`stem.InvalidArguments` if signal provided wasn't recognized\n \"\"\"\n response = self.msg('SIGNAL %s' % signal)\n stem.response.convert('SINGLELINE', response)\n if response.is_ok():\n if signal == stem.Signal.NEWNYM:\n self._last_newnym = time.time()\n else:\n if response.code == '552':\n raise stem.InvalidArguments(response.code, response.message, [signal])\n raise stem.ProtocolError('SIGNAL response contained unrecognized status code: %s' % response.code)\n ", "context": "class Controller(BaseController):\n def signal(self, signal): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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_000953.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "is_newnym_available", "tests": "import unittest\n\nclass Test_is_newnym_available(unittest.TestCase):\n @test.require.controller\n def test_newnym_availability(self):\n \"\"\"\n Test the is_newnym_available and get_newnym_wait methods.\n \"\"\"\n with test.runner.get_runner().get_tor_controller() as controller:\n self.assertEqual(True, controller.is_newnym_available())\n self.assertEqual(0.0, controller.get_newnym_wait())\n controller.signal(stem.Signal.NEWNYM)\n self.assertEqual(False, controller.is_newnym_available())\n self.assertTrue(controller.get_newnym_wait() > 9.0)\n", "method_code": " def is_newnym_available(self):\n \"\"\"\n Indicates if tor would currently accept a NEWNYM signal. This can only\n account for signals sent via this controller.\n \n .. versionadded:: 1.2.0\n \n :returns: **True** if tor would currently accept a NEWNYM signal, **False**\n otherwise\n \"\"\"\n if self.is_alive():\n return self.get_newnym_wait() == 0.0\n else:\n return False\n ", "context": "class Controller(BaseController):\n def is_newnym_available(self): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000954.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "extend_circuit", "tests": "import unittest\n\nclass Test_extend_circuit(unittest.TestCase):\n @test.require.controller\n @test.require.online\n @test.require.version(Requirement.EXTENDCIRCUIT_PATH_OPTIONAL)\n def test_extendcircuit(self):\n with test.runner.get_runner().get_tor_controller() as controller:\n circuit_id = controller.extend_circuit('0')\n self.assertNotEqual(None, controller.get_circuit(circuit_id, None))\n circuit_id = controller.new_circuit()\n self.assertNotEqual(None, controller.get_circuit(circuit_id, None))\n self.assertRaises(stem.InvalidRequest, controller.extend_circuit, 'foo')\n self.assertRaises(stem.InvalidRequest, controller.extend_circuit, '0', 'thisroutershouldntexistbecausestemexists!@##$%#')\n self.assertRaises(stem.InvalidRequest, controller.extend_circuit, '0', 'thisroutershouldntexistbecausestemexists!@##$%#', 'foo')\n", "method_code": " def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None):\n \"\"\"\n Either requests the creation of a new circuit or extends an existing one.\n \n When called with a circuit value of zero (the default) a new circuit is\n created, and when non-zero the circuit with that id is extended. If the\n path isn't provided, one is automatically selected.\n \n A python interpreter session used to create circuits could look like this...\n \n ::\n \n >>> controller.extend_circuit('0', ['718BCEA286B531757ACAFF93AE04910EA73DE617', '30BAB8EE7606CBD12F3CC269AE976E0153E7A58D', '2765D8A8C4BBA3F89585A9FFE0E8575615880BEB'])\n 19\n >>> controller.extend_circuit('0')\n 20\n >>> print(controller.get_info('circuit-status'))\n 20 EXTENDED $718BCEA286B531757ACAFF93AE04910EA73DE617=KsmoinOK,$649F2D0ACF418F7CFC6539AB2257EB2D5297BAFA=Eskimo BUILD_FLAGS=NEED_CAPACITY PURPOSE=GENERAL TIME_CREATED=2012-12-06T13:51:11.433755\n 19 BUILT $718BCEA286B531757ACAFF93AE04910EA73DE617=KsmoinOK,$30BAB8EE7606CBD12F3CC269AE976E0153E7A58D=Pascal1,$2765D8A8C4BBA3F89585A9FFE0E8575615880BEB=Anthracite PURPOSE=GENERAL TIME_CREATED=2012-12-06T13:50:56.969938\n \n .. versionchanged:: 1.7.0\n Added the timeout argument.\n \n :param str circuit_id: id of a circuit to be extended\n :param list,str path: one or more relays to make a circuit through, this is\n required if the circuit id is non-zero\n :param str purpose: 'general' or 'controller'\n :param bool await_build: blocks until the circuit is built if **True**\n :param float timeout: seconds to wait when **await_build** is **True**\n \n :returns: str of the circuit id of the created or extended circuit\n \n :raises:\n * :class:`stem.InvalidRequest` if one of the parameters were invalid\n * :class:`stem.CircuitExtensionFailed` if we were waiting for the circuit\n to build but it failed\n * :class:`stem.Timeout` if **timeout** was reached\n * :class:`stem.ControllerError` if the call fails\n \"\"\"\n circ_queue, circ_listener = (queue.Queue(), None)\n start_time = time.time()\n if await_build:\n \n def circ_listener(event):\n circ_queue.put(event)\n self.add_event_listener(circ_listener, EventType.CIRC)\n try:\n circuit_id = str(circuit_id)\n if path is None and circuit_id == '0':\n path_opt_version = stem.version.Requirement.EXTENDCIRCUIT_PATH_OPTIONAL\n if not self.get_version() >= path_opt_version:\n raise stem.InvalidRequest(512, 'EXTENDCIRCUIT requires the path prior to version %s' % path_opt_version)\n args = [circuit_id]\n if stem.util._is_str(path):\n path = [path]\n if path:\n args.append(','.join(path))\n if purpose:\n args.append('purpose=%s' % purpose)\n response = self.msg('EXTENDCIRCUIT %s' % ' '.join(args))\n stem.response.convert('SINGLELINE', response)\n if response.code in ('512', '552'):\n raise stem.InvalidRequest(response.code, response.message)\n elif not response.is_ok():\n raise stem.ProtocolError('EXTENDCIRCUIT returned unexpected response code: %s' % response.code)\n if not response.message.startswith('EXTENDED '):\n raise stem.ProtocolError('EXTENDCIRCUIT response invalid:\\n%s', response)\n new_circuit = response.message.split(' ', 1)[1]\n if await_build:\n while True:\n circ = _get_with_timeout(circ_queue, timeout, start_time)\n if circ.id == new_circuit:\n if circ.status == CircStatus.BUILT:\n break\n elif circ.status == CircStatus.FAILED:\n raise stem.CircuitExtensionFailed('Circuit failed to be created: %s' % circ.reason, circ)\n elif circ.status == CircStatus.CLOSED:\n raise stem.CircuitExtensionFailed('Circuit was closed prior to build', circ)\n return new_circuit\n finally:\n if circ_listener:\n self.remove_event_listener(circ_listener)\n ", "context": "class Controller(BaseController):\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000955.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "repurpose_circuit", "tests": "import unittest\n\nclass Test_repurpose_circuit(unittest.TestCase):\n @test.require.controller\n @test.require.online\n @test.require.version(Requirement.EXTENDCIRCUIT_PATH_OPTIONAL)\n def test_repurpose_circuit(self):\n \"\"\"\n Tests Controller.repurpose_circuit with valid and invalid input.\n \"\"\"\n runner = test.runner.get_runner()\n with runner.get_tor_controller() as controller:\n circ_id = controller.new_circuit()\n controller.repurpose_circuit(circ_id, 'CONTROLLER')\n circuit = controller.get_circuit(circ_id)\n self.assertTrue(circuit.purpose == 'CONTROLLER')\n controller.repurpose_circuit(circ_id, 'GENERAL')\n circuit = controller.get_circuit(circ_id)\n self.assertTrue(circuit.purpose == 'GENERAL')\n self.assertRaises(stem.InvalidRequest, controller.repurpose_circuit, 'f934h9f3h4', 'fooo')\n self.assertRaises(stem.InvalidRequest, controller.repurpose_circuit, '4', 'fooo')\n", "method_code": " def repurpose_circuit(self, circuit_id, purpose):\n \"\"\"\n Changes a circuit's purpose. Currently, two purposes are recognized...\n * general\n * controller\n \n :param str circuit_id: id of the circuit whose purpose is to be changed\n :param str purpose: purpose (either 'general' or 'controller')\n \n :raises: :class:`stem.InvalidArguments` if the circuit doesn't exist or if the purpose was invalid\n \"\"\"\n response = self.msg('SETCIRCUITPURPOSE %s purpose=%s' % (circuit_id, purpose))\n stem.response.convert('SINGLELINE', response)\n if not response.is_ok():\n if response.code == '552':\n raise stem.InvalidRequest(response.code, response.message)\n else:\n raise stem.ProtocolError('SETCIRCUITPURPOSE returned unexpected response code: %s' % response.code)\n ", "context": "class Controller(BaseController):\n def repurpose_circuit(self, circuit_id, purpose): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000956.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "close_circuit", "tests": "import unittest\n\nclass Test_close_circuit(unittest.TestCase):\n @test.require.controller\n @test.require.online\n @test.require.version(Requirement.EXTENDCIRCUIT_PATH_OPTIONAL)\n def test_close_circuit(self):\n \"\"\"\n Tests Controller.close_circuit with valid and invalid input.\n \"\"\"\n runner = test.runner.get_runner()\n with runner.get_tor_controller() as controller:\n circuit_id = controller.new_circuit()\n controller.close_circuit(circuit_id)\n circuit_output = controller.get_info('circuit-status')\n circ = [x.split()[0] for x in circuit_output.splitlines()]\n self.assertFalse(circuit_id in circ)\n circuit_id = controller.new_circuit()\n controller.close_circuit(circuit_id, 'IfUnused')\n circuit_output = controller.get_info('circuit-status')\n circ = [x.split()[0] for x in circuit_output.splitlines()]\n self.assertFalse(circuit_id in circ)\n circuit_id = controller.new_circuit()\n self.assertRaises(stem.InvalidArguments, controller.close_circuit, circuit_id + '1024')\n self.assertRaises(stem.InvalidRequest, controller.close_circuit, '')\n", "method_code": " def close_circuit(self, circuit_id, flag=''):\n \"\"\"\n Closes the specified circuit.\n \n :param str circuit_id: id of the circuit to be closed\n :param str flag: optional value to modify closing, the only flag available\n is 'IfUnused' which will not close the circuit unless it is unused\n \n :raises: :class:`stem.InvalidArguments` if the circuit is unknown\n :raises: :class:`stem.InvalidRequest` if not enough information is provided\n \"\"\"\n response = self.msg('CLOSECIRCUIT %s %s' % (circuit_id, flag))\n stem.response.convert('SINGLELINE', response)\n if not response.is_ok():\n if response.code in ('512', '552'):\n if response.message.startswith('Unknown circuit '):\n raise stem.InvalidArguments(response.code, response.message, [circuit_id])\n raise stem.InvalidRequest(response.code, response.message)\n else:\n raise stem.ProtocolError('CLOSECIRCUIT returned unexpected response code: %s' % response.code)\n ", "context": "class Controller(BaseController):\n def close_circuit(self, circuit_id, flag=''): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000957.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "get_streams", "tests": "import unittest\n\nclass Test_get_streams(unittest.TestCase):\n @test.require.controller\n @test.require.online\n def test_get_streams(self):\n \"\"\"\n Tests Controller.get_streams().\n \"\"\"\n host = socket.gethostbyname('www.torproject.org')\n port = 443\n runner = test.runner.get_runner()\n with runner.get_tor_controller() as controller:\n socks_listener = controller.get_socks_listeners()[0]\n with test.network.Socks(socks_listener) as s:\n s.settimeout(30)\n s.connect((host, port))\n streams = controller.get_streams()\n self.assertTrue('%s:%s' % (host, port) in [stream.target for stream in streams])\n\n def test_get_streams(self):\n \"\"\"\n Exercises the get_streams() method.\n \"\"\"\n valid_streams = (('1', 'NEW', '4', '10.10.10.1:80'), ('2', 'SUCCEEDED', '4', '10.10.10.1:80'), ('3', 'SUCCEEDED', '4', '10.10.10.1:80'))\n response = ''.join(['%s\\r\\n' % ' '.join(entry) for entry in valid_streams])\n with patch('stem.control.Controller.get_info', Mock(return_value=response)):\n streams = self.controller.get_streams()\n self.assertEqual(len(valid_streams), len(streams))\n for index, stream in enumerate(streams):\n self.assertEqual(valid_streams[index][0], stream.id)\n self.assertEqual(valid_streams[index][1], stream.status)\n self.assertEqual(valid_streams[index][2], stream.circ_id)\n self.assertEqual(valid_streams[index][3], stream.target)\n", "method_code": " def get_streams(self, default=UNDEFINED):\n \"\"\"\n get_streams(default = UNDEFINED)\n \n Provides the list of streams tor is currently handling.\n \n :param object default: response if the query fails\n \n :returns: list of :class:`stem.response.events.StreamEvent` objects\n \n :raises: :class:`stem.ControllerError` if the call fails and no default was\n provided\n \"\"\"\n streams = []\n response = self.get_info('stream-status')\n for stream in response.splitlines():\n message = stem.socket.recv_message(io.BytesIO(stem.util.str_tools._to_bytes('650 STREAM %s\\r\\n' % stream)))\n stem.response.convert('EVENT', message, arrived_at=0)\n streams.append(message)\n return streams\n ", "context": "class Controller(BaseController):\n @with_default()\n def get_streams(self, default=UNDEFINED): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000958.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "close_stream", "tests": "import unittest\n\nclass Test_close_stream(unittest.TestCase):\n @test.require.controller\n @test.require.online\n def test_close_stream(self):\n \"\"\"\n Tests Controller.close_stream with valid and invalid input.\n \"\"\"\n runner = test.runner.get_runner()\n with runner.get_tor_controller() as controller:\n socks_listener = controller.get_socks_listeners()[0]\n with test.network.Socks(socks_listener) as s:\n s.settimeout(30)\n s.connect(('www.torproject.org', 443))\n built_stream = controller.get_streams()[0]\n self.assertEqual([built_stream.id], [stream.id for stream in controller.get_streams()])\n controller.close_stream(built_stream.id)\n self.assertEqual([], controller.get_streams())\n self.assertRaises(stem.InvalidArguments, controller.close_stream, 'blarg')\n", "method_code": " def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''):\n \"\"\"\n Closes the specified stream.\n \n :param str stream_id: id of the stream to be closed\n :param stem.RelayEndReason reason: reason the stream is closing\n :param str flag: not currently used\n \n :raises:\n * :class:`stem.InvalidArguments` if the stream or reason are not recognized\n * :class:`stem.InvalidRequest` if the stream and/or reason are missing\n \"\"\"\n response = self.msg('CLOSESTREAM %s %s %s' % (stream_id, stem.RelayEndReason.index_of(reason) + 1, flag))\n stem.response.convert('SINGLELINE', response)\n if not response.is_ok():\n if response.code in ('512', '552'):\n if response.message.startswith('Unknown stream '):\n raise stem.InvalidArguments(response.code, response.message, [stream_id])\n elif response.message.startswith('Unrecognized reason '):\n raise stem.InvalidArguments(response.code, response.message, [reason])\n raise stem.InvalidRequest(response.code, response.message)\n else:\n raise stem.ProtocolError('CLOSESTREAM returned unexpected response code: %s' % response.code)\n ", "context": "class Controller(BaseController):\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000959.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "map_address", "tests": "import unittest\n\nclass Test_map_address(unittest.TestCase):\n @test.require.controller\n @test.require.online\n def test_mapaddress(self):\n self.skipTest('(https://trac.torproject.org/projects/tor/ticket/25611)')\n runner = test.runner.get_runner()\n with runner.get_tor_controller() as controller:\n controller.map_address({'1.2.1.2': 'ifconfig.me'})\n s = None\n response = None\n for _ in range(10):\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.settimeout(30)\n s.connect(('127.0.0.1', int(controller.get_conf('SocksPort'))))\n test.network.negotiate_socks(s, '1.2.1.2', 80)\n s.sendall(stem.util.str_tools._to_bytes(test.network.IP_REQUEST))\n response = s.recv(1000)\n if response:\n break\n except (stem.ProtocolError, socket.timeout):\n continue\n finally:\n if s:\n s.close()\n self.assertTrue(response)\n ip_addr = response[response.find(b'\\r\\n\\r\\n'):].strip()\n self.assertTrue(stem.util.connection.is_valid_ipv4_address(stem.util.str_tools._to_unicode(ip_addr)), \"'%s' isn't an address\" % ip_addr)\n", "method_code": " def map_address(self, mapping):\n \"\"\"\n Map addresses to replacement addresses. Tor replaces subseqent connections\n to the original addresses with the replacement addresses.\n \n If the original address is a null address, i.e., one of '0.0.0.0', '::0', or\n '.' Tor picks an original address itself and returns it in the reply. If the\n original address is already mapped to a different address the mapping is\n removed.\n \n :param dict mapping: mapping of original addresses to replacement addresses\n \n :raises:\n * :class:`stem.InvalidRequest` if the addresses are malformed\n * :class:`stem.OperationFailed` if Tor couldn't fulfill the request\n \n :returns: **dict** with 'original -> replacement' address mappings\n \"\"\"\n mapaddress_arg = ' '.join(['%s=%s' % (k, v) for k, v in list(mapping.items())])\n response = self.msg('MAPADDRESS %s' % mapaddress_arg)\n stem.response.convert('MAPADDRESS', response)\n return response.entries\n ", "context": "class Controller(BaseController):\n def map_address(self, mapping): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000960.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "get_microdescriptor", "tests": "import unittest\n\nclass Test_get_microdescriptor(unittest.TestCase):\n @test.require.controller\n @test.require.online\n @test.require.version(Requirement.MICRODESCRIPTOR_IS_DEFAULT)\n def test_get_microdescriptor(self):\n \"\"\"\n Basic checks for get_microdescriptor().\n \"\"\"\n with test.runner.get_runner().get_tor_controller() as controller:\n self.assertRaises(ValueError, controller.get_microdescriptor, '')\n self.assertRaises(ValueError, controller.get_microdescriptor, 5)\n self.assertRaises(ValueError, controller.get_microdescriptor, 'z' * 30)\n self.assertRaises(stem.ControllerError, controller.get_microdescriptor, 'blargg')\n self.assertRaises(stem.ControllerError, controller.get_microdescriptor, '5' * 40)\n test_relay = self._get_router_status_entry(controller)\n md_by_fingerprint = controller.get_microdescriptor(test_relay.fingerprint)\n md_by_nickname = controller.get_microdescriptor(test_relay.nickname)\n self.assertEqual(md_by_fingerprint, md_by_nickname)\n", "method_code": " def get_microdescriptor(self, relay=None, default=UNDEFINED):\n \"\"\"\n get_microdescriptor(relay = None, default = UNDEFINED)\n \n Provides the microdescriptor for the relay with the given fingerprint or\n nickname. If the relay identifier could be either a fingerprint *or*\n nickname then it's queried as a fingerprint.\n \n If no **relay** is provided then this defaults to ourselves. Remember that\n this requires that we've retrieved our own descriptor from remote\n authorities so this both won't be available for newly started relays and\n may be up to around an hour out of date.\n \n .. versionchanged:: 1.3.0\n Changed so we'd fetch our own descriptor if no 'relay' is provided.\n \n :param str relay: fingerprint or nickname of the relay to be queried\n :param object default: response if the query fails\n \n :returns: :class:`~stem.descriptor.microdescriptor.Microdescriptor` for the given relay\n \n :raises:\n * :class:`stem.DescriptorUnavailable` if unable to provide a descriptor\n for the given relay\n * :class:`stem.ControllerError` if unable to query the descriptor\n * **ValueError** if **relay** doesn't conform with the pattern for being\n a fingerprint or nickname\n \n An exception is only raised if we weren't provided a default response.\n \"\"\"\n if relay is None:\n try:\n relay = self.get_info('fingerprint')\n except stem.ControllerError as exc:\n raise stem.ControllerError('Unable to determine our own fingerprint: %s' % exc)\n if stem.util.tor_tools.is_valid_fingerprint(relay):\n query = 'md/id/%s' % relay\n elif stem.util.tor_tools.is_valid_nickname(relay):\n query = 'md/name/%s' % relay\n else:\n raise ValueError(\"'%s' isn't a valid fingerprint or nickname\" % relay)\n try:\n desc_content = self.get_info(query, get_bytes=True)\n except stem.InvalidArguments as exc:\n if str(exc).startswith('GETINFO request contained unrecognized keywords:'):\n raise stem.DescriptorUnavailable(\"Tor was unable to provide the descriptor for '%s'\" % relay)\n else:\n raise\n if not desc_content:\n raise stem.DescriptorUnavailable('Descriptor information is unavailable, tor might still be downloading it')\n return stem.descriptor.microdescriptor.Microdescriptor(desc_content)\n ", "context": "class Controller(BaseController):\n @with_default()\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000961.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "get_microdescriptors", "tests": "import unittest\n\nclass Test_get_microdescriptors(unittest.TestCase):\n @test.require.controller\n @test.require.online\n def test_get_microdescriptors(self):\n \"\"\"\n Fetches a few descriptors via the get_microdescriptors() method.\n \"\"\"\n runner = test.runner.get_runner()\n if not os.path.exists(runner.get_test_dir('cached-microdescs')):\n self.skipTest('(no cached microdescriptors)')\n return\n with runner.get_tor_controller() as controller:\n count = 0\n for desc in controller.get_microdescriptors():\n self.assertTrue(desc.onion_key is not None)\n count += 1\n if count > 10:\n break\n", "method_code": " def get_microdescriptors(self, default=UNDEFINED):\n \"\"\"\n get_microdescriptors(default = UNDEFINED)\n \n Provides an iterator for all of the microdescriptors that tor currently\n knows about.\n \n Prior to Tor 0.3.5.1 this information was not available via the control\n protocol. When connected to prior versions we read the microdescriptors\n directly from disk instead, which will not work remotely or if our process\n lacks read permissions.\n \n :param list default: items to provide if the query fails\n \n :returns: iterates over\n :class:`~stem.descriptor.microdescriptor.Microdescriptor` for relays in\n the tor network\n \n :raises: :class:`stem.ControllerError` if unable to query tor and no\n default was provided\n \"\"\"\n if self.get_version() >= stem.version.Requirement.GETINFO_MICRODESCRIPTORS:\n desc_content = self.get_info('md/all', get_bytes=True)\n if not desc_content:\n raise stem.DescriptorUnavailable('Descriptor information is unavailable, tor might still be downloading it')\n for desc in stem.descriptor.microdescriptor._parse_file(io.BytesIO(desc_content)):\n yield desc\n else:\n data_directory = self.get_conf('DataDirectory', None)\n if data_directory is None:\n raise stem.OperationFailed(message=\"Unable to determine tor's data directory\")\n if not os.path.exists(data_directory):\n raise stem.OperationFailed(message=\"Data directory reported by tor doesn't exist (%s)\" % data_directory)\n microdescriptor_file = None\n for filename in ('cached-microdescs', 'cached-microdescs.new'):\n cached_descriptors = os.path.join(data_directory, filename)\n if os.path.exists(cached_descriptors):\n microdescriptor_file = cached_descriptors\n break\n if microdescriptor_file is None:\n raise stem.OperationFailed(message=\"Data directory doesn't contain cached microdescriptors (%s)\" % data_directory)\n for desc in stem.descriptor.parse_file(microdescriptor_file):\n if not isinstance(desc, stem.descriptor.microdescriptor.Microdescriptor):\n raise stem.OperationFailed(message='BUG: Descriptor reader provided non-microdescriptor content (%s)' % type(desc))\n yield desc\n ", "context": "class Controller(BaseController):\n @with_default(yields=True)\n def get_microdescriptors(self, default=UNDEFINED): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000962.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "get_server_descriptor", "tests": "import unittest\n\nclass Test_get_server_descriptor(unittest.TestCase):\n @test.require.controller\n def test_get_server_descriptor(self):\n \"\"\"\n Basic checks for get_server_descriptor().\n \"\"\"\n runner = test.runner.get_runner()\n if test.tor_version() >= Requirement.MICRODESCRIPTOR_IS_DEFAULT:\n self.skipTest('(requires server descriptors)')\n return\n with runner.get_tor_controller() as controller:\n self.assertRaises(ValueError, controller.get_server_descriptor, None)\n self.assertRaises(ValueError, controller.get_server_descriptor, '')\n self.assertRaises(ValueError, controller.get_server_descriptor, 5)\n self.assertRaises(ValueError, controller.get_server_descriptor, 'z' * 30)\n self.assertRaises(stem.ControllerError, controller.get_server_descriptor, 'blargg')\n self.assertRaises(stem.ControllerError, controller.get_server_descriptor, '5' * 40)\n test_relay = self._get_router_status_entry(controller)\n desc_by_fingerprint = controller.get_server_descriptor(test_relay.fingerprint)\n desc_by_nickname = controller.get_server_descriptor(test_relay.nickname)\n self.assertEqual(desc_by_fingerprint, desc_by_nickname)\n", "method_code": " def get_server_descriptor(self, relay=None, default=UNDEFINED):\n \"\"\"\n get_server_descriptor(relay = None, default = UNDEFINED)\n \n Provides the server descriptor for the relay with the given fingerprint or\n nickname. If the relay identifier could be either a fingerprint *or*\n nickname then it's queried as a fingerprint.\n \n If no **relay** is provided then this defaults to ourselves. Remember that\n this requires that we've retrieved our own descriptor from remote\n authorities so this both won't be available for newly started relays and\n may be up to around an hour out of date.\n \n **As of Tor version 0.2.3.25 relays no longer get server descriptors by\n default.** It's advised that you use microdescriptors instead, but if you\n really need server descriptors then you can get them by setting\n 'UseMicrodescriptors 0'.\n \n .. versionchanged:: 1.3.0\n Changed so we'd fetch our own descriptor if no 'relay' is provided.\n \n :param str relay: fingerprint or nickname of the relay to be queried\n :param object default: response if the query fails\n \n :returns: :class:`~stem.descriptor.server_descriptor.RelayDescriptor` for the given relay\n \n :raises:\n * :class:`stem.DescriptorUnavailable` if unable to provide a descriptor\n for the given relay\n * :class:`stem.ControllerError` if unable to query the descriptor\n * **ValueError** if **relay** doesn't conform with the pattern for being\n a fingerprint or nickname\n \n An exception is only raised if we weren't provided a default response.\n \"\"\"\n try:\n if relay is None:\n try:\n relay = self.get_info('fingerprint')\n except stem.ControllerError as exc:\n raise stem.ControllerError('Unable to determine our own fingerprint: %s' % exc)\n if stem.util.tor_tools.is_valid_fingerprint(relay):\n query = 'desc/id/%s' % relay\n elif stem.util.tor_tools.is_valid_nickname(relay):\n query = 'desc/name/%s' % relay\n else:\n raise ValueError(\"'%s' isn't a valid fingerprint or nickname\" % relay)\n try:\n desc_content = self.get_info(query, get_bytes=True)\n except stem.InvalidArguments as exc:\n if str(exc).startswith('GETINFO request contained unrecognized keywords:'):\n raise stem.DescriptorUnavailable(\"Tor was unable to provide the descriptor for '%s'\" % relay)\n else:\n raise\n if not desc_content:\n raise stem.DescriptorUnavailable('Descriptor information is unavailable, tor might still be downloading it')\n return stem.descriptor.server_descriptor.RelayDescriptor(desc_content)\n except:\n if not self._is_server_descriptors_available():\n raise ValueError(SERVER_DESCRIPTORS_UNSUPPORTED)\n raise\n ", "context": "class Controller(BaseController):\n @with_default()\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000963.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "get_server_descriptors", "tests": "import unittest\n\nclass Test_get_server_descriptors(unittest.TestCase):\n @test.require.controller\n @test.require.online\n def test_get_server_descriptors(self):\n \"\"\"\n Fetches a few descriptors via the get_server_descriptors() method.\n \"\"\"\n runner = test.runner.get_runner()\n if test.tor_version() >= Requirement.MICRODESCRIPTOR_IS_DEFAULT:\n self.skipTest('(requires server descriptors)')\n return\n with runner.get_tor_controller() as controller:\n count = 0\n for desc in controller.get_server_descriptors():\n self.assertTrue(desc.fingerprint is not None)\n self.assertTrue(desc.nickname is not None)\n count += 1\n if count > 10:\n break\n", "method_code": " def get_server_descriptors(self, default=UNDEFINED):\n \"\"\"\n get_server_descriptors(default = UNDEFINED)\n \n Provides an iterator for all of the server descriptors that tor currently\n knows about.\n \n **As of Tor version 0.2.3.25 relays no longer get server descriptors by\n default.** It's advised that you use microdescriptors instead, but if you\n really need server descriptors then you can get them by setting\n 'UseMicrodescriptors 0'.\n \n :param list default: items to provide if the query fails\n \n :returns: iterates over\n :class:`~stem.descriptor.server_descriptor.RelayDescriptor` for relays in\n the tor network\n \n :raises: :class:`stem.ControllerError` if unable to query tor and no\n default was provided\n \"\"\"\n desc_content = self.get_info('desc/all-recent', get_bytes=True)\n if not desc_content:\n if not self._is_server_descriptors_available():\n raise stem.ControllerError(SERVER_DESCRIPTORS_UNSUPPORTED)\n else:\n raise stem.DescriptorUnavailable('Descriptor information is unavailable, tor might still be downloading it')\n for desc in stem.descriptor.server_descriptor._parse_file(io.BytesIO(desc_content)):\n yield desc\n ", "context": "class Controller(BaseController):\n @with_default(yields=True)\n def get_server_descriptors(self, default=UNDEFINED): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000964.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "get_network_status", "tests": "import unittest\n\nclass Test_get_network_status(unittest.TestCase):\n @test.require.controller\n @test.require.online\n def test_get_network_status(self):\n \"\"\"\n Basic checks for get_network_status().\n \"\"\"\n with test.runner.get_runner().get_tor_controller() as controller:\n self.assertRaises(ValueError, controller.get_network_status, '')\n self.assertRaises(ValueError, controller.get_network_status, 5)\n self.assertRaises(ValueError, controller.get_network_status, 'z' * 30)\n self.assertRaises(stem.ControllerError, controller.get_network_status, 'blargg')\n self.assertRaises(stem.ControllerError, controller.get_network_status, '5' * 40)\n test_relay = self._get_router_status_entry(controller)\n desc_by_fingerprint = controller.get_network_status(test_relay.fingerprint)\n desc_by_nickname = controller.get_network_status(test_relay.nickname)\n self.assertEqual(desc_by_fingerprint, desc_by_nickname)\n\n @patch('stem.control.Controller.get_info')\n def test_get_network_status_for_ourselves(self, get_info_mock):\n \"\"\"\n Exercises the get_network_status() method for getting our own relay.\n \"\"\"\n get_info_mock.side_effect = ControllerError('nope, too bad')\n exc_msg = 'Unable to determine our own fingerprint: nope, too bad'\n self.assertRaisesWith(ControllerError, exc_msg, self.controller.get_network_status)\n self.assertEqual('boom', self.controller.get_network_status(default='boom'))\n desc = NS_DESC % ('moria1', '/96bKo4soysolMgKn5Hex2nyFSY')\n get_info_mock.side_effect = lambda param, **kwargs: {'fingerprint': '9695DFC35FFEB861329B9F1AB04C46397020CE31', 'ns/id/9695DFC35FFEB861329B9F1AB04C46397020CE31': desc}[param]\n self.assertEqual(stem.descriptor.router_status_entry.RouterStatusEntryV3(desc), self.controller.get_network_status())\n\n @patch('stem.control.Controller.get_info')\n def test_get_network_status(self, get_info_mock):\n \"\"\"\n Exercises the get_network_status() method.\n \"\"\"\n nickname = 'Beaver'\n fingerprint = '/96bKo4soysolMgKn5Hex2nyFSY'\n desc = NS_DESC % (nickname, fingerprint)\n router = stem.descriptor.router_status_entry.RouterStatusEntryV3(desc)\n get_info_mock.return_value = desc\n self.assertEqual(router, self.controller.get_network_status(nickname))\n hex_fingerprint = stem.descriptor.router_status_entry._base64_to_hex(fingerprint, False)\n self.assertEqual(router, self.controller.get_network_status(hex_fingerprint))\n hex_fingerprint = hex_fingerprint[2:]\n self.assertRaises(ValueError, self.controller.get_network_status, hex_fingerprint)\n get_info_mock.side_effect = InvalidArguments\n self.assertEqual('default returned', self.controller.get_network_status(nickname, default='default returned'))\n self.assertRaises(InvalidArguments, self.controller.get_network_status, nickname)\n", "method_code": " def get_network_status(self, relay=None, default=UNDEFINED):\n \"\"\"\n get_network_status(relay = None, default = UNDEFINED)\n \n Provides the router status entry for the relay with the given fingerprint\n or nickname. If the relay identifier could be either a fingerprint *or*\n nickname then it's queried as a fingerprint.\n \n If no **relay** is provided then this defaults to ourselves. Remember that\n this requires that we've retrieved our own descriptor from remote\n authorities so this both won't be available for newly started relays and\n may be up to around an hour out of date.\n \n .. versionchanged:: 1.3.0\n Changed so we'd fetch our own descriptor if no 'relay' is provided.\n \n :param str relay: fingerprint or nickname of the relay to be queried\n :param object default: response if the query fails\n \n :returns: :class:`~stem.descriptor.router_status_entry.RouterStatusEntryV3`\n for the given relay\n \n :raises:\n * :class:`stem.DescriptorUnavailable` if unable to provide a descriptor\n for the given relay\n * :class:`stem.ControllerError` if unable to query the descriptor\n * **ValueError** if **relay** doesn't conform with the pattern for being\n a fingerprint or nickname\n \n An exception is only raised if we weren't provided a default response.\n \"\"\"\n if relay is None:\n try:\n relay = self.get_info('fingerprint')\n except stem.ControllerError as exc:\n raise stem.ControllerError('Unable to determine our own fingerprint: %s' % exc)\n if stem.util.tor_tools.is_valid_fingerprint(relay):\n query = 'ns/id/%s' % relay\n elif stem.util.tor_tools.is_valid_nickname(relay):\n query = 'ns/name/%s' % relay\n else:\n raise ValueError(\"'%s' isn't a valid fingerprint or nickname\" % relay)\n try:\n desc_content = self.get_info(query, get_bytes=True)\n except stem.InvalidArguments as exc:\n if str(exc).startswith('GETINFO request contained unrecognized keywords:'):\n raise stem.DescriptorUnavailable(\"Tor was unable to provide the descriptor for '%s'\" % relay)\n else:\n raise\n if not desc_content:\n raise stem.DescriptorUnavailable('Descriptor information is unavailable, tor might still be downloading it')\n return stem.descriptor.router_status_entry.RouterStatusEntryV3(desc_content)\n ", "context": "class Controller(BaseController):\n @with_default()\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000965.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "get_network_statuses", "tests": "import unittest\n\nclass Test_get_network_statuses(unittest.TestCase):\n @test.require.controller\n @test.require.online\n def test_get_network_statuses(self):\n \"\"\"\n Fetches a few descriptors via the get_network_statuses() method.\n \"\"\"\n runner = test.runner.get_runner()\n with runner.get_tor_controller() as controller:\n count = 0\n for desc in controller.get_network_statuses():\n self.assertTrue(desc.fingerprint is not None)\n self.assertTrue(desc.nickname is not None)\n for line in desc.get_unrecognized_lines():\n test.register_new_capability('Consensus Line', line)\n count += 1\n if count > 10:\n break\n", "method_code": " def get_network_statuses(self, default=UNDEFINED):\n \"\"\"\n get_network_statuses(default = UNDEFINED)\n \n Provides an iterator for all of the router status entries that tor\n currently knows about.\n \n :param list default: items to provide if the query fails\n \n :returns: iterates over\n :class:`~stem.descriptor.router_status_entry.RouterStatusEntryV3` for\n relays in the tor network\n \n :raises: :class:`stem.ControllerError` if unable to query tor and no\n default was provided\n \"\"\"\n desc_content = self.get_info('ns/all', get_bytes=True)\n if not desc_content:\n raise stem.DescriptorUnavailable('Descriptor information is unavailable, tor might still be downloading it')\n desc_iterator = stem.descriptor.router_status_entry._parse_file(io.BytesIO(desc_content), False, entry_class=stem.descriptor.router_status_entry.RouterStatusEntryV3)\n for desc in desc_iterator:\n yield desc\n ", "context": "class Controller(BaseController):\n @with_default(yields=True)\n def get_network_statuses(self, default=UNDEFINED): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 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": "stem/control.py", "focal_class": null, "focal_method": "get_hidden_service_descriptor", "tests": "import unittest\n\nclass Test_get_hidden_service_descriptor(unittest.TestCase):\n @test.require.controller\n @test.require.online\n @test.require.version(Requirement.HSFETCH)\n def test_get_hidden_service_descriptor(self):\n \"\"\"\n Fetches a few descriptors via the get_hidden_service_descriptor() method.\n \"\"\"\n runner = test.runner.get_runner()\n with runner.get_tor_controller() as controller:\n desc = controller.get_hidden_service_descriptor('3g2upl4pq6kufc4m.onion')\n self.assertTrue('MIGJAoGBAJ' in desc.permanent_key)\n exc_msg = 'No running hidden service at m4cfuk6qp4lpu2g3.onion'\n self.assertRaisesWith(stem.DescriptorUnavailable, exc_msg, controller.get_hidden_service_descriptor, 'm4cfuk6qp4lpu2g3')\n self.assertEqual('pop goes the weasel', controller.get_hidden_service_descriptor('m4cfuk6qp4lpu2g5', 'pop goes the weasel'))\n self.assertEqual(None, controller.get_hidden_service_descriptor('m4cfuk6qp4lpu2g5', await_result=False))\n", "method_code": " def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None):\n \"\"\"\n get_hidden_service_descriptor(address, default = UNDEFINED, servers = None, await_result = True)\n \n Provides the descriptor for a hidden service. The **address** is the\n '.onion' address of the hidden service (for instance 3g2upl4pq6kufc4m.onion\n for DuckDuckGo).\n \n If **await_result** is **True** then this blocks until we either receive\n the descriptor or the request fails. If **False** this returns right away.\n \n **This method only supports v2 hidden services, not v3.** (:trac:`25417`)\n \n .. versionadded:: 1.4.0\n \n .. versionchanged:: 1.7.0\n Added the timeout argument.\n \n :param str address: address of the hidden service descriptor, the '.onion' suffix is optional\n :param object default: response if the query fails\n :param list servers: requrest the descriptor from these specific servers\n :param float timeout: seconds to wait when **await_result** is **True**\n \n :returns: :class:`~stem.descriptor.hidden_service_descriptor.HiddenServiceDescriptor`\n for the given service if **await_result** is **True**, or **None** otherwise\n \n :raises:\n * :class:`stem.DescriptorUnavailable` if **await_result** is **True** and\n unable to provide a descriptor for the given service\n * :class:`stem.Timeout` if **timeout** was reached\n * :class:`stem.ControllerError` if unable to query the descriptor\n * **ValueError** if **address** doesn't conform with the pattern of a\n hidden service address\n \n An exception is only raised if we weren't provided a default response.\n \"\"\"\n if address.endswith('.onion'):\n address = address[:-6]\n if not stem.util.tor_tools.is_valid_hidden_service_address(address):\n raise ValueError(\"'%s.onion' isn't a valid hidden service address\" % address)\n if self.get_version() < stem.version.Requirement.HSFETCH:\n raise stem.UnsatisfiableRequest(message='HSFETCH was added in tor version %s' % stem.version.Requirement.HSFETCH)\n hs_desc_queue, hs_desc_listener = (queue.Queue(), None)\n hs_desc_content_queue, hs_desc_content_listener = (queue.Queue(), None)\n start_time = time.time()\n if await_result:\n \n def hs_desc_listener(event):\n hs_desc_queue.put(event)\n \n def hs_desc_content_listener(event):\n hs_desc_content_queue.put(event)\n self.add_event_listener(hs_desc_listener, EventType.HS_DESC)\n self.add_event_listener(hs_desc_content_listener, EventType.HS_DESC_CONTENT)\n try:\n request = 'HSFETCH %s' % address\n if servers:\n request += ' ' + ' '.join(['SERVER=%s' % s for s in servers])\n response = self.msg(request)\n stem.response.convert('SINGLELINE', response)\n if not response.is_ok():\n raise stem.ProtocolError('HSFETCH returned unexpected response code: %s' % response.code)\n if not await_result:\n return None\n else:\n while True:\n event = _get_with_timeout(hs_desc_content_queue, timeout, start_time)\n if event.address == address:\n if event.descriptor:\n return event.descriptor\n else:\n while True:\n event = _get_with_timeout(hs_desc_queue, timeout, start_time)\n if event.address == address and event.action == stem.HSDescAction.FAILED:\n if event.reason == stem.HSDescReason.NOT_FOUND:\n raise stem.DescriptorUnavailable('No running hidden service at %s.onion' % address)\n else:\n raise stem.DescriptorUnavailable('Unable to retrieve the descriptor for %s.onion (retrieved from %s): %s' % (address, event.directory_fingerprint, event.reason))\n finally:\n if hs_desc_listener:\n self.remove_event_listener(hs_desc_listener)\n if hs_desc_content_listener:\n self.remove_event_listener(hs_desc_content_listener)\n ", "context": "class Controller(BaseController):\n @with_default()\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000967.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "attach_stream", "tests": "import unittest\n\nclass Test_attach_stream(unittest.TestCase):\n @test.require.controller\n @test.require.online\n @test.require.version(Requirement.EXTENDCIRCUIT_PATH_OPTIONAL)\n def test_attachstream(self):\n host = socket.gethostbyname('www.torproject.org')\n port = 80\n circuit_id, streams = (None, [])\n\n def handle_streamcreated(stream):\n if stream.status == 'NEW' and circuit_id:\n controller.attach_stream(stream.id, circuit_id)\n with test.runner.get_runner().get_tor_controller() as controller:\n for i in range(10):\n controller.add_event_listener(handle_streamcreated, stem.control.EventType.STREAM)\n controller.set_conf('__LeaveStreamsUnattached', '1')\n try:\n circuit_id = controller.new_circuit(await_build=True)\n socks_listener = controller.get_socks_listeners()[0]\n with test.network.Socks(socks_listener) as s:\n s.settimeout(30)\n s.connect((host, port))\n streams = controller.get_streams()\n break\n except (stem.CircuitExtensionFailed, socket.timeout):\n continue\n finally:\n controller.remove_event_listener(handle_streamcreated)\n controller.reset_conf('__LeaveStreamsUnattached')\n our_stream = [stream for stream in streams if stream.target_address == host][0]\n self.assertTrue(our_stream.circ_id)\n self.assertTrue(circuit_id)\n self.assertEqual(our_stream.circ_id, circuit_id)\n", "method_code": " def attach_stream(self, stream_id, circuit_id, exiting_hop=None):\n \"\"\"\n Attaches a stream to a circuit.\n \n Note: Tor attaches streams to circuits automatically unless the\n __LeaveStreamsUnattached configuration variable is set to '1'\n \n :param str stream_id: id of the stream that must be attached\n :param str circuit_id: id of the circuit to which it must be attached\n :param int exiting_hop: hop in the circuit where traffic should exit\n \n :raises:\n * :class:`stem.InvalidRequest` if the stream or circuit id were unrecognized\n * :class:`stem.UnsatisfiableRequest` if the stream isn't in a state where it can be attached\n * :class:`stem.OperationFailed` if the stream couldn't be attached for any other reason\n \"\"\"\n query = 'ATTACHSTREAM %s %s' % (stream_id, circuit_id)\n if exiting_hop:\n query += ' HOP=%s' % exiting_hop\n response = self.msg(query)\n stem.response.convert('SINGLELINE', response)\n if not response.is_ok():\n if response.code == '552':\n raise stem.InvalidRequest(response.code, response.message)\n elif response.code == '551':\n raise stem.OperationFailed(response.code, response.message)\n elif response.code == '555':\n raise stem.UnsatisfiableRequest(response.code, response.message)\n else:\n raise stem.ProtocolError('ATTACHSTREAM returned unexpected response code: %s' % response.code)\n ", "context": "class Controller(BaseController):\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000968.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "get_circuits", "tests": "import unittest\n\nclass Test_get_circuits(unittest.TestCase):\n @test.require.controller\n @test.require.online\n @test.require.version(Requirement.EXTENDCIRCUIT_PATH_OPTIONAL)\n def test_get_circuits(self):\n \"\"\"\n Fetches circuits via the get_circuits() method.\n \"\"\"\n with test.runner.get_runner().get_tor_controller() as controller:\n new_circ = controller.new_circuit()\n circuits = controller.get_circuits()\n self.assertTrue(new_circ in [circ.id for circ in circuits])\n", "method_code": " def get_circuits(self, default=UNDEFINED):\n \"\"\"\n get_circuits(default = UNDEFINED)\n \n Provides tor's currently available circuits.\n \n :param object default: response if the query fails\n \n :returns: **list** of :class:`stem.response.events.CircuitEvent` for our circuits\n \n :raises: :class:`stem.ControllerError` if the call fails and no default was provided\n \"\"\"\n circuits = []\n response = self.get_info('circuit-status')\n for circ in response.splitlines():\n circ_message = stem.socket.recv_message(io.BytesIO(stem.util.str_tools._to_bytes('650 CIRC %s\\r\\n' % circ)))\n stem.response.convert('EVENT', circ_message, arrived_at=0)\n circuits.append(circ_message)\n return circuits\n ", "context": "class Controller(BaseController):\n @with_default()\n def get_circuits(self, default=UNDEFINED): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000969.py"} {"focal_file": "stem/connection.py", "focal_class": null, "focal_method": "connect", "tests": "import unittest\n\nclass Test_connect(unittest.TestCase):\n @test.require.controller\n @patch('sys.stdout', new_callable=StringIO)\n def test_connect(self, stdout_mock):\n \"\"\"\n Basic sanity checks for the connect function.\n \"\"\"\n runner = test.runner.get_runner()\n control_socket = stem.connection.connect(control_port=('127.0.0.1', test.runner.CONTROL_PORT), control_socket=test.runner.CONTROL_SOCKET_PATH, password=test.runner.CONTROL_PASSWORD, chroot_path=runner.get_chroot(), controller=None)\n test.runner.exercise_controller(self, control_socket)\n self.assertEqual('', stdout_mock.getvalue())\n", "method_code": "def connect(control_port=('127.0.0.1', 'default'), control_socket='/var/run/tor/control', password=None, password_prompt=False, chroot_path=None, controller=stem.control.Controller):\n \"\"\"\n Convenience function for quickly getting a control connection. This is very\n handy for debugging or CLI setup, handling setup and prompting for a password\n if necessary (and none is provided). If any issues arise this prints a\n description of the problem and returns **None**.\n\n If both a **control_port** and **control_socket** are provided then the\n **control_socket** is tried first, and this provides a generic error message\n if they're both unavailable.\n\n In much the same vein as git porcelain commands, users should not rely on\n details of how this works. Messages and details of this function's behavior\n could change in the future.\n\n If the **port** is **'default'** then this checks on both 9051 (default for\n relays) and 9151 (default for the Tor Browser). This default may change in\n the future.\n\n .. versionadded:: 1.2.0\n\n .. versionchanged:: 1.5.0\n Use both port 9051 and 9151 by default.\n\n :param tuple contol_port: address and port tuple, for instance **('127.0.0.1', 9051)**\n :param str path: path where the control socket is located\n :param str password: passphrase to authenticate to the socket\n :param bool password_prompt: prompt for the controller password if it wasn't\n supplied\n :param str chroot_path: path prefix if in a chroot environment\n :param Class controller: :class:`~stem.control.BaseController` subclass to be\n returned, this provides a :class:`~stem.socket.ControlSocket` if **None**\n\n :returns: authenticated control connection, the type based on the controller argument\n\n :raises: **ValueError** if given an invalid control_port, or both\n **control_port** and **control_socket** are **None**\n \"\"\"\n if control_port is None and control_socket is None:\n raise ValueError('Neither a control port nor control socket were provided. Nothing to connect to.')\n elif control_port:\n if len(control_port) != 2:\n raise ValueError('The control_port argument for connect() should be an (address, port) tuple.')\n elif not stem.util.connection.is_valid_ipv4_address(control_port[0]):\n raise ValueError(\"'%s' isn't a vaid IPv4 address\" % control_port[0])\n elif control_port[1] != 'default' and (not stem.util.connection.is_valid_port(control_port[1])):\n raise ValueError(\"'%s' isn't a valid port\" % control_port[1])\n control_connection, error_msg = (None, '')\n if control_socket:\n if os.path.exists(control_socket):\n try:\n control_connection = stem.socket.ControlSocketFile(control_socket)\n except stem.SocketError as exc:\n error_msg = CONNECT_MESSAGES['unable_to_use_socket'].format(path=control_socket, error=exc)\n else:\n error_msg = CONNECT_MESSAGES['socket_doesnt_exist'].format(path=control_socket)\n if control_port and (not control_connection):\n address, port = control_port\n try:\n if port == 'default':\n control_connection = _connection_for_default_port(address)\n else:\n control_connection = stem.socket.ControlPort(address, int(port))\n except stem.SocketError as exc:\n error_msg = CONNECT_MESSAGES['unable_to_use_port'].format(address=address, port=port, error=exc)\n if not control_connection:\n if control_socket and control_port:\n is_tor_running = stem.util.system.is_running(COMMON_TOR_COMMANDS)\n error_msg = CONNECT_MESSAGES['no_control_port'] if is_tor_running else CONNECT_MESSAGES['tor_isnt_running']\n print(error_msg)\n return None\n return _connect_auth(control_connection, password, password_prompt, chroot_path, controller)", "context": "def connect(control_port=('127.0.0.1', 'default'), control_socket='/var/run/tor/control', password=None, password_prompt=False, chroot_path=None, controller=stem.control.Controller): ...\ndef connect(control_port=('127.0.0.1', 'default'), control_socket='/var/run/tor/control', password=None, password_prompt=False, chroot_path=None, controller=stem.control.Controller): ...\ndef connect_port(address='127.0.0.1', port=9051, password=None, chroot_path=None, controller=stem.control.Controller): ...\ndef connect_socket_file(path='/var/run/tor/control', password=None, chroot_path=None, controller=stem.control.Controller): ...\ndef _connect_auth(control_socket, password, password_prompt, chroot_path, controller): ...\ndef authenticate(controller, password=None, chroot_path=None, protocolinfo_response=None): ...\ndef authenticate_none(controller, suppress_ctl_errors=True): ...\ndef authenticate_password(controller, password, suppress_ctl_errors=True): ...\ndef authenticate_cookie(controller, cookie_path, suppress_ctl_errors=True): ...\ndef authenticate_safecookie(controller, cookie_path, suppress_ctl_errors=True): ...\ndef get_protocolinfo(controller): ...\ndef _msg(controller, message): ...\ndef _connection_for_default_port(address): ...\ndef _read_cookie(cookie_path, is_safecookie): ...\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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_000970.py"} {"focal_file": "stem/connection.py", "focal_class": null, "focal_method": "connect_port", "tests": "import unittest\n\nclass Test_connect_port(unittest.TestCase):\n @test.require.controller\n @patch('sys.stdout', new_callable=StringIO)\n def test_connect_port(self, stdout_mock):\n \"\"\"\n Basic sanity checks for the connect_port function.\n \"\"\"\n runner = test.runner.get_runner()\n control_socket = stem.connection.connect_port(port=test.runner.CONTROL_PORT, password=test.runner.CONTROL_PASSWORD, chroot_path=runner.get_chroot(), controller=None)\n if test.runner.Torrc.PORT in runner.get_options():\n test.runner.exercise_controller(self, control_socket)\n control_socket.close()\n self.assertEqual('', stdout_mock.getvalue())\n else:\n self.assertEqual(control_socket, None)\n\n @test.require.controller\n @patch('sys.stdout', new_callable=StringIO)\n def test_connect_to_socks_port(self, stdout_mock):\n \"\"\"\n Common user gotcha is connecting to the SocksPort or ORPort rather than the\n ControlPort. Testing that connecting to the SocksPort errors in a\n reasonable way.\n \"\"\"\n runner = test.runner.get_runner()\n control_socket = stem.connection.connect_port(port=test.runner.SOCKS_PORT, chroot_path=runner.get_chroot(), controller=None)\n self.assertEqual(None, control_socket)\n self.assertEqual('Please check in your torrc that 1112 is the ControlPort. Maybe you\\nconfigured it to be the ORPort or SocksPort instead?\\n', stdout_mock.getvalue())\n", "method_code": "def connect_port(address='127.0.0.1', port=9051, password=None, chroot_path=None, controller=stem.control.Controller):\n \"\"\"\n Convenience function for quickly getting a control connection. This is very\n handy for debugging or CLI setup, handling setup and prompting for a password\n if necessary (and none is provided). If any issues arise this prints a\n description of the problem and returns **None**.\n\n .. deprecated:: 1.2.0\n Use :func:`~stem.connection.connect` instead.\n\n :param str address: ip address of the controller\n :param int port: port number of the controller\n :param str password: passphrase to authenticate to the socket\n :param str chroot_path: path prefix if in a chroot environment\n :param Class controller: :class:`~stem.control.BaseController` subclass to be\n returned, this provides a :class:`~stem.socket.ControlSocket` if **None**\n\n :returns: authenticated control connection, the type based on the controller argument\n \"\"\"\n try:\n control_port = stem.socket.ControlPort(address, port)\n except stem.SocketError as exc:\n print(exc)\n return None\n return _connect_auth(control_port, password, True, chroot_path, controller)", "context": "def connect_port(address='127.0.0.1', port=9051, password=None, chroot_path=None, controller=stem.control.Controller): ...\ndef connect(control_port=('127.0.0.1', 'default'), control_socket='/var/run/tor/control', password=None, password_prompt=False, chroot_path=None, controller=stem.control.Controller): ...\ndef connect_port(address='127.0.0.1', port=9051, password=None, chroot_path=None, controller=stem.control.Controller): ...\ndef connect_socket_file(path='/var/run/tor/control', password=None, chroot_path=None, controller=stem.control.Controller): ...\ndef _connect_auth(control_socket, password, password_prompt, chroot_path, controller): ...\ndef authenticate(controller, password=None, chroot_path=None, protocolinfo_response=None): ...\ndef authenticate_none(controller, suppress_ctl_errors=True): ...\ndef authenticate_password(controller, password, suppress_ctl_errors=True): ...\ndef authenticate_cookie(controller, cookie_path, suppress_ctl_errors=True): ...\ndef authenticate_safecookie(controller, cookie_path, suppress_ctl_errors=True): ...\ndef get_protocolinfo(controller): ...\ndef _msg(controller, message): ...\ndef _connection_for_default_port(address): ...\ndef _read_cookie(cookie_path, is_safecookie): ...\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000971.py"} {"focal_file": "stem/connection.py", "focal_class": null, "focal_method": "connect_socket_file", "tests": "import unittest\n\nclass Test_connect_socket_file(unittest.TestCase):\n @test.require.controller\n @patch('sys.stdout', new_callable=StringIO)\n def test_connect_socket_file(self, stdout_mock):\n \"\"\"\n Basic sanity checks for the connect_socket_file function.\n \"\"\"\n runner = test.runner.get_runner()\n control_socket = stem.connection.connect_socket_file(path=test.runner.CONTROL_SOCKET_PATH, password=test.runner.CONTROL_PASSWORD, chroot_path=runner.get_chroot(), controller=None)\n if test.runner.Torrc.SOCKET in runner.get_options():\n test.runner.exercise_controller(self, control_socket)\n control_socket.close()\n self.assertEqual('', stdout_mock.getvalue())\n else:\n self.assertEqual(control_socket, None)\n", "method_code": "def connect_socket_file(path='/var/run/tor/control', password=None, chroot_path=None, controller=stem.control.Controller):\n \"\"\"\n Convenience function for quickly getting a control connection. For more\n information see the :func:`~stem.connection.connect_port` function.\n\n In much the same vein as git porcelain commands, users should not rely on\n details of how this works. Messages or details of this function's behavior\n might change in the future.\n\n .. deprecated:: 1.2.0\n Use :func:`~stem.connection.connect` instead.\n\n :param str path: path where the control socket is located\n :param str password: passphrase to authenticate to the socket\n :param str chroot_path: path prefix if in a chroot environment\n :param Class controller: :class:`~stem.control.BaseController` subclass to be\n returned, this provides a :class:`~stem.socket.ControlSocket` if **None**\n\n :returns: authenticated control connection, the type based on the controller argument\n \"\"\"\n try:\n control_socket = stem.socket.ControlSocketFile(path)\n except stem.SocketError as exc:\n print(exc)\n return None\n return _connect_auth(control_socket, password, True, chroot_path, controller)", "context": "def connect_socket_file(path='/var/run/tor/control', password=None, chroot_path=None, controller=stem.control.Controller): ...\ndef connect(control_port=('127.0.0.1', 'default'), control_socket='/var/run/tor/control', password=None, password_prompt=False, chroot_path=None, controller=stem.control.Controller): ...\ndef connect_port(address='127.0.0.1', port=9051, password=None, chroot_path=None, controller=stem.control.Controller): ...\ndef connect_socket_file(path='/var/run/tor/control', password=None, chroot_path=None, controller=stem.control.Controller): ...\ndef _connect_auth(control_socket, password, password_prompt, chroot_path, controller): ...\ndef authenticate(controller, password=None, chroot_path=None, protocolinfo_response=None): ...\ndef authenticate_none(controller, suppress_ctl_errors=True): ...\ndef authenticate_password(controller, password, suppress_ctl_errors=True): ...\ndef authenticate_cookie(controller, cookie_path, suppress_ctl_errors=True): ...\ndef authenticate_safecookie(controller, cookie_path, suppress_ctl_errors=True): ...\ndef get_protocolinfo(controller): ...\ndef _msg(controller, message): ...\ndef _connection_for_default_port(address): ...\ndef _read_cookie(cookie_path, is_safecookie): ...\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000972.py"} {"focal_file": "stem/util/system.py", "focal_class": null, "focal_method": "is_available", "tests": "import unittest\n\nclass Test_is_available(unittest.TestCase):\n @require_path\n def test_is_available(self):\n \"\"\"\n Checks the stem.util.system.is_available function.\n \"\"\"\n if stem.util.system.is_windows():\n self.assertTrue(stem.util.system.is_available('dir'))\n else:\n self.assertTrue(stem.util.system.is_available('ls'))\n self.assertFalse(stem.util.system.is_available('blarg_and_stuff'))\n", "method_code": "def is_available(command, cached=True):\n \"\"\"\n Checks the current PATH to see if a command is available or not. If more\n than one command is present (for instance \"ls -a | grep foo\") then this\n just checks the first.\n\n Note that shell (like cd and ulimit) aren't in the PATH so this lookup will\n try to assume that it's available. This only happends for recognized shell\n commands (those in SHELL_COMMANDS).\n\n :param str command: command to search for\n :param bool cached: makes use of available cached results if **True**\n\n :returns: **True** if an executable we can use by that name exists in the\n PATH, **False** otherwise\n \"\"\"\n if ' ' in command:\n command = command.split(' ')[0]\n if command in SHELL_COMMANDS:\n return True\n elif cached and command in CMD_AVAILABLE_CACHE:\n return CMD_AVAILABLE_CACHE[command]\n elif 'PATH' not in os.environ:\n return False\n cmd_exists = False\n for path in os.environ['PATH'].split(os.pathsep):\n cmd_path = os.path.join(path, command)\n if is_windows():\n cmd_path += '.exe'\n if os.path.exists(cmd_path) and os.access(cmd_path, os.X_OK):\n cmd_exists = True\n break\n CMD_AVAILABLE_CACHE[command] = cmd_exists\n return cmd_exists", "context": "def is_available(command, cached=True): ...\ndef is_windows(): ...\ndef is_mac(): ...\ndef is_gentoo(): ...\ndef is_slackware(): ...\ndef is_bsd(): ...\ndef is_available(command, cached=True): ...\ndef is_running(command): ...\ndef size_of(obj, exclude=None): ...\ndef name_by_pid(pid): ...\ndef pid_by_name(process_name, multiple=False): ...\ndef pid_by_port(port): ...\ndef pid_by_open_file(path): ...\ndef pids_by_user(user): ...\ndef cwd(pid): ...\ndef user(pid): ...\ndef start_time(pid): ...\ndef tail(target, lines=None): ...\ndef bsd_jail_id(pid): ...\ndef bsd_jail_path(jid): ...\ndef is_tarfile(path): ...\ndef expand_path(path, cwd=None): ...\ndef files_with_suffix(base_path, suffix): ...\ndef call(command, default=UNDEFINED, ignore_exit_status=False, timeout=None, cwd=None, env=None): ...\ndef get_process_name(): ...\ndef set_process_name(process_name): ...\ndef _set_argv(process_name): ...\ndef _set_prctl_name(process_name): ...\ndef _set_proc_title(process_name): ...\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000973.py"} {"focal_file": "stem/util/system.py", "focal_class": null, "focal_method": "is_running", "tests": "import unittest\n\nclass Test_is_running(unittest.TestCase):\n def test_is_running_by_pid(self):\n \"\"\"\n Checks the stem.util.system.is_running function with a pid.\n \"\"\"\n self.assertTrue(stem.util.system.is_running(test.runner.get_runner().get_pid()))\n self.assertFalse(stem.util.system.is_running(528955))\n\n @test.require.command('ps')\n def test_is_running_by_name(self):\n \"\"\"\n Checks the stem.util.system.is_running function with a process name.\n \"\"\"\n tor_cmd = test.runner.get_runner().get_tor_command(True)\n self.assertTrue(stem.util.system.is_running(tor_cmd) or stem.util.system.is_running('tor.real'))\n self.assertFalse(stem.util.system.is_running('blarg_and_stuff'))\n\n @patch('stem.util.system.call')\n @patch('stem.util.system.is_available', Mock(return_value=True))\n def test_is_running(self, call_mock):\n \"\"\"\n Exercises multiple use cases for the is_running function.\n \"\"\"\n running_commands = ['irssi', 'moc', 'tor', 'ps', ' firefox ']\n for ps_cmd in (system.IS_RUNNING_PS_LINUX, system.IS_RUNNING_PS_BSD):\n call_mock.side_effect = mock_call(ps_cmd, running_commands)\n self.assertTrue(system.is_running('irssi'))\n self.assertTrue(system.is_running('moc'))\n self.assertTrue(system.is_running('tor'))\n self.assertTrue(system.is_running(['funky-tor', 'tor']))\n self.assertTrue(system.is_running('ps'))\n self.assertTrue(system.is_running('firefox'))\n self.assertFalse(system.is_running('something_else'))\n self.assertFalse(system.is_running(['funky-tor', 'funkier-tor']))\n call_mock.return_value = None\n call_mock.side_effect = None\n self.assertFalse(system.is_running('irssi'))\n self.assertEqual(None, system.is_running('irssi'))\n", "method_code": "def is_running(command):\n \"\"\"\n Checks for if a process with a given name or pid is running.\n\n .. versionchanged:: 1.6.0\n Added support for list and pid arguments.\n\n :param str,list,int command: process name if a str, multiple process names if\n a list, or pid if an int to be checked\n\n :returns: **True** if the process is running, **False** if it's not among ps\n results, and **None** if ps can't be queried\n \"\"\"\n if isinstance(command, int):\n try:\n os.kill(command, 0)\n return True\n except OSError:\n return False\n if is_available('ps'):\n if is_bsd():\n primary_resolver = IS_RUNNING_PS_BSD\n secondary_resolver = IS_RUNNING_PS_LINUX\n else:\n primary_resolver = IS_RUNNING_PS_LINUX\n secondary_resolver = IS_RUNNING_PS_BSD\n command_listing = call(primary_resolver, None)\n if not command_listing:\n command_listing = call(secondary_resolver, None)\n if command_listing:\n command_listing = [c.strip() for c in command_listing]\n if stem.util._is_str(command):\n command = [command]\n for cmd in command:\n if cmd in command_listing:\n return True\n return False\n return None", "context": "def is_running(command): ...\ndef is_windows(): ...\ndef is_mac(): ...\ndef is_gentoo(): ...\ndef is_slackware(): ...\ndef is_bsd(): ...\ndef is_available(command, cached=True): ...\ndef is_running(command): ...\ndef size_of(obj, exclude=None): ...\ndef name_by_pid(pid): ...\ndef pid_by_name(process_name, multiple=False): ...\ndef pid_by_port(port): ...\ndef pid_by_open_file(path): ...\ndef pids_by_user(user): ...\ndef cwd(pid): ...\ndef user(pid): ...\ndef start_time(pid): ...\ndef tail(target, lines=None): ...\ndef bsd_jail_id(pid): ...\ndef bsd_jail_path(jid): ...\ndef is_tarfile(path): ...\ndef expand_path(path, cwd=None): ...\ndef files_with_suffix(base_path, suffix): ...\ndef call(command, default=UNDEFINED, ignore_exit_status=False, timeout=None, cwd=None, env=None): ...\ndef get_process_name(): ...\ndef set_process_name(process_name): ...\ndef _set_argv(process_name): ...\ndef _set_prctl_name(process_name): ...\ndef _set_proc_title(process_name): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_is_running_by_pid", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000974.py"} {"focal_file": "stem/util/system.py", "focal_class": null, "focal_method": "pid_by_name", "tests": "import unittest\n\nclass Test_pid_by_name(unittest.TestCase):\n @require_path\n @require_single_tor_instance\n def test_pid_by_name(self):\n \"\"\"\n Checks general usage of the stem.util.system.pid_by_name function. This\n will fail if there's other tor instances running.\n \"\"\"\n tor_pid = test.runner.get_runner().get_pid()\n tor_cmd = test.runner.get_runner().get_tor_command(True)\n self.assertEqual(tor_pid, stem.util.system.pid_by_name(tor_cmd))\n self.assertEqual(None, stem.util.system.pid_by_name('blarg_and_stuff'))\n\n @require_single_tor_instance\n @test.require.command('pgrep')\n def test_pid_by_name_pgrep(self):\n \"\"\"\n Tests the pid_by_name function with a pgrep response.\n \"\"\"\n pgrep_prefix = stem.util.system.GET_PID_BY_NAME_PGREP % ''\n call_replacement = filter_system_call([pgrep_prefix])\n with patch('stem.util.system.call') as call_mock:\n call_mock.side_effect = call_replacement\n tor_pid = test.runner.get_runner().get_pid()\n tor_cmd = test.runner.get_runner().get_tor_command(True)\n self.assertEqual(tor_pid, stem.util.system.pid_by_name(tor_cmd))\n\n @require_single_tor_instance\n @test.require.command('pidof')\n def test_pid_by_name_pidof(self):\n \"\"\"\n Tests the pid_by_name function with a pidof response.\n \"\"\"\n pidof_prefix = stem.util.system.GET_PID_BY_NAME_PIDOF % ''\n call_replacement = filter_system_call([pidof_prefix])\n with patch('stem.util.system.call') as call_mock:\n call_mock.side_effect = call_replacement\n tor_pid = test.runner.get_runner().get_pid()\n tor_cmd = test.runner.get_runner().get_tor_command()\n self.assertEqual(tor_pid, stem.util.system.pid_by_name(tor_cmd))\n\n @require_linux\n @require_single_tor_instance\n @test.require.command('ps')\n def test_pid_by_name_ps_linux(self):\n \"\"\"\n Tests the pid_by_name function with the linux variant of ps.\n \"\"\"\n ps_prefix = stem.util.system.GET_PID_BY_NAME_PS_LINUX % ''\n call_replacement = filter_system_call([ps_prefix])\n with patch('stem.util.system.call') as call_mock:\n call_mock.side_effect = call_replacement\n tor_pid = test.runner.get_runner().get_pid()\n tor_cmd = test.runner.get_runner().get_tor_command(True)\n self.assertEqual(tor_pid, stem.util.system.pid_by_name(tor_cmd))\n\n @require_bsd\n @require_single_tor_instance\n @test.require.command('ps')\n def test_pid_by_name_ps_bsd(self):\n \"\"\"\n Tests the pid_by_name function with the bsd variant of ps.\n \"\"\"\n ps_prefix = stem.util.system.GET_PID_BY_NAME_PS_BSD\n call_replacement = filter_system_call([ps_prefix])\n with patch('stem.util.system.call') as call_mock:\n call_mock.side_effect = call_replacement\n tor_pid = test.runner.get_runner().get_pid()\n tor_cmd = test.runner.get_runner().get_tor_command(True)\n self.assertEqual(tor_pid, stem.util.system.pid_by_name(tor_cmd))\n\n @require_single_tor_instance\n @test.require.ptrace\n @test.require.command('lsof')\n def test_pid_by_name_lsof(self):\n \"\"\"\n Tests the pid_by_name function with a lsof response.\n \"\"\"\n lsof_prefix = stem.util.system.GET_PID_BY_NAME_LSOF % ''\n call_replacement = filter_system_call([lsof_prefix])\n with patch('stem.util.system.call') as call_mock:\n call_mock.side_effect = call_replacement\n tor_cmd = test.runner.get_runner().get_tor_command(True)\n our_tor_pid = test.runner.get_runner().get_pid()\n all_tor_pids = stem.util.system.pid_by_name(tor_cmd, multiple=True)\n if len(all_tor_pids) == 1:\n self.assertEqual(our_tor_pid, all_tor_pids[0])\n\n @require_single_tor_instance\n @test.require.command('tasklist')\n def test_pid_by_name_tasklist(self):\n \"\"\"\n Tests the pid_by_name function with a tasklist response.\n \"\"\"\n runner = test.runner.get_runner()\n self.assertEqual(runner.get_pid(), stem.util.system.pid_by_name(runner.get_tor_command(True)))\n\n @patch('stem.util.system.call')\n @patch('stem.util.system.is_available', Mock(return_value=True))\n @patch('stem.util.system.is_windows', Mock(return_value=False))\n def test_pid_by_name_pgrep(self, call_mock):\n \"\"\"\n Tests the pid_by_name function with pgrep responses.\n \"\"\"\n responses = dict(GET_PID_BY_NAME_BASE_RESULTS)\n responses['success'] = ['1111']\n responses['multiple_results'] = ['123', '456', '789']\n call_mock.side_effect = mock_call(system.GET_PID_BY_NAME_PGREP, responses)\n for test_input in responses:\n expected_response = 1111 if test_input == 'success' else None\n self.assertEqual(expected_response, system.pid_by_name(test_input))\n self.assertEqual([123, 456, 789], system.pid_by_name('multiple_results', multiple=True))\n\n @patch('stem.util.system.call')\n @patch('stem.util.system.is_available', Mock(return_value=True))\n @patch('stem.util.system.is_windows', Mock(return_value=False))\n def test_pid_by_name_pidof(self, call_mock):\n \"\"\"\n Tests the pid_by_name function with pidof responses.\n \"\"\"\n responses = dict(GET_PID_BY_NAME_BASE_RESULTS)\n responses['success'] = ['1111']\n responses['multiple_results'] = ['123 456 789']\n call_mock.side_effect = mock_call(system.GET_PID_BY_NAME_PIDOF, responses)\n for test_input in responses:\n expected_response = 1111 if test_input == 'success' else None\n self.assertEqual(expected_response, system.pid_by_name(test_input))\n self.assertEqual([123, 456, 789], system.pid_by_name('multiple_results', multiple=True))\n\n @patch('stem.util.system.call')\n @patch('stem.util.system.is_bsd', Mock(return_value=False))\n @patch('stem.util.system.is_windows', Mock(return_value=False))\n @patch('stem.util.system.is_available', Mock(return_value=True))\n def test_pid_by_name_ps_linux(self, call_mock):\n \"\"\"\n Tests the pid_by_name function with the linux variant of ps.\n \"\"\"\n responses = dict(GET_PID_BY_NAME_BASE_RESULTS)\n responses['success'] = ['PID', ' 1111']\n responses['multiple_results'] = ['PID', ' 123', ' 456', ' 789']\n call_mock.side_effect = mock_call(system.GET_PID_BY_NAME_PS_LINUX, responses)\n for test_input in responses:\n expected_response = 1111 if test_input == 'success' else None\n self.assertEqual(expected_response, system.pid_by_name(test_input))\n self.assertEqual([123, 456, 789], system.pid_by_name('multiple_results', multiple=True))\n\n @patch('stem.util.system.call')\n @patch('stem.util.system.is_bsd', Mock(return_value=True))\n @patch('stem.util.system.is_windows', Mock(return_value=False))\n @patch('stem.util.system.is_available', Mock(return_value=True))\n def test_pid_by_name_ps_bsd(self, call_mock):\n \"\"\"\n Tests the pid_by_name function with the bsd variant of ps.\n \"\"\"\n call_mock.side_effect = mock_call(system.GET_PID_BY_NAME_PS_BSD, GET_PID_BY_NAME_PS_BSD)\n self.assertEqual(1, system.pid_by_name('launchd'))\n self.assertEqual(11, system.pid_by_name('DirectoryService'))\n self.assertEqual(None, system.pid_by_name('blarg'))\n call_mock.side_effect = mock_call(system.GET_PID_BY_NAME_PS_BSD, GET_PID_BY_NAME_PS_BSD_MULTIPLE)\n self.assertEqual([1, 41], system.pid_by_name('launchd', multiple=True))\n\n @patch('stem.util.system.call')\n @patch('stem.util.system.is_available', Mock(return_value=True))\n @patch('stem.util.system.is_windows', Mock(return_value=False))\n def test_pid_by_name_lsof(self, call_mock):\n \"\"\"\n Tests the pid_by_name function with lsof responses.\n \"\"\"\n responses = dict(GET_PID_BY_NAME_BASE_RESULTS)\n responses['success'] = ['1111']\n responses['multiple_results'] = ['123', '456', '789']\n call_mock.side_effect = mock_call(system.GET_PID_BY_NAME_LSOF, responses)\n for test_input in responses:\n expected_response = 1111 if test_input == 'success' else None\n self.assertEqual(expected_response, system.pid_by_name(test_input))\n self.assertEqual([123, 456, 789], system.pid_by_name('multiple_results', multiple=True))\n\n @patch('stem.util.system.call')\n @patch('stem.util.system.is_available', Mock(return_value=True))\n @patch('stem.util.system.is_windows', Mock(return_value=True))\n def test_pid_by_name_tasklist(self, call_mock):\n \"\"\"\n Tests the pid_by_name function with tasklist responses.\n \"\"\"\n call_mock.side_effect = mock_call('tasklist', GET_PID_BY_NAME_TASKLIST_RESULTS)\n self.assertEqual(3712, system.pid_by_name('tor'))\n self.assertEqual(None, system.pid_by_name('DirectoryService'))\n self.assertEqual(None, system.pid_by_name('blarg'))\n self.assertEqual([3712, 3713], system.pid_by_name('tor', multiple=True))\n", "method_code": "def pid_by_name(process_name, multiple=False):\n \"\"\"\n Attempts to determine the process id for a running process, using...\n\n ::\n\n 1. pgrep -x \n 2. pidof \n 3. ps -o pid -C (linux)\n ps axc | egrep \" $\" (bsd)\n 4. lsof -tc \n 5. tasklist | str .exe\n\n :param str process_name: process name for which to fetch the pid\n :param bool multiple: provides a list of all pids if **True**, otherwise\n results with multiple processes are discarded\n\n :returns:\n Response depends upon the 'multiple' argument as follows...\n\n * if **False** then this provides an **int** with the process id or **None** if it can't be determined\n * if **True** then this provides a **list** of all **int** process ids, and an empty list if it can't be determined\n \"\"\"\n if is_available('pgrep'):\n results = call(GET_PID_BY_NAME_PGREP % process_name, None)\n if results:\n try:\n pids = list(map(int, results))\n if multiple:\n return pids\n elif len(pids) == 1:\n return pids[0]\n except ValueError:\n pass\n if is_available('pidof'):\n results = call(GET_PID_BY_NAME_PIDOF % process_name, None)\n if results and len(results) == 1:\n try:\n pids = list(map(int, results[0].split()))\n if multiple:\n return pids\n elif len(pids) == 1:\n return pids[0]\n except ValueError:\n pass\n if is_available('ps'):\n if not is_bsd():\n results = call(GET_PID_BY_NAME_PS_LINUX % process_name, None)\n if results:\n try:\n pids = list(map(int, results[1:]))\n if multiple:\n return pids\n elif len(pids) == 1:\n return pids[0]\n except ValueError:\n pass\n if is_bsd():\n results = call(GET_PID_BY_NAME_PS_BSD, None)\n if results:\n results = [r.split()[0] for r in results if r.endswith(' %s' % process_name)]\n try:\n pids = list(map(int, results))\n if multiple:\n return pids\n elif len(pids) == 1:\n return pids[0]\n except ValueError:\n pass\n if is_available('lsof'):\n results = call(GET_PID_BY_NAME_LSOF % process_name, None)\n if results:\n try:\n pids = list(map(int, results))\n if multiple:\n return pids\n elif len(pids) == 1:\n return pids[0]\n except ValueError:\n pass\n if is_available('tasklist') and is_windows():\n if not process_name.endswith('.exe'):\n process_name = process_name + '.exe'\n process_ids = []\n results = stem.util.system.call('tasklist', None)\n if results:\n tasklist_regex = re.compile('^\\\\s*%s\\\\s+(?P[0-9]*)' % process_name)\n for line in results:\n match = tasklist_regex.search(line)\n if match:\n process_ids.append(int(match.group('pid')))\n if multiple:\n return process_ids\n elif len(process_ids) > 0:\n return process_ids[0]\n log.debug(\"failed to resolve a pid for '%s'\" % process_name)\n return [] if multiple else None", "context": "def pid_by_name(process_name, multiple=False): ...\ndef is_windows(): ...\ndef is_mac(): ...\ndef is_gentoo(): ...\ndef is_slackware(): ...\ndef is_bsd(): ...\ndef is_available(command, cached=True): ...\ndef is_running(command): ...\ndef size_of(obj, exclude=None): ...\ndef name_by_pid(pid): ...\ndef pid_by_name(process_name, multiple=False): ...\ndef pid_by_port(port): ...\ndef pid_by_open_file(path): ...\ndef pids_by_user(user): ...\ndef cwd(pid): ...\ndef user(pid): ...\ndef start_time(pid): ...\ndef tail(target, lines=None): ...\ndef bsd_jail_id(pid): ...\ndef bsd_jail_path(jid): ...\ndef is_tarfile(path): ...\ndef expand_path(path, cwd=None): ...\ndef files_with_suffix(base_path, suffix): ...\ndef call(command, default=UNDEFINED, ignore_exit_status=False, timeout=None, cwd=None, env=None): ...\ndef get_process_name(): ...\ndef set_process_name(process_name): ...\ndef _set_argv(process_name): ...\ndef _set_prctl_name(process_name): ...\ndef _set_proc_title(process_name): ...\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000975.py"} {"focal_file": "stem/util/system.py", "focal_class": null, "focal_method": "pid_by_port", "tests": "import unittest\n\nclass Test_pid_by_port(unittest.TestCase):\n @require_control_port\n @test.require.ptrace\n def test_pid_by_port(self):\n \"\"\"\n Checks general usage of the stem.util.system.pid_by_port function.\n \"\"\"\n if stem.util.system.is_windows():\n self.skipTest('(unavailable on windows)')\n return\n elif stem.util.system.is_mac() or stem.util.system.is_gentoo():\n self.skipTest('(resolvers unavailable)')\n return\n elif not (stem.util.system.is_available('netstat') or stem.util.system.is_available('sockstat') or stem.util.system.is_available('lsof')):\n self.skipTest('(connection resolvers unavailable)')\n return\n runner = test.runner.get_runner()\n tor_pid, tor_port = (runner.get_pid(), test.runner.CONTROL_PORT)\n self.assertEqual(tor_pid, stem.util.system.pid_by_port(tor_port))\n self.assertEqual(None, stem.util.system.pid_by_port(99999))\n\n @require_linux\n @require_control_port\n @test.require.ptrace\n @test.require.command('netstat')\n def test_pid_by_port_netstat(self):\n \"\"\"\n Tests the pid_by_port function with a netstat response.\n \"\"\"\n if stem.util.system.is_gentoo():\n self.skipTest('(unavailable on gentoo)')\n return\n netstat_prefix = stem.util.system.GET_PID_BY_PORT_NETSTAT\n call_replacement = filter_system_call([netstat_prefix])\n with patch('stem.util.system.call') as call_mock:\n call_mock.side_effect = call_replacement\n tor_pid = test.runner.get_runner().get_pid()\n self.assertEqual(tor_pid, stem.util.system.pid_by_port(test.runner.CONTROL_PORT))\n\n @require_bsd\n @require_control_port\n @test.require.ptrace\n @test.require.command('sockstat')\n def test_pid_by_port_sockstat(self):\n \"\"\"\n Tests the pid_by_port function with a sockstat response.\n \"\"\"\n sockstat_prefix = stem.util.system.GET_PID_BY_PORT_SOCKSTAT % ''\n call_replacement = filter_system_call([sockstat_prefix])\n with patch('stem.util.system.call') as call_mock:\n call_mock.side_effect = call_replacement\n tor_pid = test.runner.get_runner().get_pid()\n self.assertEqual(tor_pid, stem.util.system.pid_by_port(test.runner.CONTROL_PORT))\n\n @require_control_port\n @test.require.ptrace\n @test.require.command('lsof')\n def test_pid_by_port_lsof(self):\n \"\"\"\n Tests the pid_by_port function with a lsof response.\n \"\"\"\n if stem.util.system.is_mac() or stem.util.system.is_gentoo():\n self.skipTest('(resolvers unavailable)')\n return\n lsof_prefix = stem.util.system.GET_PID_BY_PORT_LSOF\n call_replacement = filter_system_call([lsof_prefix])\n with patch('stem.util.system.call') as call_mock:\n call_mock.side_effect = call_replacement\n tor_pid = test.runner.get_runner().get_pid()\n self.assertEqual(tor_pid, stem.util.system.pid_by_port(test.runner.CONTROL_PORT))\n\n @patch('stem.util.system.call')\n @patch('stem.util.system.is_available', Mock(return_value=True))\n def test_pid_by_port_netstat(self, call_mock):\n \"\"\"\n Tests the pid_by_port function with a netstat response.\n \"\"\"\n call_mock.side_effect = mock_call(system.GET_PID_BY_PORT_NETSTAT, GET_PID_BY_PORT_NETSTAT_RESULTS)\n self.assertEqual(1641, system.pid_by_port(9051))\n self.assertEqual(1641, system.pid_by_port('9051'))\n self.assertEqual(None, system.pid_by_port(631))\n self.assertEqual(None, system.pid_by_port(123))\n\n @patch('stem.util.system.call')\n @patch('stem.util.system.is_available', Mock(return_value=True))\n def test_pid_by_port_sockstat(self, call_mock):\n \"\"\"\n Tests the pid_by_port function with a sockstat response.\n \"\"\"\n call_mock.side_effect = mock_call(system.GET_PID_BY_PORT_SOCKSTAT % 9051, GET_PID_BY_PORT_SOCKSTAT_RESULTS)\n self.assertEqual(4397, system.pid_by_port(9051))\n self.assertEqual(4397, system.pid_by_port('9051'))\n self.assertEqual(None, system.pid_by_port(123))\n\n @patch('stem.util.system.call')\n @patch('stem.util.system.is_available', Mock(return_value=True))\n def test_pid_by_port_lsof(self, call_mock):\n \"\"\"\n Tests the pid_by_port function with a lsof response.\n \"\"\"\n call_mock.side_effect = mock_call(system.GET_PID_BY_PORT_LSOF, GET_PID_BY_PORT_LSOF_RESULTS)\n self.assertEqual(1745, system.pid_by_port(9051))\n self.assertEqual(1745, system.pid_by_port('9051'))\n self.assertEqual(329, system.pid_by_port(80))\n self.assertEqual(None, system.pid_by_port(123))\n", "method_code": "def pid_by_port(port):\n \"\"\"\n Attempts to determine the process id for a process with the given port,\n using...\n\n ::\n\n 1. netstat -npltu | grep 127.0.0.1:\n 2. sockstat -4l -P tcp -p \n 3. lsof -wnP -iTCP -sTCP:LISTEN | grep \":\"\n\n Most queries limit results to listening TCP connections. This function likely\n won't work on Mac OSX.\n\n :param int port: port where the process we're looking for is listening\n\n :returns: **int** with the process id, **None** if it can't be determined\n \"\"\"\n if is_available('netstat'):\n results = call(GET_PID_BY_PORT_NETSTAT, None)\n if results:\n results = [r for r in results if '127.0.0.1:%s' % port in r]\n if len(results) == 1 and len(results[0].split()) == 7:\n results = results[0].split()[6]\n pid = results[:results.find('/')]\n if pid.isdigit():\n return int(pid)\n if is_available('sockstat'):\n results = call(GET_PID_BY_PORT_SOCKSTAT % port, None)\n if results:\n results = [r for r in results if len(r.split()) == 7 and ':%s' % port in r.split()[5]]\n if len(results) == 1:\n pid = results[0].split()[2]\n if pid.isdigit():\n return int(pid)\n if is_available('lsof'):\n results = call(GET_PID_BY_PORT_LSOF, None)\n if results:\n results = [r for r in results if len(r.split()) == 10 and ':%s' % port in r.split()[8]]\n if len(results) == 1:\n pid = results[0].split()[1]\n if pid.isdigit():\n return int(pid)\n return None", "context": "def pid_by_port(port): ...\ndef is_windows(): ...\ndef is_mac(): ...\ndef is_gentoo(): ...\ndef is_slackware(): ...\ndef is_bsd(): ...\ndef is_available(command, cached=True): ...\ndef is_running(command): ...\ndef size_of(obj, exclude=None): ...\ndef name_by_pid(pid): ...\ndef pid_by_name(process_name, multiple=False): ...\ndef pid_by_port(port): ...\ndef pid_by_open_file(path): ...\ndef pids_by_user(user): ...\ndef cwd(pid): ...\ndef user(pid): ...\ndef start_time(pid): ...\ndef tail(target, lines=None): ...\ndef bsd_jail_id(pid): ...\ndef bsd_jail_path(jid): ...\ndef is_tarfile(path): ...\ndef expand_path(path, cwd=None): ...\ndef files_with_suffix(base_path, suffix): ...\ndef call(command, default=UNDEFINED, ignore_exit_status=False, timeout=None, cwd=None, env=None): ...\ndef get_process_name(): ...\ndef set_process_name(process_name): ...\ndef _set_argv(process_name): ...\ndef _set_prctl_name(process_name): ...\ndef _set_proc_title(process_name): ...\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000976.py"} {"focal_file": "stem/util/system.py", "focal_class": null, "focal_method": "pid_by_open_file", "tests": "import unittest\n\nclass Test_pid_by_open_file(unittest.TestCase):\n def test_pid_by_open_file(self):\n \"\"\"\n Checks the stem.util.system.pid_by_open_file function.\n \"\"\"\n tmpdir = tempfile.mkdtemp()\n self.assertEqual(None, stem.util.system.pid_by_open_file(tmpdir))\n os.rmdir(tmpdir)\n self.assertEqual(None, stem.util.system.pid_by_open_file(tmpdir))\n\n @patch('stem.util.system.call')\n @patch('stem.util.system.is_available', Mock(return_value=True))\n def test_pid_by_open_file_lsof(self, call_mock):\n \"\"\"\n Tests the pid_by_open_file function with a lsof response.\n \"\"\"\n lsof_query = system.GET_PID_BY_FILE_LSOF % '/tmp/foo'\n call_mock.side_effect = mock_call(lsof_query, ['4762'])\n self.assertEqual(4762, system.pid_by_open_file('/tmp/foo'))\n call_mock.return_value = []\n call_mock.side_effect = None\n self.assertEqual(None, system.pid_by_open_file('/tmp/somewhere_else'))\n", "method_code": "def pid_by_open_file(path):\n \"\"\"\n Attempts to determine the process id for a process with the given open file,\n using...\n\n ::\n\n lsof -w \n\n :param str path: location of the socket file to query against\n\n :returns: **int** with the process id, **None** if it can't be determined\n \"\"\"\n if is_available('lsof'):\n results = call(GET_PID_BY_FILE_LSOF % path, [])\n if len(results) == 1:\n pid = results[0].strip()\n if pid.isdigit():\n return int(pid)\n return None", "context": "def pid_by_open_file(path): ...\ndef is_windows(): ...\ndef is_mac(): ...\ndef is_gentoo(): ...\ndef is_slackware(): ...\ndef is_bsd(): ...\ndef is_available(command, cached=True): ...\ndef is_running(command): ...\ndef size_of(obj, exclude=None): ...\ndef name_by_pid(pid): ...\ndef pid_by_name(process_name, multiple=False): ...\ndef pid_by_port(port): ...\ndef pid_by_open_file(path): ...\ndef pids_by_user(user): ...\ndef cwd(pid): ...\ndef user(pid): ...\ndef start_time(pid): ...\ndef tail(target, lines=None): ...\ndef bsd_jail_id(pid): ...\ndef bsd_jail_path(jid): ...\ndef is_tarfile(path): ...\ndef expand_path(path, cwd=None): ...\ndef files_with_suffix(base_path, suffix): ...\ndef call(command, default=UNDEFINED, ignore_exit_status=False, timeout=None, cwd=None, env=None): ...\ndef get_process_name(): ...\ndef set_process_name(process_name): ...\ndef _set_argv(process_name): ...\ndef _set_prctl_name(process_name): ...\ndef _set_proc_title(process_name): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_pid_by_open_file", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000977.py"} {"focal_file": "stem/util/system.py", "focal_class": null, "focal_method": "pids_by_user", "tests": "import unittest\n\nclass Test_pids_by_user(unittest.TestCase):\n @require_path\n def test_pids_by_user(self):\n \"\"\"\n Checks the stem.util.system.pids_by_user function.\n \"\"\"\n pids = stem.util.system.pids_by_user(getpass.getuser())\n self.assertTrue(os.getpid() in pids)\n", "method_code": "def pids_by_user(user):\n \"\"\"\n Provides processes owned by a given user.\n\n .. versionadded:: 1.5.0\n\n :param str user: user to look up processes for\n\n :returns: **list** with the process ids, **None** if it can't be determined\n \"\"\"\n if is_available('ps'):\n if is_bsd():\n results = call(GET_PIDS_BY_USER_BSD % user, None)\n else:\n results = call(GET_PIDS_BY_USER_LINUX % user, None)\n if results:\n try:\n return list(map(int, results[1:]))\n except ValueError:\n pass\n return None", "context": "def pids_by_user(user): ...\ndef is_windows(): ...\ndef is_mac(): ...\ndef is_gentoo(): ...\ndef is_slackware(): ...\ndef is_bsd(): ...\ndef is_available(command, cached=True): ...\ndef is_running(command): ...\ndef size_of(obj, exclude=None): ...\ndef name_by_pid(pid): ...\ndef pid_by_name(process_name, multiple=False): ...\ndef pid_by_port(port): ...\ndef pid_by_open_file(path): ...\ndef pids_by_user(user): ...\ndef cwd(pid): ...\ndef user(pid): ...\ndef start_time(pid): ...\ndef tail(target, lines=None): ...\ndef bsd_jail_id(pid): ...\ndef bsd_jail_path(jid): ...\ndef is_tarfile(path): ...\ndef expand_path(path, cwd=None): ...\ndef files_with_suffix(base_path, suffix): ...\ndef call(command, default=UNDEFINED, ignore_exit_status=False, timeout=None, cwd=None, env=None): ...\ndef get_process_name(): ...\ndef set_process_name(process_name): ...\ndef _set_argv(process_name): ...\ndef _set_prctl_name(process_name): ...\ndef _set_proc_title(process_name): ...\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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, 1, 0, 0], "pynose_source_file": "test_000978.py"} {"focal_file": "stem/util/system.py", "focal_class": null, "focal_method": "cwd", "tests": "import unittest\n\nclass Test_cwd(unittest.TestCase):\n @test.require.ptrace\n def test_cwd(self):\n \"\"\"\n Checks general usage of the stem.util.system.cwd function.\n \"\"\"\n if stem.util.system.is_windows():\n self.skipTest('(unavailable on windows)')\n return\n runner = test.runner.get_runner()\n runner_pid, tor_cwd = (runner.get_pid(), runner.get_tor_cwd())\n self.assertEqual(tor_cwd, stem.util.system.cwd(runner_pid))\n self.assertEqual(None, stem.util.system.cwd(99999))\n", "method_code": "def cwd(pid):\n \"\"\"\n Provides the working directory of the given process.\n\n :param int pid: process id of the process to be queried\n\n :returns: **str** with the absolute path for the process' present working\n directory, **None** if it can't be determined\n \"\"\"\n if stem.util.proc.is_available():\n try:\n return stem.util.proc.cwd(pid)\n except IOError:\n pass\n logging_prefix = 'cwd(%s):' % pid\n if is_available('pwdx'):\n results = call(GET_CWD_PWDX % pid, None)\n if not results:\n log.debug(\"%s pwdx didn't return any results\" % logging_prefix)\n elif results[0].endswith('No such process'):\n log.debug('%s pwdx processes reported for this pid' % logging_prefix)\n elif len(results) != 1 or results[0].count(' ') != 1 or (not results[0].startswith('%s: ' % pid)):\n log.debug('%s we got unexpected output from pwdx: %s' % (logging_prefix, results))\n else:\n return results[0].split(' ', 1)[1].strip()\n if is_available('lsof'):\n results = call(GET_CWD_LSOF % pid, [])\n if len(results) >= 2 and results[-1].startswith('n/'):\n lsof_result = results[-1][1:].strip()\n if ' ' not in lsof_result:\n return lsof_result\n else:\n log.debug('%s we got unexpected output from lsof: %s' % (logging_prefix, results))\n return None", "context": "def cwd(pid): ...\ndef is_windows(): ...\ndef is_mac(): ...\ndef is_gentoo(): ...\ndef is_slackware(): ...\ndef is_bsd(): ...\ndef is_available(command, cached=True): ...\ndef is_running(command): ...\ndef size_of(obj, exclude=None): ...\ndef name_by_pid(pid): ...\ndef pid_by_name(process_name, multiple=False): ...\ndef pid_by_port(port): ...\ndef pid_by_open_file(path): ...\ndef pids_by_user(user): ...\ndef cwd(pid): ...\ndef user(pid): ...\ndef start_time(pid): ...\ndef tail(target, lines=None): ...\ndef bsd_jail_id(pid): ...\ndef bsd_jail_path(jid): ...\ndef is_tarfile(path): ...\ndef expand_path(path, cwd=None): ...\ndef files_with_suffix(base_path, suffix): ...\ndef call(command, default=UNDEFINED, ignore_exit_status=False, timeout=None, cwd=None, env=None): ...\ndef get_process_name(): ...\ndef set_process_name(process_name): ...\ndef _set_argv(process_name): ...\ndef _set_prctl_name(process_name): ...\ndef _set_proc_title(process_name): ...\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000979.py"} {"focal_file": "stem/util/system.py", "focal_class": null, "focal_method": "start_time", "tests": "import unittest\n\nclass Test_start_time(unittest.TestCase):\n def test_start_time_none(self):\n \"\"\"\n Tests the start_time function when the process doesn't exist.\n \"\"\"\n self.assertEqual(None, stem.util.system.start_time(None))\n self.assertEqual(None, stem.util.system.start_time(-5))\n self.assertEqual(None, stem.util.system.start_time(98765))\n\n @test.require.proc\n def test_start_time_proc(self):\n \"\"\"\n Tests the start_time function with a proc response.\n \"\"\"\n call_replacement = filter_system_call(['ps '])\n with patch('stem.util.system.call') as call_mock:\n call_mock.side_effect = call_replacement\n pid = test.runner.get_runner().get_pid()\n self.assertTrue(stem.util.system.start_time(pid) >= 0)\n\n @test.require.command('ps')\n @patch('stem.util.proc.is_available', Mock(return_value=False))\n def test_start_time_ps(self):\n \"\"\"\n Tests the start_time function with a ps response.\n \"\"\"\n pid = test.runner.get_runner().get_pid()\n self.assertTrue(stem.util.system.start_time(pid) >= 0)\n", "method_code": "def start_time(pid):\n \"\"\"\n Provides the unix timestamp when the given process started.\n\n :param int pid: process id of the process to be queried\n\n :returns: **float** for the unix timestamp when the process began, **None**\n if it can't be determined\n \"\"\"\n if not isinstance(pid, int) or pid < 0:\n return None\n if stem.util.proc.is_available():\n try:\n return float(stem.util.proc.stats(pid, stem.util.proc.Stat.START_TIME)[0])\n except IOError:\n pass\n try:\n ps_results = call('ps -p %s -o etime' % pid, [])\n if len(ps_results) >= 2:\n etime = ps_results[1].strip()\n return time.time() - stem.util.str_tools.parse_short_time_label(etime)\n except:\n pass\n return None", "context": "def start_time(pid): ...\ndef is_windows(): ...\ndef is_mac(): ...\ndef is_gentoo(): ...\ndef is_slackware(): ...\ndef is_bsd(): ...\ndef is_available(command, cached=True): ...\ndef is_running(command): ...\ndef size_of(obj, exclude=None): ...\ndef name_by_pid(pid): ...\ndef pid_by_name(process_name, multiple=False): ...\ndef pid_by_port(port): ...\ndef pid_by_open_file(path): ...\ndef pids_by_user(user): ...\ndef cwd(pid): ...\ndef user(pid): ...\ndef start_time(pid): ...\ndef tail(target, lines=None): ...\ndef bsd_jail_id(pid): ...\ndef bsd_jail_path(jid): ...\ndef is_tarfile(path): ...\ndef expand_path(path, cwd=None): ...\ndef files_with_suffix(base_path, suffix): ...\ndef call(command, default=UNDEFINED, ignore_exit_status=False, timeout=None, cwd=None, env=None): ...\ndef get_process_name(): ...\ndef set_process_name(process_name): ...\ndef _set_argv(process_name): ...\ndef _set_prctl_name(process_name): ...\ndef _set_proc_title(process_name): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_start_time_none", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000980.py"} {"focal_file": "stem/util/system.py", "focal_class": null, "focal_method": "bsd_jail_id", "tests": "import unittest\n\nclass Test_bsd_jail_id(unittest.TestCase):\n def test_bsd_jail_id(self):\n \"\"\"\n Exercises the stem.util.system.bsd_jail_id function, running through\n the failure case (since I'm not on BSD I can't really test this function\n properly).\n \"\"\"\n self.assertEqual(0, stem.util.system.bsd_jail_id(99999))\n\n @patch('stem.util.system.call')\n @patch('stem.util.system.is_available', Mock(return_value=True))\n def test_bsd_jail_id(self, call_mock):\n \"\"\"\n Tests the bsd_jail_id function.\n \"\"\"\n responses = {'1111': ['JID', ' 1'], '2222': ['JID', ' 0'], '3333': ['JID', 'bad data'], '4444': ['bad data'], '5555': [], '6666': []}\n call_mock.side_effect = mock_call(system.GET_BSD_JAIL_ID_PS, responses)\n for test_input in responses:\n expected_response = 1 if test_input == '1111' else 0\n self.assertEqual(expected_response, system.bsd_jail_id(test_input))\n", "method_code": "def bsd_jail_id(pid):\n \"\"\"\n Gets the jail id for a process. These seem to only exist for FreeBSD (this\n style for jails does not exist on Linux, OSX, or OpenBSD).\n\n :param int pid: process id of the jail id to be queried\n\n :returns: **int** for the jail id, zero if this can't be determined\n \"\"\"\n ps_output = call(GET_BSD_JAIL_ID_PS % pid, [])\n if len(ps_output) == 2 and len(ps_output[1].split()) == 1:\n jid = ps_output[1].strip()\n if jid.isdigit():\n return int(jid)\n os_name = platform.system()\n if os_name == 'FreeBSD':\n log.warn('Unable to get the jail id for process %s.' % pid)\n else:\n log.debug('bsd_jail_id(%s): jail ids do not exist on %s' % (pid, os_name))\n return 0", "context": "def bsd_jail_id(pid): ...\ndef is_windows(): ...\ndef is_mac(): ...\ndef is_gentoo(): ...\ndef is_slackware(): ...\ndef is_bsd(): ...\ndef is_available(command, cached=True): ...\ndef is_running(command): ...\ndef size_of(obj, exclude=None): ...\ndef name_by_pid(pid): ...\ndef pid_by_name(process_name, multiple=False): ...\ndef pid_by_port(port): ...\ndef pid_by_open_file(path): ...\ndef pids_by_user(user): ...\ndef cwd(pid): ...\ndef user(pid): ...\ndef start_time(pid): ...\ndef tail(target, lines=None): ...\ndef bsd_jail_id(pid): ...\ndef bsd_jail_path(jid): ...\ndef is_tarfile(path): ...\ndef expand_path(path, cwd=None): ...\ndef files_with_suffix(base_path, suffix): ...\ndef call(command, default=UNDEFINED, ignore_exit_status=False, timeout=None, cwd=None, env=None): ...\ndef get_process_name(): ...\ndef set_process_name(process_name): ...\ndef _set_argv(process_name): ...\ndef _set_prctl_name(process_name): ...\ndef _set_proc_title(process_name): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_bsd_jail_id", "smells": [1, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000981.py"} {"focal_file": "stem/util/system.py", "focal_class": null, "focal_method": "expand_path", "tests": "import unittest\n\nclass Test_expand_path(unittest.TestCase):\n def test_expand_path(self):\n \"\"\"\n Exercises the expand_path() method with actual runtime data.\n \"\"\"\n if getpass.getuser() == 'root':\n self.skipTest('(running as root)')\n return\n self.assertEqual(os.getcwd(), stem.util.system.expand_path('.'))\n self.assertEqual(os.getcwd(), stem.util.system.expand_path('./'))\n self.assertEqual(os.path.join(os.getcwd(), 'foo'), stem.util.system.expand_path('./foo'))\n home_dir, username = (os.path.expanduser('~'), getpass.getuser())\n self.assertEqual(home_dir, stem.util.system.expand_path('~'))\n self.assertEqual(home_dir, stem.util.system.expand_path('~/'))\n self.assertEqual(home_dir, stem.util.system.expand_path('~%s' % username))\n self.assertEqual(os.path.join(home_dir, 'foo'), stem.util.system.expand_path('~%s/foo' % username))\n\n @patch('platform.system', Mock(return_value='Linux'))\n @patch('os.path.join', Mock(side_effect=posixpath.join))\n def test_expand_path_unix(self):\n \"\"\"\n Tests the expand_path function. This does not exercise home directory\n expansions since that deals with our environment (that's left to integ\n tests).\n \"\"\"\n self.assertEqual('', system.expand_path(''))\n self.assertEqual('/tmp', system.expand_path('/tmp'))\n self.assertEqual('/tmp', system.expand_path('/tmp/'))\n self.assertEqual('/tmp', system.expand_path('.', '/tmp'))\n self.assertEqual('/tmp', system.expand_path('./', '/tmp'))\n self.assertEqual('/tmp/foo', system.expand_path('foo', '/tmp'))\n self.assertEqual('/tmp/foo', system.expand_path('./foo', '/tmp'))\n\n @patch('platform.system', Mock(return_value='Windows'))\n @patch('os.path.join', Mock(side_effect=ntpath.join))\n def test_expand_path_windows(self):\n \"\"\"\n Tests the expand_path function on windows. This does not exercise\n home directory expansions since that deals with our environment\n (that's left to integ tests).\n \"\"\"\n self.assertEqual('', system.expand_path(''))\n self.assertEqual('C:\\\\tmp', system.expand_path('C:\\\\tmp'))\n self.assertEqual('C:\\\\tmp', system.expand_path('C:\\\\tmp\\\\'))\n self.assertEqual('C:\\\\tmp', system.expand_path('.', 'C:\\\\tmp'))\n self.assertEqual('C:\\\\tmp', system.expand_path('.\\\\', 'C:\\\\tmp'))\n self.assertEqual('C:\\\\tmp\\\\foo', system.expand_path('foo', 'C:\\\\tmp'))\n self.assertEqual('C:\\\\tmp\\\\foo', system.expand_path('.\\\\foo', 'C:\\\\tmp'))\n", "method_code": "def expand_path(path, cwd=None):\n \"\"\"\n Provides an absolute path, expanding tildes with the user's home and\n appending a current working directory if the path was relative.\n\n :param str path: path to be expanded\n :param str cwd: current working directory to expand relative paths with, our\n process' if this is **None**\n\n :returns: **str** of the path expanded to be an absolute path, never with an\n ending slash\n \"\"\"\n if is_windows():\n relative_path = path.replace('/', '\\\\').rstrip('\\\\')\n else:\n relative_path = path.rstrip('/')\n if not relative_path or os.path.isabs(relative_path):\n pass\n elif relative_path.startswith('~'):\n relative_path = os.path.expanduser(relative_path)\n else:\n if not cwd:\n cwd = os.getcwd()\n if relative_path.startswith('./') or relative_path.startswith('.\\\\'):\n relative_path = relative_path[2:]\n elif relative_path == '.':\n relative_path = ''\n if relative_path == '':\n relative_path = cwd\n else:\n relative_path = os.path.join(cwd, relative_path)\n return relative_path", "context": "def expand_path(path, cwd=None): ...\ndef is_windows(): ...\ndef is_mac(): ...\ndef is_gentoo(): ...\ndef is_slackware(): ...\ndef is_bsd(): ...\ndef is_available(command, cached=True): ...\ndef is_running(command): ...\ndef size_of(obj, exclude=None): ...\ndef name_by_pid(pid): ...\ndef pid_by_name(process_name, multiple=False): ...\ndef pid_by_port(port): ...\ndef pid_by_open_file(path): ...\ndef pids_by_user(user): ...\ndef cwd(pid): ...\ndef user(pid): ...\ndef start_time(pid): ...\ndef tail(target, lines=None): ...\ndef bsd_jail_id(pid): ...\ndef bsd_jail_path(jid): ...\ndef is_tarfile(path): ...\ndef expand_path(path, cwd=None): ...\ndef files_with_suffix(base_path, suffix): ...\ndef call(command, default=UNDEFINED, ignore_exit_status=False, timeout=None, cwd=None, env=None): ...\ndef get_process_name(): ...\ndef set_process_name(process_name): ...\ndef _set_argv(process_name): ...\ndef _set_prctl_name(process_name): ...\ndef _set_proc_title(process_name): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_expand_path", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000982.py"} {"focal_file": "stem/util/system.py", "focal_class": null, "focal_method": "set_process_name", "tests": "import unittest\n\nclass Test_set_process_name(unittest.TestCase):\n def test_set_process_name(self):\n \"\"\"\n Exercises the get_process_name() and set_process_name() methods.\n \"\"\"\n if stem.prereq.is_pypy():\n self.skipTest('(unimplemented for pypy)')\n return\n initial_name = stem.util.system.get_process_name()\n self.assertTrue('run_tests.py' in initial_name)\n try:\n stem.util.system.set_process_name('stem_integ')\n self.assertEqual('stem_integ', stem.util.system.get_process_name())\n finally:\n stem.util.system.set_process_name(initial_name)\n", "method_code": "def set_process_name(process_name):\n \"\"\"\n Renames our current process from \"python \" to a custom name. This is\n best-effort, not necessarily working on all platforms.\n\n :param str process_name: new name for our process\n\n :raises: **IOError** if the process cannot be renamed\n \"\"\"\n _set_argv(process_name)\n if platform.system() == 'Linux':\n _set_prctl_name(process_name)\n elif platform.system() in ('Darwin', 'FreeBSD', 'OpenBSD'):\n _set_proc_title(process_name)", "context": "def set_process_name(process_name): ...\ndef is_windows(): ...\ndef is_mac(): ...\ndef is_gentoo(): ...\ndef is_slackware(): ...\ndef is_bsd(): ...\ndef is_available(command, cached=True): ...\ndef is_running(command): ...\ndef size_of(obj, exclude=None): ...\ndef name_by_pid(pid): ...\ndef pid_by_name(process_name, multiple=False): ...\ndef pid_by_port(port): ...\ndef pid_by_open_file(path): ...\ndef pids_by_user(user): ...\ndef cwd(pid): ...\ndef user(pid): ...\ndef start_time(pid): ...\ndef tail(target, lines=None): ...\ndef bsd_jail_id(pid): ...\ndef bsd_jail_path(jid): ...\ndef is_tarfile(path): ...\ndef expand_path(path, cwd=None): ...\ndef files_with_suffix(base_path, suffix): ...\ndef call(command, default=UNDEFINED, ignore_exit_status=False, timeout=None, cwd=None, env=None): ...\ndef get_process_name(): ...\ndef set_process_name(process_name): ...\ndef _set_argv(process_name): ...\ndef _set_prctl_name(process_name): ...\ndef _set_proc_title(process_name): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_set_process_name", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000983.py"} {"focal_file": "stem/util/conf.py", "focal_class": null, "focal_method": "load", "tests": "import unittest\n\nclass Test_load(unittest.TestCase):\n def test_load_multiline(self):\n \"\"\"\n Tests the load method with multi-line configuration files.\n \"\"\"\n test_config_path = _make_config(MULTILINE_CONF)\n test_config = stem.util.conf.get_config('integ_testing')\n test_config.load(test_config_path)\n for entry in ('simple', 'leading_whitespace', 'squashed_top', 'squashed_bottom'):\n self.assertEqual('la de da\\nand a ho hum', test_config.get('multiline.entry.%s' % entry))\n self.assertEqual('', test_config.get('multiline.entry.empty'))\n", "method_code": " def load(self, path=None, commenting=True):\n \"\"\"\n Reads in the contents of the given path, adding its configuration values\n to our current contents. If the path is a directory then this loads each\n of the files, recursively.\n \n .. versionchanged:: 1.3.0\n Added support for directories.\n \n .. versionchanged:: 1.3.0\n Added the **commenting** argument.\n \n .. versionchanged:: 1.6.0\n Avoid loading vim swap files.\n \n :param str path: file or directory path to be loaded, this uses the last\n loaded path if not provided\n :param bool commenting: ignore line content after a '#' if **True**, read\n otherwise\n \n :raises:\n * **IOError** if we fail to read the file (it doesn't exist, insufficient\n permissions, etc)\n * **ValueError** if no path was provided and we've never been provided one\n \"\"\"\n if path:\n self._path = path\n elif not self._path:\n raise ValueError('Unable to load configuration: no path provided')\n if os.path.isdir(self._path):\n for root, dirnames, filenames in os.walk(self._path):\n for filename in filenames:\n if filename.endswith('.swp'):\n continue\n self.load(os.path.join(root, filename))\n return\n with open(self._path, 'r') as config_file:\n read_contents = config_file.readlines()\n with self._contents_lock:\n while read_contents:\n line = read_contents.pop(0)\n comment_start = line.find('#') if commenting else -1\n if comment_start != -1:\n line = line[:comment_start]\n line = line.strip()\n if line:\n if ' ' in line:\n key, value = line.split(' ', 1)\n self.set(key, value.strip(), False)\n else:\n multiline_buffer = []\n while read_contents and read_contents[0].lstrip().startswith('|'):\n content = read_contents.pop(0).lstrip()[1:]\n content = content.rstrip('\\n')\n multiline_buffer.append(content)\n if multiline_buffer:\n self.set(line, '\\n'.join(multiline_buffer), False)\n else:\n self.set(line, '', False)\n ", "context": "class Config(object):\n def load(self, path=None, commenting=True): ...\n def __init__(self): ...\n def save(self, path=None): ...\n def clear(self): ...\n def add_listener(self, listener, backfill=True): ...\n def clear_listeners(self): ...\n def keys(self): ...\n def unused_keys(self): ...\n def set(self, key, value, overwrite=True): ...\n def get(self, key, default=None): ...\n def get_value(self, key, default=None, multiple=False): ...\n def __getitem__(self, key): ...\n\n self._path = None\n self._contents = OrderedDict()\n self._listeners = []\n self._contents_lock = threading.RLock()\n self._requested_keys = set()\n self._settings_loaded = False\n", "repository": "illumineinteractive/stem", "test_name": "test_load_multiline", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000984.py"} {"focal_file": "stem/util/conf.py", "focal_class": null, "focal_method": "save", "tests": "import unittest\n\nclass Test_save(unittest.TestCase):\n def test_save(self):\n \"\"\"\n Saves then reloads a configuration with several types of values.\n \"\"\"\n test_config = stem.util.conf.get_config('integ_testing')\n test_config.set('single_value', \"yup, I'm there\")\n test_config.set('multiple_values', 'a', False)\n test_config.set('multiple_values', 'b', False)\n test_config.set('multiple_values', 'c', False)\n test_config.set('multiline_value', HERALD_POEM)\n test_config.save(_get_test_config_path())\n test_config.clear()\n test_config.load()\n self.assertEqual(\"yup, I'm there\", test_config.get_value('single_value'))\n self.assertEqual(['a', 'b', 'c'], test_config.get_value('multiple_values', multiple=True))\n self.assertEqual(HERALD_POEM, test_config.get_value('multiline_value'))\n", "method_code": " def save(self, path=None):\n \"\"\"\n Saves configuration contents to disk. If a path is provided then it\n replaces the configuration location that we track.\n \n :param str path: location to be saved to\n \n :raises:\n * **IOError** if we fail to save the file (insufficient permissions, etc)\n * **ValueError** if no path was provided and we've never been provided one\n \"\"\"\n if path:\n self._path = path\n elif not self._path:\n raise ValueError('Unable to save configuration: no path provided')\n with self._contents_lock:\n if not os.path.exists(os.path.dirname(self._path)):\n os.makedirs(os.path.dirname(self._path))\n with open(self._path, 'w') as output_file:\n for entry_key in self.keys():\n for entry_value in self.get_value(entry_key, multiple=True):\n if '\\n' in entry_value:\n entry_value = '\\n|' + entry_value.replace('\\n', '\\n|')\n output_file.write('%s %s\\n' % (entry_key, entry_value))\n ", "context": "class Config(object):\n def save(self, path=None): ...\n def __init__(self): ...\n def load(self, path=None, commenting=True): ...\n def clear(self): ...\n def add_listener(self, listener, backfill=True): ...\n def clear_listeners(self): ...\n def keys(self): ...\n def unused_keys(self): ...\n def set(self, key, value, overwrite=True): ...\n def get(self, key, default=None): ...\n def get_value(self, key, default=None, multiple=False): ...\n def __getitem__(self, key): ...\n\n self._path = None\n self._contents = OrderedDict()\n self._listeners = []\n self._contents_lock = threading.RLock()\n self._requested_keys = set()\n self._settings_loaded = False\n", "repository": "illumineinteractive/stem", "test_name": "test_save", "smells": [1, 0, 0, 0, 1, 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": [1, 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": "stem/util/proc.py", "focal_class": null, "focal_method": "cwd", "tests": "import unittest\n\nclass Test_cwd(unittest.TestCase):\n @test.require.proc\n @test.require.ptrace\n def test_cwd(self):\n \"\"\"\n Checks that stem.util.proc.cwd matches our tor instance's cwd.\n \"\"\"\n runner = test.runner.get_runner()\n runner_pid, tor_cwd = (runner.get_pid(), runner.get_tor_cwd())\n self.assertEqual(tor_cwd, proc.cwd(runner_pid))\n\n @patch('os.readlink')\n def test_cwd(self, readlink_mock):\n \"\"\"\n Tests the cwd function with a given pid.\n \"\"\"\n readlink_mock.side_effect = lambda param: {'/proc/24019/cwd': '/home/directory/TEST'}[param]\n self.assertEqual('/home/directory/TEST', proc.cwd(24019))\n", "method_code": "def cwd(pid):\n \"\"\"\n Provides the current working directory for the given process.\n\n :param int pid: process id of the process to be queried\n\n :returns: **str** with the path of the working directory for the process\n\n :raises: **IOError** if it can't be determined\n \"\"\"\n start_time, parameter = (time.time(), 'cwd')\n proc_cwd_link = '/proc/%s/cwd' % pid\n if pid == 0:\n cwd = ''\n else:\n try:\n cwd = os.readlink(proc_cwd_link)\n except OSError:\n exc = IOError('unable to read %s' % proc_cwd_link)\n _log_failure(parameter, exc)\n raise exc\n _log_runtime(parameter, proc_cwd_link, start_time)\n return cwd", "context": "def cwd(pid): ...\ndef is_available(): ...\ndef system_start_time(): ...\ndef physical_memory(): ...\ndef cwd(pid): ...\ndef uid(pid): ...\ndef memory_usage(pid): ...\ndef stats(pid, *stat_types): ...\ndef file_descriptors_used(pid): ...\ndef connections(pid=None, user=None): ...\ndef _inodes_for_sockets(pid): ...\ndef _unpack_addr(addr): ...\ndef _is_float(*value): ...\ndef _get_line(file_path, line_prefix, parameter): ...\ndef _get_lines(file_path, line_prefixes, parameter): ...\ndef _log_runtime(parameter, proc_location, start_time): ...\ndef _log_failure(parameter, exc): ...\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000986.py"} {"focal_file": "stem/util/proc.py", "focal_class": null, "focal_method": "uid", "tests": "import unittest\n\nclass Test_uid(unittest.TestCase):\n @test.require.proc\n def test_uid(self):\n \"\"\"\n Checks that stem.util.proc.uid matches our tor instance's uid.\n \"\"\"\n tor_pid = test.runner.get_runner().get_pid()\n self.assertEqual(os.geteuid(), proc.uid(tor_pid))\n\n @patch('stem.util.proc._get_line')\n def test_uid(self, get_line_mock):\n \"\"\"\n Tests the uid function with a given pid.\n \"\"\"\n for test_value in [(24019, 11111), (0, 22222)]:\n pid, uid = test_value\n get_line_mock.side_effect = lambda *params: {('/proc/%s/status' % pid, 'Uid:', 'uid'): 'Uid: %s' % uid}[params]\n self.assertEqual(uid, proc.uid(pid))\n", "method_code": "def uid(pid):\n \"\"\"\n Provides the user ID the given process is running under.\n\n :param int pid: process id of the process to be queried\n\n :returns: **int** with the user id for the owner of the process\n\n :raises: **IOError** if it can't be determined\n \"\"\"\n start_time, parameter = (time.time(), 'uid')\n status_path = '/proc/%s/status' % pid\n uid_line = _get_line(status_path, 'Uid:', parameter)\n try:\n result = int(uid_line.split()[1])\n _log_runtime(parameter, '%s[Uid]' % status_path, start_time)\n return result\n except:\n exc = IOError('unable to parse the %s Uid entry: %s' % (status_path, uid_line))\n _log_failure(parameter, exc)\n raise exc", "context": "def uid(pid): ...\ndef is_available(): ...\ndef system_start_time(): ...\ndef physical_memory(): ...\ndef cwd(pid): ...\ndef uid(pid): ...\ndef memory_usage(pid): ...\ndef stats(pid, *stat_types): ...\ndef file_descriptors_used(pid): ...\ndef connections(pid=None, user=None): ...\ndef _inodes_for_sockets(pid): ...\ndef _unpack_addr(addr): ...\ndef _is_float(*value): ...\ndef _get_line(file_path, line_prefix, parameter): ...\ndef _get_lines(file_path, line_prefixes, parameter): ...\ndef _log_runtime(parameter, proc_location, start_time): ...\ndef _log_failure(parameter, exc): ...\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000987.py"} {"focal_file": "stem/util/proc.py", "focal_class": null, "focal_method": "memory_usage", "tests": "import unittest\n\nclass Test_memory_usage(unittest.TestCase):\n @test.require.proc\n def test_memory_usage(self):\n \"\"\"\n Checks that stem.util.proc.memory_usage looks somewhat reasonable.\n \"\"\"\n tor_pid = test.runner.get_runner().get_pid()\n res_size, vir_size = proc.memory_usage(tor_pid)\n self.assertTrue(res_size > 1024)\n self.assertTrue(vir_size > 1024)\n\n @patch('stem.util.proc._get_lines')\n def test_memory_usage(self, get_lines_mock):\n \"\"\"\n Tests the memory_usage function with a given pid.\n \"\"\"\n get_lines_mock.side_effect = lambda *params: {('/proc/1111/status', ('VmRSS:', 'VmSize:'), 'memory usage'): {'VmRSS:': 'VmRSS: 100 kB', 'VmSize:': 'VmSize: 1800 kB'}}[params]\n self.assertEqual((0, 0), proc.memory_usage(0))\n self.assertEqual((100 * 1024, 1800 * 1024), proc.memory_usage(1111))\n", "method_code": "def memory_usage(pid):\n \"\"\"\n Provides the memory usage in bytes for the given process.\n\n :param int pid: process id of the process to be queried\n\n :returns: **tuple** of two ints with the memory usage of the process, of the\n form **(resident_size, virtual_size)**\n\n :raises: **IOError** if it can't be determined\n \"\"\"\n if pid == 0:\n return (0, 0)\n start_time, parameter = (time.time(), 'memory usage')\n status_path = '/proc/%s/status' % pid\n mem_lines = _get_lines(status_path, ('VmRSS:', 'VmSize:'), parameter)\n try:\n residentSize = int(mem_lines['VmRSS:'].split()[1]) * 1024\n virtualSize = int(mem_lines['VmSize:'].split()[1]) * 1024\n _log_runtime(parameter, '%s[VmRSS|VmSize]' % status_path, start_time)\n return (residentSize, virtualSize)\n except:\n exc = IOError('unable to parse the %s VmRSS and VmSize entries: %s' % (status_path, ', '.join(mem_lines)))\n _log_failure(parameter, exc)\n raise exc", "context": "def memory_usage(pid): ...\ndef is_available(): ...\ndef system_start_time(): ...\ndef physical_memory(): ...\ndef cwd(pid): ...\ndef uid(pid): ...\ndef memory_usage(pid): ...\ndef stats(pid, *stat_types): ...\ndef file_descriptors_used(pid): ...\ndef connections(pid=None, user=None): ...\ndef _inodes_for_sockets(pid): ...\ndef _unpack_addr(addr): ...\ndef _is_float(*value): ...\ndef _get_line(file_path, line_prefix, parameter): ...\ndef _get_lines(file_path, line_prefixes, parameter): ...\ndef _log_runtime(parameter, proc_location, start_time): ...\ndef _log_failure(parameter, exc): ...\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000988.py"} {"focal_file": "stem/util/proc.py", "focal_class": null, "focal_method": "stats", "tests": "import unittest\n\nclass Test_stats(unittest.TestCase):\n @test.require.proc\n def test_stats(self):\n \"\"\"\n Checks that stem.util.proc.stats looks somewhat reasonable.\n \"\"\"\n tor_cmd = test.runner.get_runner().get_tor_command(True)\n tor_pid = test.runner.get_runner().get_pid()\n command, utime, stime, start_time = proc.stats(tor_pid, 'command', 'utime', 'stime', 'start time')\n self.assertEqual(tor_cmd, command)\n self.assertTrue(float(utime) > 0)\n self.assertTrue(float(stime) >= 0)\n self.assertTrue(float(start_time) > proc.system_start_time())\n\n @patch('stem.util.proc._get_line')\n @patch('stem.util.proc.system_start_time', Mock(return_value=10))\n @patch('stem.util.proc.CLOCK_TICKS', 100)\n def test_stats(self, get_line_mock):\n \"\"\"\n Tests stats() with all combinations of stat_type arguments.\n \"\"\"\n stat_combinations = test.get_all_combinations([('command', 'test_program'), ('utime', '0.13'), ('stime', '0.14'), ('start time', '10.21')])\n stat_path = '/proc/24062/stat'\n stat = '1 (test_program) 2 3 4 5 6 7 8 9 10 11 12 13.0 14.0 15 16 17 18 19 20 21.0 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43'\n get_line_mock.side_effect = lambda *params: {(stat_path, '24062', 'process '): stat}[params]\n self.assertEqual((), proc.stats(24062))\n for stats in stat_combinations:\n args, response = list(zip(*stats))\n get_line_mock.side_effect = lambda *params: {(stat_path, '24062', 'process %s' % ', '.join(args)): stat}[params]\n self.assertEqual(response, proc.stats(24062, *args))\n if 'start time' in args:\n response = 10\n else:\n response = ()\n for arg in args:\n if arg == 'command':\n response += ('sched',)\n elif arg == 'utime':\n response += ('0',)\n elif arg == 'stime':\n response += ('0',)\n get_line_mock.side_effect = lambda *params: {('/proc/0/stat', '0', 'process %s' % ', '.join(args)): stat}[params]\n self.assertEqual(response, proc.stats(0, *args))\n", "method_code": "def stats(pid, *stat_types):\n \"\"\"\n Provides process specific information. See the :data:`~stem.util.proc.Stat`\n enum for valid options.\n\n :param int pid: process id of the process to be queried\n :param Stat stat_types: information to be provided back\n\n :returns: **tuple** with all of the requested statistics as strings\n\n :raises: **IOError** if it can't be determined\n \"\"\"\n if CLOCK_TICKS is None:\n raise IOError('Unable to look up SC_CLK_TCK')\n start_time, parameter = (time.time(), 'process %s' % ', '.join(stat_types))\n stat_path = '/proc/%s/stat' % pid\n stat_line = _get_line(stat_path, str(pid), parameter)\n stat_comp = []\n cmd_start, cmd_end = (stat_line.find('('), stat_line.find(')'))\n if cmd_start != -1 and cmd_end != -1:\n stat_comp.append(stat_line[:cmd_start])\n stat_comp.append(stat_line[cmd_start + 1:cmd_end])\n stat_comp += stat_line[cmd_end + 1:].split()\n if len(stat_comp) < 44 and _is_float(stat_comp[13], stat_comp[14], stat_comp[21]):\n exc = IOError('stat file had an unexpected format: %s' % stat_path)\n _log_failure(parameter, exc)\n raise exc\n results = []\n for stat_type in stat_types:\n if stat_type == Stat.COMMAND:\n if pid == 0:\n results.append('sched')\n else:\n results.append(stat_comp[1])\n elif stat_type == Stat.CPU_UTIME:\n if pid == 0:\n results.append('0')\n else:\n results.append(str(float(stat_comp[13]) / CLOCK_TICKS))\n elif stat_type == Stat.CPU_STIME:\n if pid == 0:\n results.append('0')\n else:\n results.append(str(float(stat_comp[14]) / CLOCK_TICKS))\n elif stat_type == Stat.START_TIME:\n if pid == 0:\n return system_start_time()\n else:\n p_start_time = float(stat_comp[21]) / CLOCK_TICKS\n results.append(str(p_start_time + system_start_time()))\n _log_runtime(parameter, stat_path, start_time)\n return tuple(results)", "context": "def stats(pid, *stat_types): ...\ndef is_available(): ...\ndef system_start_time(): ...\ndef physical_memory(): ...\ndef cwd(pid): ...\ndef uid(pid): ...\ndef memory_usage(pid): ...\ndef stats(pid, *stat_types): ...\ndef file_descriptors_used(pid): ...\ndef connections(pid=None, user=None): ...\ndef _inodes_for_sockets(pid): ...\ndef _unpack_addr(addr): ...\ndef _is_float(*value): ...\ndef _get_line(file_path, line_prefix, parameter): ...\ndef _get_lines(file_path, line_prefixes, parameter): ...\ndef _log_runtime(parameter, proc_location, start_time): ...\ndef _log_failure(parameter, exc): ...\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000989.py"} {"focal_file": "stem/util/proc.py", "focal_class": null, "focal_method": "connections", "tests": "import unittest\n\nclass Test_connections(unittest.TestCase):\n @test.require.proc\n @test.require.ptrace\n def test_connections(self):\n \"\"\"\n Checks for our control port in the stem.util.proc.connections output if\n we have one.\n \"\"\"\n runner = test.runner.get_runner()\n if test.runner.Torrc.PORT not in runner.get_options():\n self.skiTestp('(no control port)')\n return\n elif not os.access('/proc/net/tcp', os.R_OK) or not os.access('/proc/net/udp', os.R_OK):\n self.skipTest('(proc lacks read permissions)')\n return\n with runner.get_tor_socket():\n tor_pid = test.runner.get_runner().get_pid()\n for conn in proc.connections(tor_pid):\n if ('127.0.0.1', test.runner.CONTROL_PORT) == conn[:2]:\n return\n self.fail()\n\n @patch('os.listdir')\n @patch('os.path.exists')\n @patch('os.readlink')\n @patch('stem.util.proc.open', create=True)\n def test_connections(self, open_mock, readlink_mock, path_exists_mock, listdir_mock):\n \"\"\"\n Tests the connections function.\n \"\"\"\n pid = 1111\n listdir_mock.side_effect = lambda param: {'/proc/%s/fd' % pid: ['1', '2', '3', '4']}[param]\n readlink_mock.side_effect = lambda param: {'/proc/%s/fd/1' % pid: 'socket:[99999999]', '/proc/%s/fd/2' % pid: 'socket:[IIIIIIII]', '/proc/%s/fd/3' % pid: 'pipe:[30303]', '/proc/%s/fd/4' % pid: 'pipe:[40404]'}[param]\n tcp = TITLE_LINE + b'\\n 0: 11111111:1111 22222222:2222 01 44444444:44444444 55:55555555 66666666 1111 8 99999999'\n udp = TITLE_LINE + b'\\n A: BBBBBBBB:BBBB CCCCCCCC:CCCC DD EEEEEEEE:EEEEEEEE FF:FFFFFFFF GGGGGGGG 1111 H IIIIIIII'\n path_exists_mock.side_effect = lambda param: {'/proc/net/tcp6': False, '/proc/net/udp6': False}[param]\n open_mock.side_effect = lambda param, mode: {'/proc/net/tcp': io.BytesIO(tcp), '/proc/net/udp': io.BytesIO(udp)}[param]\n expected = [Connection('17.17.17.17', 4369, '34.34.34.34', 8738, 'tcp', False), Connection('187.187.187.187', 48059, '204.204.204.204', 52428, 'udp', False)]\n self.assertEqual(expected, proc.connections(pid))\n\n @patch('os.listdir')\n @patch('os.path.exists')\n @patch('os.readlink')\n @patch('stem.util.proc.open', create=True)\n def test_connections_ipv6(self, open_mock, readlink_mock, path_exists_mock, listdir_mock):\n \"\"\"\n Tests the connections function with ipv6 addresses.\n \"\"\"\n pid = 1111\n listdir_mock.side_effect = lambda param: {'/proc/%s/fd' % pid: ['1', '2']}[param]\n readlink_mock.side_effect = lambda param: {'/proc/%s/fd/1' % pid: 'socket:[42088802]', '/proc/%s/fd/2' % pid: 'socket:[41691357]'}[param]\n path_exists_mock.side_effect = lambda param: {'/proc/net/tcp6': True, '/proc/net/udp6': False}[param]\n open_mock.side_effect = lambda param, mode: {'/proc/net/tcp': io.BytesIO(TITLE_LINE), '/proc/net/tcp6': io.BytesIO(TCP6_CONTENT), '/proc/net/udp': io.BytesIO(TITLE_LINE)}[param]\n expected = [Connection('2a01:04f8:0190:514a:0000:0000:0000:0002', 443, '2001:0638:a000:4140:0000:0000:ffff:0189', 40435, 'tcp', True), Connection('2a01:04f8:0190:514a:0000:0000:0000:0002', 443, '2001:0858:0002:0002:aabb:0000:563b:1526', 44469, 'tcp', True)]\n self.assertEqual(expected, proc.connections(pid=pid))\n\n @patch('os.path.exists')\n @patch('pwd.getpwnam')\n @patch('stem.util.proc.open', create=True)\n def test_connections_ipv6_by_user(self, open_mock, getpwnam_mock, path_exists_mock):\n \"\"\"\n Tests the connections function with ipv6 addresses.\n \"\"\"\n getpwnam_mock('me').pw_uid = 106\n path_exists_mock.side_effect = lambda param: {'/proc/net/tcp6': True, '/proc/net/udp6': False}[param]\n open_mock.side_effect = lambda param, mode: {'/proc/net/tcp': io.BytesIO(TITLE_LINE), '/proc/net/tcp6': io.BytesIO(TCP6_CONTENT), '/proc/net/udp': io.BytesIO(TITLE_LINE)}[param]\n expected = [Connection('0000:0000:0000:0000:0000:ffff:0509:9e4b', 5222, '0000:0000:0000:0000:0000:ffff:4e36:8621', 38330, 'tcp', True), Connection('2a01:04f8:0190:514a:0000:0000:0000:0002', 5269, '2001:06f8:126f:0011:0000:0000:0000:0026', 50594, 'tcp', True), Connection('0000:0000:0000:0000:0000:ffff:0509:9e4b', 5222, '0000:0000:0000:0000:0000:ffff:4e36:8621', 38174, 'tcp', True)]\n self.assertEqual(expected, proc.connections(user='me'))\n\n @patch('os.listdir')\n @patch('os.path.exists')\n @patch('os.readlink')\n @patch('stem.util.proc.open', create=True)\n def test_high_connection_count(self, open_mock, readlink_mock, path_exists_mock, listdir_mock):\n \"\"\"\n When we have over ten thousand connections the 'SL' column's width changes.\n Checking that we account for this.\n \"\"\"\n pid = 1111\n listdir_mock.side_effect = lambda param: {'/proc/%s/fd' % pid: ['1', '2', '3', '4']}[param]\n readlink_mock.side_effect = lambda param: {'/proc/%s/fd/1' % pid: 'socket:[99999999]', '/proc/%s/fd/2' % pid: 'socket:[88888888]', '/proc/%s/fd/3' % pid: 'socket:[77777777]', '/proc/%s/fd/4' % pid: 'pipe:[30303]', '/proc/%s/fd/5' % pid: 'pipe:[40404]'}[param]\n path_exists_mock.side_effect = lambda param: {'/proc/net/tcp6': False, '/proc/net/udp6': False}[param]\n open_mock.side_effect = lambda param, mode: {'/proc/net/tcp': io.BytesIO(SL_WIDTH_CHANGE), '/proc/net/udp': io.BytesIO(TITLE_LINE)}[param]\n expected = [Connection('17.17.17.17', 4369, '51.34.34.34', 8772, 'tcp', False), Connection('34.34.34.34', 8738, '68.51.51.51', 13141, 'tcp', False), Connection('51.51.51.51', 13107, '85.68.68.68', 17510, 'tcp', False)]\n self.assertEqual(expected, proc.connections(pid))\n", "method_code": "def connections(pid=None, user=None):\n \"\"\"\n Queries connections from the proc contents. This matches netstat, lsof, and\n friends but is much faster. If no **pid** or **user** are provided this\n provides all present connections.\n\n :param int pid: pid to provide connections for\n :param str user: username to look up connections for\n\n :returns: **list** of :class:`~stem.util.connection.Connection` instances\n\n :raises: **IOError** if it can't be determined\n \"\"\"\n start_time, conn = (time.time(), [])\n if pid:\n parameter = 'connections for pid %s' % pid\n try:\n pid = int(pid)\n if pid < 0:\n raise IOError(\"Process pids can't be negative: %s\" % pid)\n except (ValueError, TypeError):\n raise IOError('Process pid was non-numeric: %s' % pid)\n elif user:\n parameter = 'connections for user %s' % user\n else:\n parameter = 'all connections'\n try:\n if not IS_PWD_AVAILABLE:\n raise IOError(\"This requires python's pwd module, which is unavailable on Windows.\")\n inodes = _inodes_for_sockets(pid) if pid else set()\n process_uid = stem.util.str_tools._to_bytes(str(pwd.getpwnam(user).pw_uid)) if user else None\n for proc_file_path in ('/proc/net/tcp', '/proc/net/tcp6', '/proc/net/udp', '/proc/net/udp6'):\n if proc_file_path.endswith('6') and (not os.path.exists(proc_file_path)):\n continue\n protocol = proc_file_path[10:].rstrip('6')\n is_ipv6 = proc_file_path.endswith('6')\n try:\n with open(proc_file_path, 'rb') as proc_file:\n proc_file.readline()\n for line in proc_file:\n _, l_dst, r_dst, status, _, _, _, uid, _, inode = line.split()[:10]\n if inodes and inode not in inodes:\n continue\n elif process_uid and uid != process_uid:\n continue\n elif protocol == 'tcp' and status != b'01':\n continue\n div = l_dst.find(b':')\n l_addr = _unpack_addr(l_dst[:div])\n l_port = int(l_dst[div + 1:], 16)\n div = r_dst.find(b':')\n r_addr = _unpack_addr(r_dst[:div])\n r_port = int(r_dst[div + 1:], 16)\n if r_addr == '0.0.0.0' or r_addr == '0000:0000:0000:0000:0000:0000':\n continue\n elif l_port == 0 or r_port == 0:\n continue\n conn.append(stem.util.connection.Connection(l_addr, l_port, r_addr, r_port, protocol, is_ipv6))\n except IOError as exc:\n raise IOError(\"unable to read '%s': %s\" % (proc_file_path, exc))\n except Exception as exc:\n raise IOError(\"unable to parse '%s': %s\" % (proc_file_path, exc))\n _log_runtime(parameter, '/proc/net/[tcp|udp]', start_time)\n return conn\n except IOError as exc:\n _log_failure(parameter, exc)\n raise", "context": "def connections(pid=None, user=None): ...\ndef is_available(): ...\ndef system_start_time(): ...\ndef physical_memory(): ...\ndef cwd(pid): ...\ndef uid(pid): ...\ndef memory_usage(pid): ...\ndef stats(pid, *stat_types): ...\ndef file_descriptors_used(pid): ...\ndef connections(pid=None, user=None): ...\ndef _inodes_for_sockets(pid): ...\ndef _unpack_addr(addr): ...\ndef _is_float(*value): ...\ndef _get_line(file_path, line_prefix, parameter): ...\ndef _get_lines(file_path, line_prefixes, parameter): ...\ndef _log_runtime(parameter, proc_location, start_time): ...\ndef _log_failure(parameter, exc): ...\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_000990.py"} {"focal_file": "stem/descriptor/remote.py", "focal_class": "stem.descriptor.remote.DescriptorDownloader", "focal_method": "use_directory_mirrors", "tests": "import unittest\n\nclass Test_stem_descriptor_remote_DescriptorDownloader_use_directory_mirrors(unittest.TestCase):\n @test.require.only_run_once\n @test.require.online\n def test_use_directory_mirrors(self):\n \"\"\"\n Checks that we can fetch and use a list of directory mirrors.\n \"\"\"\n downloader = stem.descriptor.remote.DescriptorDownloader()\n downloader.use_directory_mirrors()\n self.assertTrue(len(downloader._endpoints) > 50)\n", "method_code": " def use_directory_mirrors(self):\n \"\"\"\n Downloads the present consensus and configures ourselves to use directory\n mirrors, in addition to authorities.\n \n :returns: :class:`~stem.descriptor.networkstatus.NetworkStatusDocumentV3`\n from which we got the directory mirrors\n \n :raises: **Exception** if unable to determine the directory mirrors\n \"\"\"\n directories = stem.directory.Authority.from_cache().values()\n new_endpoints = set([(directory.address, directory.dir_port) for directory in directories])\n consensus = list(self.get_consensus(document_handler=stem.descriptor.DocumentHandler.DOCUMENT).run())[0]\n for desc in consensus.routers.values():\n if stem.Flag.V2DIR in desc.flags and desc.dir_port:\n new_endpoints.add((desc.address, desc.dir_port))\n self._endpoints = list(new_endpoints)\n return consensus\n ", "context": "class DescriptorDownloader(object):\n def use_directory_mirrors(self): ...\n def __init__(self, use_mirrors=False, **default_args): ...\n def their_server_descriptor(self, **query_args): ...\n def get_server_descriptors(self, fingerprints=None, **query_args): ...\n def get_extrainfo_descriptors(self, fingerprints=None, **query_args): ...\n def get_microdescriptors(self, hashes, **query_args): ...\n def get_consensus(self, authority_v3ident=None, microdescriptor=False, **query_args): ...\n def get_vote(self, authority, **query_args): ...\n def get_key_certificates(self, authority_v3idents=None, **query_args): ...\n def get_detached_signatures(self, **query_args): ...\n def query(self, resource, **query_args): ...\n\n self._default_args = default_args\n self._endpoints = [(directory.address, directory.dir_port) for directory in directories]\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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, 1, 0, 0], "pynose_source_file": "test_000991.py"} {"focal_file": "stem/descriptor/remote.py", "focal_class": "stem.descriptor.remote.DescriptorDownloader", "focal_method": "get_server_descriptors", "tests": "import unittest\n\nclass Test_stem_descriptor_remote_DescriptorDownloader_get_server_descriptors(unittest.TestCase):\n @test.require.only_run_once\n @test.require.online\n def test_get_server_descriptors(self):\n \"\"\"\n Exercises the downloader's get_server_descriptors() method.\n \"\"\"\n downloader = stem.descriptor.remote.DescriptorDownloader(validate=True)\n single_query = downloader.get_server_descriptors('9695DFC35FFEB861329B9F1AB04C46397020CE31')\n multiple_query = downloader.get_server_descriptors(['9695DFC35FFEB861329B9F1AB04C46397020CE31', '847B1F850344D7876491A54892F904934E4EB85D'])\n single_query.run()\n multiple_query.run()\n single_query_results = list(single_query)\n self.assertEqual(1, len(single_query_results))\n self.assertEqual('moria1', single_query_results[0].nickname)\n self.assertTrue(isinstance(single_query_results[0], stem.descriptor.server_descriptor.ServerDescriptor))\n self.assertEqual(2, len(list(multiple_query)))\n", "method_code": "def get_server_descriptors(fingerprints=None, **query_args):\n \"\"\"\n Shorthand for\n :func:`~stem.descriptor.remote.DescriptorDownloader.get_server_descriptors`\n on our singleton instance.\n\n .. versionadded:: 1.5.0\n \"\"\"\n return get_instance().get_server_descriptors(fingerprints, **query_args)", "context": "def get_server_descriptors(fingerprints=None, **query_args): ...\ndef get_instance(): ...\ndef their_server_descriptor(**query_args): ...\ndef get_server_descriptors(fingerprints=None, **query_args): ...\ndef get_extrainfo_descriptors(fingerprints=None, **query_args): ...\ndef get_microdescriptors(hashes, **query_args): ...\ndef get_consensus(authority_v3ident=None, microdescriptor=False, **query_args): ...\ndef get_detached_signatures(**query_args): ...\ndef _download_from_orport(endpoint, compression, resource): ...\ndef _download_from_dirport(url, compression, timeout): ...\ndef _decompress(data, encoding): ...\ndef _guess_descriptor_type(resource): ...\ndef get_authorities(): ...\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000992.py"} {"focal_file": "stem/descriptor/remote.py", "focal_class": "stem.descriptor.remote.DescriptorDownloader", "focal_method": "get_extrainfo_descriptors", "tests": "import unittest\n\nclass Test_stem_descriptor_remote_DescriptorDownloader_get_extrainfo_descriptors(unittest.TestCase):\n @test.require.only_run_once\n @test.require.online\n def test_get_extrainfo_descriptors(self):\n \"\"\"\n Exercises the downloader's get_extrainfo_descriptors() method.\n \"\"\"\n downloader = stem.descriptor.remote.DescriptorDownloader(validate=True)\n single_query = downloader.get_extrainfo_descriptors('9695DFC35FFEB861329B9F1AB04C46397020CE31')\n multiple_query = downloader.get_extrainfo_descriptors(['9695DFC35FFEB861329B9F1AB04C46397020CE31', '847B1F850344D7876491A54892F904934E4EB85D'])\n single_query.run()\n multiple_query.run()\n single_query_results = list(single_query)\n self.assertEqual(1, len(single_query_results))\n self.assertEqual('moria1', single_query_results[0].nickname)\n self.assertTrue(isinstance(single_query_results[0], stem.descriptor.extrainfo_descriptor.ExtraInfoDescriptor))\n self.assertEqual(2, len(list(multiple_query)))\n", "method_code": "def get_extrainfo_descriptors(fingerprints=None, **query_args):\n \"\"\"\n Shorthand for\n :func:`~stem.descriptor.remote.DescriptorDownloader.get_extrainfo_descriptors`\n on our singleton instance.\n\n .. versionadded:: 1.5.0\n \"\"\"\n return get_instance().get_extrainfo_descriptors(fingerprints, **query_args)", "context": "def get_extrainfo_descriptors(fingerprints=None, **query_args): ...\ndef get_instance(): ...\ndef their_server_descriptor(**query_args): ...\ndef get_server_descriptors(fingerprints=None, **query_args): ...\ndef get_extrainfo_descriptors(fingerprints=None, **query_args): ...\ndef get_microdescriptors(hashes, **query_args): ...\ndef get_consensus(authority_v3ident=None, microdescriptor=False, **query_args): ...\ndef get_detached_signatures(**query_args): ...\ndef _download_from_orport(endpoint, compression, resource): ...\ndef _download_from_dirport(url, compression, timeout): ...\ndef _decompress(data, encoding): ...\ndef _guess_descriptor_type(resource): ...\ndef get_authorities(): ...\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000993.py"} {"focal_file": "stem/descriptor/remote.py", "focal_class": "stem.descriptor.remote.DescriptorDownloader", "focal_method": "get_consensus", "tests": "import unittest\n\nclass Test_stem_descriptor_remote_DescriptorDownloader_get_consensus(unittest.TestCase):\n @test.require.only_run_once\n @test.require.online\n def test_get_consensus(self):\n \"\"\"\n Exercises the downloader's get_consensus() method.\n \"\"\"\n downloader = stem.descriptor.remote.DescriptorDownloader(validate=True)\n consensus_query = downloader.get_consensus()\n consensus_query.run()\n consensus = list(consensus_query)\n self.assertTrue(len(consensus) > 50)\n self.assertTrue(isinstance(consensus[0], stem.descriptor.router_status_entry.RouterStatusEntryV3))\n\n @test.require.only_run_once\n @test.require.online\n def test_get_microdescriptor_consensus(self):\n \"\"\"\n Exercises the downloader's get_consensus() method for fetching a\n microdescriptor consensus.\n \"\"\"\n downloader = stem.descriptor.remote.DescriptorDownloader(validate=True)\n consensus_query = downloader.get_consensus(microdescriptor=True)\n consensus_query.run()\n consensus = list(consensus_query)\n self.assertTrue(len(consensus) > 50)\n self.assertTrue(isinstance(consensus[0], stem.descriptor.router_status_entry.RouterStatusEntryMicroV3))\n", "method_code": "def get_consensus(authority_v3ident=None, microdescriptor=False, **query_args):\n \"\"\"\n Shorthand for\n :func:`~stem.descriptor.remote.DescriptorDownloader.get_consensus`\n on our singleton instance.\n\n .. versionadded:: 1.5.0\n \"\"\"\n return get_instance().get_consensus(authority_v3ident, microdescriptor, **query_args)", "context": "def get_consensus(authority_v3ident=None, microdescriptor=False, **query_args): ...\ndef get_instance(): ...\ndef their_server_descriptor(**query_args): ...\ndef get_server_descriptors(fingerprints=None, **query_args): ...\ndef get_extrainfo_descriptors(fingerprints=None, **query_args): ...\ndef get_microdescriptors(hashes, **query_args): ...\ndef get_consensus(authority_v3ident=None, microdescriptor=False, **query_args): ...\ndef get_detached_signatures(**query_args): ...\ndef _download_from_orport(endpoint, compression, resource): ...\ndef _download_from_dirport(url, compression, timeout): ...\ndef _decompress(data, encoding): ...\ndef _guess_descriptor_type(resource): ...\ndef get_authorities(): ...\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000994.py"} {"focal_file": "stem/descriptor/remote.py", "focal_class": "stem.descriptor.remote.DescriptorDownloader", "focal_method": "get_key_certificates", "tests": "import unittest\n\nclass Test_stem_descriptor_remote_DescriptorDownloader_get_key_certificates(unittest.TestCase):\n @test.require.only_run_once\n @test.require.online\n def test_get_key_certificates(self):\n \"\"\"\n Exercises the downloader's get_key_certificates() method.\n \"\"\"\n downloader = stem.descriptor.remote.DescriptorDownloader(validate=True)\n single_query = downloader.get_key_certificates('D586D18309DED4CD6D57C18FDB97EFA96D330566')\n multiple_query = downloader.get_key_certificates(['D586D18309DED4CD6D57C18FDB97EFA96D330566', '14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4'])\n single_query.run()\n multiple_query.run()\n single_query_results = list(single_query)\n self.assertEqual(1, len(single_query_results))\n self.assertEqual('D586D18309DED4CD6D57C18FDB97EFA96D330566', single_query_results[0].fingerprint)\n self.assertTrue(isinstance(single_query_results[0], stem.descriptor.networkstatus.KeyCertificate))\n self.assertEqual(2, len(list(multiple_query)))\n", "method_code": " def get_key_certificates(self, authority_v3idents=None, **query_args):\n \"\"\"\n Provides the key certificates for authorities with the given fingerprints.\n If no fingerprints are provided then this returns all present key\n certificates.\n \n :param str authority_v3idents: fingerprint or list of fingerprints of the\n authority keys, see `'v3ident' in tor's config.c\n `_\n for the values.\n :param query_args: additional arguments for the\n :class:`~stem.descriptor.remote.Query` constructor\n \n :returns: :class:`~stem.descriptor.remote.Query` for the key certificates\n \n :raises: **ValueError** if we request more than 96 key certificates by\n their identity fingerprints (this is due to a limit on the url length by\n squid proxies).\n \"\"\"\n resource = '/tor/keys/all'\n if isinstance(authority_v3idents, str):\n authority_v3idents = [authority_v3idents]\n if authority_v3idents:\n if len(authority_v3idents) > MAX_FINGERPRINTS:\n raise ValueError('Unable to request more than %i key certificates at a time by their identity fingerprints' % MAX_FINGERPRINTS)\n resource = '/tor/keys/fp/%s' % '+'.join(authority_v3idents)\n return self.query(resource, **query_args)\n ", "context": "class DescriptorDownloader(object):\n def get_key_certificates(self, authority_v3idents=None, **query_args): ...\n def __init__(self, use_mirrors=False, **default_args): ...\n def use_directory_mirrors(self): ...\n def their_server_descriptor(self, **query_args): ...\n def get_server_descriptors(self, fingerprints=None, **query_args): ...\n def get_extrainfo_descriptors(self, fingerprints=None, **query_args): ...\n def get_microdescriptors(self, hashes, **query_args): ...\n def get_consensus(self, authority_v3ident=None, microdescriptor=False, **query_args): ...\n def get_vote(self, authority, **query_args): ...\n def get_detached_signatures(self, **query_args): ...\n def query(self, resource, **query_args): ...\n\n self._default_args = default_args\n self._endpoints = [(directory.address, directory.dir_port) for directory in directories]\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_000995.py"} {"focal_file": "stem/version.py", "focal_class": "Version", "focal_method": "greater_than", "tests": "import unittest\n\nclass Test_Version_greater_than(unittest.TestCase):\n def test_requirements_greater_than(self):\n \"\"\"\n Checks a VersionRequirements with a single greater_than rule.\n \"\"\"\n requirements = stem.version._VersionRequirements()\n requirements.greater_than(Version('0.2.2.36'))\n self.assertTrue(Version('0.2.2.36') >= requirements)\n self.assertTrue(Version('0.2.2.37') >= requirements)\n self.assertTrue(Version('0.2.3.36') >= requirements)\n self.assertFalse(Version('0.2.2.35') >= requirements)\n self.assertFalse(Version('0.2.1.38') >= requirements)\n requirements = stem.version._VersionRequirements()\n requirements.greater_than(Version('0.2.2.36'), False)\n self.assertFalse(Version('0.2.2.35') >= requirements)\n self.assertFalse(Version('0.2.2.36') >= requirements)\n self.assertTrue(Version('0.2.2.37') >= requirements)\n", "method_code": " def greater_than(self, version, inclusive=True):\n \"\"\"\n Adds a constraint that we're greater than the given version.\n \n :param stem.version.Version version: version we're checking against\n :param bool inclusive: if comparison is inclusive or not\n \"\"\"\n if inclusive:\n self.rules.append(lambda v: version <= v)\n else:\n self.rules.append(lambda v: version < v)\n ", "context": "class _VersionRequirements(object):\n def greater_than(self, version, inclusive=True): ...\n def __init__(self): ...\n def less_than(self, version, inclusive=True): ...\n def in_range(self, from_version, to_version, from_inclusive=True, to_inclusive=False): ...\n\n self.rules = []\n", "repository": "illumineinteractive/stem", "test_name": "test_requirements_greater_than", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000996.py"} {"focal_file": "stem/version.py", "focal_class": "Version", "focal_method": "less_than", "tests": "import unittest\n\nclass Test_Version_less_than(unittest.TestCase):\n def test_requirements_less_than(self):\n \"\"\"\n Checks a VersionRequirements with a single less_than rule.\n \"\"\"\n requirements = stem.version._VersionRequirements()\n requirements.less_than(Version('0.2.2.36'))\n self.assertTrue(Version('0.2.2.36') >= requirements)\n self.assertTrue(Version('0.2.2.35') >= requirements)\n self.assertTrue(Version('0.2.1.38') >= requirements)\n self.assertFalse(Version('0.2.2.37') >= requirements)\n self.assertFalse(Version('0.2.3.36') >= requirements)\n requirements = stem.version._VersionRequirements()\n requirements.less_than(Version('0.2.2.36'), False)\n self.assertFalse(Version('0.2.2.37') >= requirements)\n self.assertFalse(Version('0.2.2.36') >= requirements)\n self.assertTrue(Version('0.2.2.35') >= requirements)\n\n def test_requirements_multiple_rules(self):\n \"\"\"\n Checks a VersionRequirements is the logical 'or' when it has multiple rules.\n \"\"\"\n requirements = stem.version._VersionRequirements()\n requirements.greater_than(Version('0.2.3.0'))\n requirements.less_than(Version('0.2.2.0'), False)\n self.assertTrue(Version('0.2.3.0') >= requirements)\n self.assertFalse(Version('0.2.2.0') >= requirements)\n for index in range(0, 100):\n self.assertFalse(Version('0.2.2.%i' % index) >= requirements)\n", "method_code": " def less_than(self, version, inclusive=True):\n \"\"\"\n Adds a constraint that we're less than the given version.\n \n :param stem.version.Version version: version we're checking against\n :param bool inclusive: if comparison is inclusive or not\n \"\"\"\n if inclusive:\n self.rules.append(lambda v: version >= v)\n else:\n self.rules.append(lambda v: version > v)\n ", "context": "class _VersionRequirements(object):\n def less_than(self, version, inclusive=True): ...\n def __init__(self): ...\n def greater_than(self, version, inclusive=True): ...\n def in_range(self, from_version, to_version, from_inclusive=True, to_inclusive=False): ...\n\n self.rules = []\n", "repository": "illumineinteractive/stem", "test_name": "test_requirements_less_than", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000997.py"} {"focal_file": "stem/version.py", "focal_class": "Version", "focal_method": "in_range", "tests": "import unittest\n\nclass Test_Version_in_range(unittest.TestCase):\n def test_requirements_in_range(self):\n \"\"\"\n Checks a VersionRequirements with a single in_range rule.\n \"\"\"\n requirements = stem.version._VersionRequirements()\n requirements.in_range(Version('0.2.2.36'), Version('0.2.2.38'))\n self.assertFalse(Version('0.2.2.35') >= requirements)\n self.assertTrue(Version('0.2.2.36') >= requirements)\n self.assertTrue(Version('0.2.2.37') >= requirements)\n self.assertFalse(Version('0.2.2.38') >= requirements)\n requirements = stem.version._VersionRequirements()\n requirements.in_range(Version('0.2.2.0'), Version('0.2.3.0'))\n for index in range(0, 100):\n self.assertTrue(Version('0.2.2.%i' % index) >= requirements)\n", "method_code": " def in_range(self, from_version, to_version, from_inclusive=True, to_inclusive=False):\n \"\"\"\n Adds constraint that we're within the range from one version to another.\n \n :param stem.version.Version from_version: beginning of the comparison range\n :param stem.version.Version to_version: end of the comparison range\n :param bool from_inclusive: if comparison is inclusive with the starting version\n :param bool to_inclusive: if comparison is inclusive with the ending version\n \"\"\"\n \n def new_rule(v):\n if from_inclusive and to_inclusive:\n return from_version <= v <= to_version\n elif from_inclusive:\n return from_version <= v < to_version\n else:\n return from_version < v < to_version\n self.rules.append(new_rule)\n ", "context": "class _VersionRequirements(object):\n def in_range(self, from_version, to_version, from_inclusive=True, to_inclusive=False): ...\n def __init__(self): ...\n def greater_than(self, version, inclusive=True): ...\n def less_than(self, version, inclusive=True): ...\n\n self.rules = []\n", "repository": "illumineinteractive/stem", "test_name": "test_requirements_in_range", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_000998.py"} {"focal_file": "stem/manual.py", "focal_class": null, "focal_method": "query", "tests": "import unittest\n\nclass Test_query(unittest.TestCase):\n def test_query(self):\n self.assertEqual(\"If set, this option overrides the default location and file name for Tor's cookie file. (See CookieAuthentication above.)\", stem.manual.query('SELECT description FROM torrc WHERE name=\"CookieAuthFile\"').fetchone()[0])\n self.assertEqual(\"If set, this option overrides the default location and file name for Tor's cookie file. (See CookieAuthentication above.)\", stem.manual.query('SELECT description FROM torrc WHERE name=?', 'CookieAuthFile').fetchone()[0])\n", "method_code": "def query(query, *param):\n \"\"\"\n Performs the given query on our sqlite manual cache. This database should\n be treated as being read-only. File permissions generally enforce this, and\n in the future will be enforced by this function as well.\n\n ::\n\n >>> import stem.manual\n >>> print(stem.manual.query('SELECT description FROM torrc WHERE key=?', 'CONTROLSOCKET').fetchone()[0])\n Like ControlPort, but listens on a Unix domain socket, rather than a TCP socket. 0 disables ControlSocket. (Unix and Unix-like systems only.) (Default: 0)\n\n .. versionadded:: 1.6.0\n\n :param str query: query to run on the cache\n :param list param: query parameters\n\n :returns: :class:`sqlite3.Cursor` with the query results\n\n :raises:\n * **ImportError** if the sqlite3 module is unavailable\n * **sqlite3.OperationalError** if query fails\n \"\"\"\n if not stem.prereq.is_sqlite_available():\n raise ImportError('Querying requires the sqlite3 module')\n import sqlite3\n global DATABASE\n if DATABASE is None:\n DATABASE = sqlite3.connect(CACHE_PATH)\n return DATABASE.execute(query, param)", "context": "def query(query, *param): ...\ndef query(query, *param): ...\ndef _config(lowercase=True): ...\ndef _manual_differences(previous_manual, new_manual): ...\ndef is_important(option): ...\ndef download_man_page(path=None, file_handle=None, url=GITWEB_MANUAL_URL, timeout=20): ...\ndef _get_categories(content): ...\ndef _get_indented_descriptions(lines): ...\ndef _add_config_options(config_options, category, lines): ...\ndef _join_lines(lines): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_query", "smells": [1, 0, 0, 0, 1, 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": [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": "stem/manual.py", "focal_class": null, "focal_method": "is_important", "tests": "import unittest\n\nclass Test_is_important(unittest.TestCase):\n def test_is_important(self):\n self.assertTrue(stem.manual.is_important('ExitPolicy'))\n self.assertTrue(stem.manual.is_important('exitpolicy'))\n self.assertTrue(stem.manual.is_important('EXITPOLICY'))\n self.assertFalse(stem.manual.is_important('ConstrainedSockSize'))\n", "method_code": "def is_important(option):\n \"\"\"\n Indicates if a configuration option of particularly common importance or not.\n\n :param str option: tor configuration option to check\n\n :returns: **bool** that's **True** if this is an important option and\n **False** otherwise\n \"\"\"\n return option.lower() in _config()['manual.important']", "context": "def is_important(option): ...\ndef query(query, *param): ...\ndef _config(lowercase=True): ...\ndef _manual_differences(previous_manual, new_manual): ...\ndef is_important(option): ...\ndef download_man_page(path=None, file_handle=None, url=GITWEB_MANUAL_URL, timeout=20): ...\ndef _get_categories(content): ...\ndef _get_indented_descriptions(lines): ...\ndef _add_config_options(config_options, category, lines): ...\ndef _join_lines(lines): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_is_important", "smells": [1, 0, 0, 0, 1, 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": [1, 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": "stem/manual.py", "focal_class": null, "focal_method": "download_man_page", "tests": "import unittest\n\nclass Test_download_man_page(unittest.TestCase):\n @patch('tempfile.mkdtemp', Mock(return_value='/no/such/path'))\n @patch('shutil.rmtree', Mock())\n @patch('stem.manual.open', create=True)\n @patch('stem.util.system.call')\n @patch('stem.util.system.is_available', Mock(return_value=True))\n @patch('os.path.exists', Mock(return_value=True))\n @patch(URL_OPEN, Mock(return_value=io.BytesIO(b'test content')))\n def test_download_man_page_when_successful(self, call_mock, open_mock):\n open_mock.side_effect = lambda path, *args: {'/no/such/path/tor.1.txt': io.BytesIO(), '/no/such/path/tor.1': io.BytesIO(b'a2x output')}[path]\n call_mock.return_value = Mock()\n output = io.BytesIO()\n stem.manual.download_man_page(file_handle=output)\n self.assertEqual(b'a2x output', output.getvalue())\n call_mock.assert_called_once_with('a2x -f manpage /no/such/path/tor.1.txt')\n", "method_code": "def download_man_page(path=None, file_handle=None, url=GITWEB_MANUAL_URL, timeout=20):\n \"\"\"\n Downloads tor's latest man page from `gitweb.torproject.org\n `_. This method is\n both slow and unreliable - please see the warnings on\n :func:`~stem.manual.Manual.from_remote`.\n\n :param str path: path to save tor's man page to\n :param file file_handle: file handler to save tor's man page to\n :param str url: url to download tor's asciidoc manual from\n :param int timeout: seconds to wait before timing out the request\n\n :raises: **IOError** if unable to retrieve the manual\n \"\"\"\n if not path and (not file_handle):\n raise ValueError(\"Either the path or file_handle we're saving to must be provided\")\n elif not stem.util.system.is_available('a2x'):\n raise IOError('We require a2x from asciidoc to provide a man page')\n dirpath = tempfile.mkdtemp()\n asciidoc_path = os.path.join(dirpath, 'tor.1.txt')\n manual_path = os.path.join(dirpath, 'tor.1')\n try:\n try:\n with open(asciidoc_path, 'wb') as asciidoc_file:\n request = urllib.urlopen(url, timeout=timeout)\n shutil.copyfileobj(request, asciidoc_file)\n except:\n exc = sys.exc_info()[1]\n raise IOError(\"Unable to download tor's manual from %s to %s: %s\" % (url, asciidoc_path, exc))\n try:\n stem.util.system.call('a2x -f manpage %s' % asciidoc_path)\n if not os.path.exists(manual_path):\n raise OSError('no man page was generated')\n except stem.util.system.CallError as exc:\n raise IOError(\"Unable to run '%s': %s\" % (exc.command, exc.stderr))\n if path:\n try:\n path_dir = os.path.dirname(path)\n if not os.path.exists(path_dir):\n os.makedirs(path_dir)\n shutil.copyfile(manual_path, path)\n except OSError as exc:\n raise IOError(exc)\n if file_handle:\n with open(manual_path, 'rb') as manual_file:\n shutil.copyfileobj(manual_file, file_handle)\n file_handle.flush()\n finally:\n shutil.rmtree(dirpath)", "context": "def download_man_page(path=None, file_handle=None, url=GITWEB_MANUAL_URL, timeout=20): ...\ndef query(query, *param): ...\ndef _config(lowercase=True): ...\ndef _manual_differences(previous_manual, new_manual): ...\ndef is_important(option): ...\ndef download_man_page(path=None, file_handle=None, url=GITWEB_MANUAL_URL, timeout=20): ...\ndef _get_categories(content): ...\ndef _get_indented_descriptions(lines): ...\ndef _add_config_options(config_options, category, lines): ...\ndef _join_lines(lines): ...\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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_001001.py"} {"focal_file": "stem/interpreter/autocomplete.py", "focal_class": "Autocompleter", "focal_method": "matches", "tests": "import unittest\n\nclass Test_Autocompleter_matches(unittest.TestCase):\n def test_autocompleter_match(self):\n \"\"\"\n Exercise our Autocompleter's match method.\n \"\"\"\n autocompleter = Autocompleter(None)\n self.assertEqual(['/help'], autocompleter.matches('/help'))\n self.assertEqual(['/help'], autocompleter.matches('/hel'))\n self.assertEqual(['/help'], autocompleter.matches('/he'))\n self.assertEqual(['/help'], autocompleter.matches('/h'))\n self.assertEqual(['/help', '/events', '/info', '/quit'], autocompleter.matches('/'))\n self.assertEqual(['/help'], autocompleter.matches('/HELP'))\n self.assertEqual(['/help'], autocompleter.matches('/HeLp'))\n self.assertEqual([], autocompleter.matches('blarg'))\n", "method_code": " def matches(self, text):\n \"\"\"\n Provides autocompletion matches for the given text.\n \n :param str text: text to check for autocompletion matches with\n \n :returns: **list** with possible matches\n \"\"\"\n lowercase_text = text.lower()\n return [cmd for cmd in self._commands if cmd.lower().startswith(lowercase_text)]\n ", "context": "class Autocompleter(object):\n @lru_cache()\n def matches(self, text): ...\n def __init__(self, controller): ...\n def complete(self, text, state): ...\n\n self._commands = _get_commands(controller)\n", "repository": "illumineinteractive/stem", "test_name": "test_autocompleter_match", "smells": [1, 0, 0, 0, 1, 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": [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": "stem/interpreter/autocomplete.py", "focal_class": "Autocompleter", "focal_method": "complete", "tests": "import unittest\n\nclass Test_Autocompleter_complete(unittest.TestCase):\n def test_autocompleter_complete(self):\n \"\"\"\n Exercise our Autocompleter's complete method.\n \"\"\"\n autocompleter = Autocompleter(None)\n self.assertEqual('/help', autocompleter.complete('/', 0))\n self.assertEqual('/events', autocompleter.complete('/', 1))\n self.assertEqual('/info', autocompleter.complete('/', 2))\n self.assertEqual('/quit', autocompleter.complete('/', 3))\n self.assertEqual(None, autocompleter.complete('/', 4))\n self.assertEqual(None, autocompleter.complete('blarg', 0))\n", "method_code": " def complete(self, text, state):\n \"\"\"\n Provides case insensetive autocompletion options, acting as a functor for\n the readlines set_completer function.\n \n :param str text: text to check for autocompletion matches with\n :param int state: index of result to be provided, readline fetches matches\n until this function provides None\n \n :returns: **str** with the autocompletion match, **None** if eithe none\n exists or state is higher than our number of matches\n \"\"\"\n try:\n return self.matches(text)[state]\n except IndexError:\n return None\n ", "context": "class Autocompleter(object):\n def complete(self, text, state): ...\n def __init__(self, controller): ...\n def matches(self, text): ...\n\n self._commands = _get_commands(controller)\n", "repository": "illumineinteractive/stem", "test_name": "test_autocompleter_complete", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001003.py"} {"focal_file": "stem/interpreter/help.py", "focal_class": null, "focal_method": "_normalize", "tests": "import unittest\n\nclass Test_normalize(unittest.TestCase):\n def test_normalization(self):\n self.assertEqual('', _normalize(''))\n self.assertEqual('', _normalize(' '))\n self.assertEqual('GETINFO', _normalize('GETINFO'))\n self.assertEqual('GETINFO', _normalize('GetInfo'))\n self.assertEqual('GETINFO', _normalize('getinfo'))\n self.assertEqual('GETINFO', _normalize('GETINFO version'))\n self.assertEqual('GETINFO', _normalize('GETINFO '))\n self.assertEqual('INFO', _normalize('/info'))\n self.assertEqual('INFO', _normalize('/info caerSidi'))\n", "method_code": "def _normalize(arg):\n arg = arg.upper()\n arg = arg.split(' ')[0]\n if arg.startswith('/'):\n arg = arg[1:]\n return arg", "context": "def _normalize(arg): ...\ndef response(controller, arg): ...\ndef _normalize(arg): ...\ndef _response(controller, arg, config): ...\ndef _general_help(): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_normalization", "smells": [1, 0, 0, 0, 1, 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": [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": "stem/interpreter/commands.py", "focal_class": null, "focal_method": "_get_fingerprint", "tests": "import unittest\n\nclass Test_get_fingerprint(unittest.TestCase):\n def test_get_fingerprint_for_ourselves(self):\n controller = Mock()\n controller.get_info.side_effect = lambda arg: {'fingerprint': FINGERPRINT}[arg]\n self.assertEqual(FINGERPRINT, _get_fingerprint('', controller))\n controller.get_info.side_effect = stem.ControllerError\n self.assertRaises(ValueError, _get_fingerprint, '', controller)\n\n def test_get_fingerprint_for_fingerprint(self):\n self.assertEqual(FINGERPRINT, _get_fingerprint(FINGERPRINT, Mock()))\n\n def test_get_fingerprint_for_nickname(self):\n controller, descriptor = (Mock(), Mock())\n descriptor.fingerprint = FINGERPRINT\n controller.get_network_status.side_effect = lambda arg: {'moria1': descriptor}[arg]\n self.assertEqual(FINGERPRINT, _get_fingerprint('moria1', controller))\n controller.get_network_status.side_effect = stem.ControllerError\n self.assertRaises(ValueError, _get_fingerprint, 'moria1', controller)\n\n def test_get_fingerprint_for_address(self):\n controller = Mock()\n self.assertRaises(ValueError, _get_fingerprint, '127.0.0.1:-1', controller)\n self.assertRaises(ValueError, _get_fingerprint, '127.0.0.901:80', controller)\n descriptor = Mock()\n descriptor.address = '127.0.0.1'\n descriptor.or_port = 80\n descriptor.fingerprint = FINGERPRINT\n controller.get_network_statuses.return_value = [descriptor]\n self.assertEqual(FINGERPRINT, _get_fingerprint('127.0.0.1', controller))\n self.assertEqual(FINGERPRINT, _get_fingerprint('127.0.0.1:80', controller))\n self.assertRaises(ValueError, _get_fingerprint, '127.0.0.1:81', controller)\n self.assertRaises(ValueError, _get_fingerprint, '127.0.0.2', controller)\n", "method_code": "def _get_fingerprint(arg, controller):\n \"\"\"\n Resolves user input into a relay fingerprint. This accepts...\n\n * Fingerprints\n * Nicknames\n * IPv4 addresses, either with or without an ORPort\n * Empty input, which is resolved to ourselves if we're a relay\n\n :param str arg: input to be resolved to a relay fingerprint\n :param stem.control.Controller controller: tor control connection\n\n :returns: **str** for the relay fingerprint\n\n :raises: **ValueError** if we're unable to resolve the input to a relay\n \"\"\"\n if not arg:\n try:\n return controller.get_info('fingerprint')\n except:\n raise ValueError(\"We aren't a relay, no information to provide\")\n elif stem.util.tor_tools.is_valid_fingerprint(arg):\n return arg\n elif stem.util.tor_tools.is_valid_nickname(arg):\n try:\n return controller.get_network_status(arg).fingerprint\n except:\n raise ValueError(\"Unable to find a relay with the nickname of '%s'\" % arg)\n elif ':' in arg or stem.util.connection.is_valid_ipv4_address(arg):\n if ':' in arg:\n address, port = arg.rsplit(':', 1)\n if not stem.util.connection.is_valid_ipv4_address(address):\n raise ValueError(\"'%s' isn't a valid IPv4 address\" % address)\n elif port and (not stem.util.connection.is_valid_port(port)):\n raise ValueError(\"'%s' isn't a valid port\" % port)\n port = int(port)\n else:\n address, port = (arg, None)\n matches = {}\n for desc in controller.get_network_statuses():\n if desc.address == address:\n if not port or desc.or_port == port:\n matches[desc.or_port] = desc.fingerprint\n if len(matches) == 0:\n raise ValueError('No relays found at %s' % arg)\n elif len(matches) == 1:\n return list(matches.values())[0]\n else:\n response = \"There's multiple relays at %s, include a port to specify which.\\n\\n\" % arg\n for i, or_port in enumerate(matches):\n response += ' %i. %s:%s, fingerprint: %s\\n' % (i + 1, address, or_port, matches[or_port])\n raise ValueError(response)\n else:\n raise ValueError(\"'%s' isn't a fingerprint, nickname, or IP address\" % arg)", "context": "def _get_fingerprint(arg, controller): ...\ndef _get_fingerprint(arg, controller): ...\ndef redirect(stdout, stderr): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_get_fingerprint_for_ourselves", "smells": [1, 0, 0, 0, 1, 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": [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": "stem/interpreter/commands.py", "focal_class": "ControlInterpreter", "focal_method": "run_command", "tests": "import unittest\n\nclass Test_ControlInterpreter_run_command(unittest.TestCase):\n def test_unrecognized_interpreter_command(self):\n interpreter = ControlInterpreter(CONTROLLER)\n expected = \"\\x1b[1;31m'/unrecognized' isn't a recognized command\\x1b[0m\\n\"\n self.assertEqual(expected, interpreter.run_command('/unrecognized'))\n", "method_code": " def run_command(self, command, config, print_response=False):\n \"\"\"\n Runs the given command. Requests starting with a '/' are special commands\n to the interpreter, and anything else is sent to the control port.\n \n :param stem.control.Controller controller: tor control connection\n :param str command: command to be processed\n :param bool print_response: prints the response to stdout if true\n \n :returns: **list** out output lines, each line being a list of\n (msg, format) tuples\n \n :raises: **stem.SocketClosed** if the control connection has been severed\n \"\"\"\n cmd, arg = (command.strip(), '')\n if ' ' in cmd:\n cmd, arg = cmd.split(' ', 1)\n output = ''\n if cmd.startswith('/'):\n cmd = cmd.lower()\n if cmd == '/quit':\n raise stem.SocketClosed()\n elif cmd == '/events':\n output = self.do_events(arg)\n elif cmd == '/info':\n output = self.do_info(arg)\n elif cmd == '/python':\n output = self.do_python(arg)\n elif cmd == '/help':\n output = self.do_help(arg)\n else:\n output = format(\"'%s' isn't a recognized command\" % command, *ERROR_OUTPUT)\n else:\n cmd = cmd.upper()\n if cmd.replace('+', '') in ('LOADCONF', 'POSTDESCRIPTOR'):\n output = format(msg('msg.multiline_unimplemented_notice'), *ERROR_OUTPUT)\n elif cmd == 'QUIT':\n self._controller.msg(command)\n raise stem.SocketClosed()\n else:\n is_tor_command = cmd in config.get('help.usage', {}) and cmd.lower() != 'events'\n if self._run_python_commands and (not is_tor_command):\n console_output = StringIO()\n with redirect(console_output, console_output):\n self.is_multiline_context = code.InteractiveConsole.push(self, command)\n output = console_output.getvalue().strip()\n else:\n try:\n output = format(self._controller.msg(command).raw_content().strip(), *STANDARD_OUTPUT)\n except stem.ControllerError as exc:\n if isinstance(exc, stem.SocketClosed):\n raise\n else:\n output = format(str(exc), *ERROR_OUTPUT)\n if output:\n output += '\\n'\n if print_response:\n print(output)\n return output\n ", "context": "class ControlInterpreter(code.InteractiveConsole):\n @uses_settings\n def run_command(self, command, config, print_response=False): ...\n def __init__(self, controller): ...\n def get_events(self, *event_types): ...\n def do_help(self, arg): ...\n def do_events(self, arg): ...\n def do_info(self, arg): ...\n def do_python(self, arg): ...\n\n self._received_events = []\n self._controller = controller\n self._run_python_commands = True\n self.is_multiline_context = False\n self._controller._handle_event = handle_event_wrapper\n", "repository": "illumineinteractive/stem", "test_name": "test_unrecognized_interpreter_command", "smells": [1, 0, 0, 0, 1, 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_001006.py"} {"focal_file": "stem/interpreter/arguments.py", "focal_class": null, "focal_method": "get_help", "tests": "import unittest\n\nclass Test_get_help(unittest.TestCase):\n def test_get_help(self):\n help_text = get_help()\n self.assertTrue('Interactive interpreter for Tor.' in help_text)\n self.assertTrue('change control interface from 127.0.0.1:default' in help_text)\n", "method_code": "def get_help():\n \"\"\"\n Provides our --help usage information.\n\n :returns: **str** with our usage information\n \"\"\"\n return stem.interpreter.msg('msg.help', address=DEFAULT_ARGS['control_address'], port=DEFAULT_ARGS['control_port'], socket=DEFAULT_ARGS['control_socket'])", "context": "def get_help(): ...\ndef parse(argv): ...\ndef get_help(): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_get_help", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001007.py"} {"focal_file": "stem/exit_policy.py", "focal_class": "ExitPolicy", "focal_method": "can_exit_to", "tests": "import unittest\n\nclass Test_ExitPolicy_can_exit_to(unittest.TestCase):\n def test_can_exit_to(self):\n policy = ExitPolicy('accept *:80', 'accept *:443', 'reject *:*')\n for index in range(1, 100):\n ip_addr = '%i.%i.%i.%i' % (index / 2, index / 2, index / 2, index / 2)\n expected_result = index in (80, 443)\n self.assertEqual(expected_result, policy.can_exit_to(ip_addr, index))\n self.assertEqual(expected_result, policy.can_exit_to(port=index))\n", "method_code": " def can_exit_to(self, address=None, port=None, strict=False):\n \"\"\"\n Checks if this policy allows exiting to a given destination or not. If the\n address or port is omitted then this will check if we're allowed to exit to\n any instances of the defined address or port.\n \n :param str address: IPv4 or IPv6 address (with or without brackets)\n :param int port: port number\n :param bool strict: if the address or port is excluded then check if we can\n exit to **all** instances of the defined address or port\n \n :returns: **True** if exiting to this destination is allowed, **False** otherwise\n \"\"\"\n if not self.is_exiting_allowed():\n return False\n for rule in self._get_rules():\n if rule.is_match(address, port, strict):\n return rule.is_accept\n return self._is_allowed_default\n ", "context": "class ExitPolicy(object):\n @lru_cache()\n def can_exit_to(self, address=None, port=None, strict=False): ...\n def __init__(self, *rules): ...\n def is_exiting_allowed(self): ...\n def summary(self): ...\n def has_private(self): ...\n def strip_private(self): ...\n def has_default(self): ...\n def strip_default(self): ...\n def _get_rules(self): ...\n def __len__(self): ...\n def __iter__(self): ...\n def __str__(self): ...\n def __hash__(self): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n\n self._rules = None\n self._hash = None\n self._is_allowed_default = True\n", "repository": "illumineinteractive/stem", "test_name": "test_can_exit_to", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001008.py"} {"focal_file": "stem/exit_policy.py", "focal_class": "ExitPolicy", "focal_method": "is_exiting_allowed", "tests": "import unittest\n\nclass Test_ExitPolicy_is_exiting_allowed(unittest.TestCase):\n def test_is_exiting_allowed(self):\n test_inputs = {(): True, ('accept *:*',): True, ('reject *:*',): False, ('accept *:80', 'reject *:*'): True, ('reject *:80', 'accept *:80', 'reject *:*'): False, ('reject *:50-90', 'accept *:80', 'reject *:*'): False, ('reject *:2-65535', 'accept *:80-65535', 'reject *:*'): False, ('reject *:2-65535', 'accept 127.0.0.0:1', 'reject *:*'): True, ('reject 127.0.0.1:*', 'accept *:80', 'reject *:*'): True}\n for rules, expected_result in test_inputs.items():\n policy = ExitPolicy(*rules)\n self.assertEqual(expected_result, policy.is_exiting_allowed())\n", "method_code": " def is_exiting_allowed(self):\n \"\"\"\n Provides **True** if the policy allows exiting whatsoever, **False**\n otherwise.\n \"\"\"\n rejected_ports = set()\n for rule in self._get_rules():\n if rule.is_accept:\n for port in range(rule.min_port, rule.max_port + 1):\n if port not in rejected_ports:\n return True\n elif rule.is_address_wildcard():\n if rule.is_port_wildcard():\n return False\n else:\n rejected_ports.update(range(rule.min_port, rule.max_port + 1))\n return self._is_allowed_default\n ", "context": "class ExitPolicy(object):\n @lru_cache()\n def is_exiting_allowed(self): ...\n def __init__(self, *rules): ...\n def can_exit_to(self, address=None, port=None, strict=False): ...\n def summary(self): ...\n def has_private(self): ...\n def strip_private(self): ...\n def has_default(self): ...\n def strip_default(self): ...\n def _get_rules(self): ...\n def __len__(self): ...\n def __iter__(self): ...\n def __str__(self): ...\n def __hash__(self): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n\n self._rules = None\n self._hash = None\n self._is_allowed_default = True\n", "repository": "illumineinteractive/stem", "test_name": "test_is_exiting_allowed", "smells": [1, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001009.py"} {"focal_file": "stem/exit_policy.py", "focal_class": "ExitPolicy", "focal_method": "get_config_policy", "tests": "import unittest\n\nclass Test_ExitPolicy_get_config_policy(unittest.TestCase):\n def test_all_private_policy(self):\n for port in ('*', '80', '1-1024'):\n private_policy = get_config_policy('reject private:%s' % port, '12.34.56.78')\n for rule in private_policy:\n self.assertTrue(rule.is_private())\n self.assertEqual(ExitPolicy(), private_policy.strip_private())\n private_policy = get_config_policy('accept private:*')\n self.assertEqual(ExitPolicy(), private_policy.strip_private())\n\n def test_mixed_default_policy(self):\n policy = ExitPolicy('accept *:80', 'accept 127.0.0.1:1-65533', *DEFAULT_POLICY_RULES)\n for rule in policy:\n self.assertTrue(rule.is_accept != rule.is_default() or (rule.is_accept and rule.is_address_wildcard() and rule.is_port_wildcard()))\n self.assertEqual(get_config_policy('accept *:80, accept 127.0.0.1:1-65533'), policy.strip_default())\n\n def test_get_config_policy(self):\n test_inputs = {'': ExitPolicy(), 'reject *': ExitPolicy('reject *:*'), 'reject *:*': ExitPolicy('reject *:*'), 'reject private': ExitPolicy('reject 0.0.0.0/8:*', 'reject 169.254.0.0/16:*', 'reject 127.0.0.0/8:*', 'reject 192.168.0.0/16:*', 'reject 10.0.0.0/8:*', 'reject 172.16.0.0/12:*', 'reject 12.34.56.78:*'), 'accept *:80, reject *': ExitPolicy('accept *:80', 'reject *:*'), ' accept *:80, reject * ': ExitPolicy('accept *:80', 'reject *:*')}\n for test_input, expected in test_inputs.items():\n self.assertEqual(expected, get_config_policy(test_input, '12.34.56.78'))\n test_inputs = ('blarg', 'accept *:*:*', 'acceptt *:80', 'accept 257.0.0.1:80', 'accept *:999999')\n for test_input in test_inputs:\n self.assertRaises(ValueError, get_config_policy, test_input)\n", "method_code": "def get_config_policy(rules, ip_address=None):\n \"\"\"\n Converts an ExitPolicy found in a torrc to a proper exit pattern. This\n accounts for...\n\n * ports being optional\n * the 'private' keyword\n\n .. deprecated:: 1.7.0\n\n Tor's torrc parameters lack a formal spec, making it difficult for this\n method to be reliable. Callers are encouraged to move to\n :func:`~stem.control.Controller.get_exit_policy` instead.\n\n :param str,list rules: comma separated rules or list to be converted\n :param str ip_address: this relay's IP address for the 'private' policy if\n it's present, this defaults to the local address\n\n :returns: :class:`~stem.exit_policy.ExitPolicy` reflected by the rules\n\n :raises: **ValueError** if input isn't a valid tor exit policy\n \"\"\"\n if ip_address and (not (stem.util.connection.is_valid_ipv4_address(ip_address) or stem.util.connection.is_valid_ipv6_address(ip_address, allow_brackets=True))):\n raise ValueError(\"%s isn't a valid IP address\" % ip_address)\n elif ip_address and stem.util.connection.is_valid_ipv6_address(ip_address, allow_brackets=True) and (not (ip_address[0] == '[' and ip_address[-1] == ']')):\n ip_address = '[%s]' % ip_address\n if stem.util._is_str(rules):\n rules = rules.split(',')\n result = []\n for rule in rules:\n rule = rule.strip()\n if not rule:\n continue\n if not re.search(':[\\\\d\\\\-\\\\*]+$', rule):\n rule = '%s:*' % rule\n if 'private' in rule:\n acceptance = rule.split(' ', 1)[0]\n port = rule.rsplit(':', 1)[1]\n addresses = list(PRIVATE_ADDRESSES)\n if ip_address:\n addresses.append(ip_address)\n else:\n try:\n addresses.append(socket.gethostbyname(socket.gethostname()))\n except:\n pass\n for private_addr in addresses:\n result.append(ExitPolicyRule('%s %s:%s' % (acceptance, private_addr, port)))\n else:\n result.append(ExitPolicyRule(rule))\n return ExitPolicy(*result)", "context": "def get_config_policy(rules, ip_address=None): ...\ndef get_config_policy(rules, ip_address=None): ...\ndef _flag_private_rules(rules): ...\ndef _flag_default_rules(rules): ...\ndef _address_type_to_int(address_type): ...\ndef _int_to_address_type(address_type_int): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_all_private_policy", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001010.py"} {"focal_file": "stem/exit_policy.py", "focal_class": "ExitPolicy", "focal_method": "is_default", "tests": "import unittest\n\nclass Test_ExitPolicy_is_default(unittest.TestCase):\n def test_all_default_policy(self):\n policy = ExitPolicy(*DEFAULT_POLICY_RULES)\n for rule in policy:\n self.assertTrue(rule.is_default())\n self.assertTrue(policy.has_default())\n self.assertEqual(ExitPolicy(), policy.strip_default())\n", "method_code": " def is_default(self):\n \"\"\"\n Checks if this rule belongs to the default exit policy suffix.\n \n .. versionadded:: 1.3.0\n \n :returns: **True** if this rule was part of the default end of a policy, **False** otherwise.\n \"\"\"\n return self._is_default_suffix\n ", "context": "class ExitPolicyRule(object):\n def is_default(self): ...\n def __init__(self, rule): ...\n def is_address_wildcard(self): ...\n def is_port_wildcard(self): ...\n def is_match(self, address=None, port=None, strict=False): ...\n def get_address_type(self): ...\n def get_mask(self, cache=True): ...\n def get_masked_bits(self): ...\n def is_private(self): ...\n def __str__(self): ...\n def _get_mask_bin(self): ...\n def _get_address_bin(self): ...\n def _apply_addrspec(self, rule, addrspec, is_ipv6_only): ...\n def _apply_portspec(self, rule, portspec): ...\n def __hash__(self): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n\n self.is_accept = rule.startswith('accept')\n self.address = None\n self._address_type = None\n self._masked_bits = None\n self.min_port = self.max_port = None\n self._hash = None\n self._mask = None\n self._skip_rule = False\n self._is_private = False\n self._is_default_suffix = False\n", "repository": "illumineinteractive/stem", "test_name": "test_all_default_policy", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001011.py"} {"focal_file": "stem/exit_policy.py", "focal_class": null, "focal_method": "get_config_policy", "tests": "import unittest\n\nclass Test_get_config_policy(unittest.TestCase):\n def test_mixed_private_policy(self):\n policy = get_config_policy('accept *:80, reject private:1-65533, accept *:*')\n for rule in policy:\n self.assertTrue(rule.is_accept != rule.is_private())\n self.assertEqual(get_config_policy('accept *:80, accept *:*'), policy.strip_private())\n\n def test_get_config_policy_with_ipv6(self):\n self.assertTrue(get_config_policy('reject private:80', 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329').is_exiting_allowed())\n self.assertTrue(get_config_policy('reject private:80', '[fe80:0000:0000:0000:0202:b3ff:fe1e:8329]').is_exiting_allowed())\n", "method_code": "def get_config_policy(rules, ip_address=None):\n \"\"\"\n Converts an ExitPolicy found in a torrc to a proper exit pattern. This\n accounts for...\n\n * ports being optional\n * the 'private' keyword\n\n .. deprecated:: 1.7.0\n\n Tor's torrc parameters lack a formal spec, making it difficult for this\n method to be reliable. Callers are encouraged to move to\n :func:`~stem.control.Controller.get_exit_policy` instead.\n\n :param str,list rules: comma separated rules or list to be converted\n :param str ip_address: this relay's IP address for the 'private' policy if\n it's present, this defaults to the local address\n\n :returns: :class:`~stem.exit_policy.ExitPolicy` reflected by the rules\n\n :raises: **ValueError** if input isn't a valid tor exit policy\n \"\"\"\n if ip_address and (not (stem.util.connection.is_valid_ipv4_address(ip_address) or stem.util.connection.is_valid_ipv6_address(ip_address, allow_brackets=True))):\n raise ValueError(\"%s isn't a valid IP address\" % ip_address)\n elif ip_address and stem.util.connection.is_valid_ipv6_address(ip_address, allow_brackets=True) and (not (ip_address[0] == '[' and ip_address[-1] == ']')):\n ip_address = '[%s]' % ip_address\n if stem.util._is_str(rules):\n rules = rules.split(',')\n result = []\n for rule in rules:\n rule = rule.strip()\n if not rule:\n continue\n if not re.search(':[\\\\d\\\\-\\\\*]+$', rule):\n rule = '%s:*' % rule\n if 'private' in rule:\n acceptance = rule.split(' ', 1)[0]\n port = rule.rsplit(':', 1)[1]\n addresses = list(PRIVATE_ADDRESSES)\n if ip_address:\n addresses.append(ip_address)\n else:\n try:\n addresses.append(socket.gethostbyname(socket.gethostname()))\n except:\n pass\n for private_addr in addresses:\n result.append(ExitPolicyRule('%s %s:%s' % (acceptance, private_addr, port)))\n else:\n result.append(ExitPolicyRule(rule))\n return ExitPolicy(*result)", "context": "def get_config_policy(rules, ip_address=None): ...\ndef get_config_policy(rules, ip_address=None): ...\ndef _flag_private_rules(rules): ...\ndef _flag_default_rules(rules): ...\ndef _address_type_to_int(address_type): ...\ndef _int_to_address_type(address_type_int): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_mixed_private_policy", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001012.py"} {"focal_file": "stem/exit_policy.py", "focal_class": "MicroExitPolicy", "focal_method": "can_exit_to", "tests": "import unittest\n\nclass Test_MicroExitPolicy_can_exit_to(unittest.TestCase):\n def test_microdescriptor_can_exit_to(self):\n test_inputs = {'accept 443': {442: False, 443: True, 444: False}, 'reject 443': {442: True, 443: False, 444: True}, 'accept 80,443': {80: True, 443: True, 10: False}, 'reject 1-1024': {1: False, 1024: False, 1025: True}}\n for policy_arg, attr in test_inputs.items():\n policy = MicroExitPolicy(policy_arg)\n for port, expected_value in attr.items():\n self.assertEqual(expected_value, policy.can_exit_to(port=port))\n policy = MicroExitPolicy('accept 80,443')\n self.assertFalse(policy.can_exit_to('127.0.0.1', 79))\n self.assertTrue(policy.can_exit_to('127.0.0.1', 80))\n", "method_code": " def can_exit_to(self, address=None, port=None, strict=False):\n \"\"\"\n Checks if this policy allows exiting to a given destination or not. If the\n address or port is omitted then this will check if we're allowed to exit to\n any instances of the defined address or port.\n \n :param str address: IPv4 or IPv6 address (with or without brackets)\n :param int port: port number\n :param bool strict: if the address or port is excluded then check if we can\n exit to **all** instances of the defined address or port\n \n :returns: **True** if exiting to this destination is allowed, **False** otherwise\n \"\"\"\n if not self.is_exiting_allowed():\n return False\n for rule in self._get_rules():\n if rule.is_match(address, port, strict):\n return rule.is_accept\n return self._is_allowed_default\n ", "context": "class ExitPolicy(object):\n @lru_cache()\n def can_exit_to(self, address=None, port=None, strict=False): ...\n def __init__(self, *rules): ...\n def is_exiting_allowed(self): ...\n def summary(self): ...\n def has_private(self): ...\n def strip_private(self): ...\n def has_default(self): ...\n def strip_default(self): ...\n def _get_rules(self): ...\n def __len__(self): ...\n def __iter__(self): ...\n def __str__(self): ...\n def __hash__(self): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n\n self._rules = None\n self._hash = None\n self._is_allowed_default = True\n", "repository": "illumineinteractive/stem", "test_name": "test_microdescriptor_can_exit_to", "smells": [1, 0, 0, 0, 1, 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": [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": "stem/exit_policy.py", "focal_class": "ExitPolicyRule", "focal_method": "is_address_wildcard", "tests": "import unittest\n\nclass Test_ExitPolicyRule_is_address_wildcard(unittest.TestCase):\n def test_valid_wildcard(self):\n test_inputs = {'reject *:*': (True, True), 'reject *:80': (True, False), 'accept 192.168.0.1:*': (False, True), 'accept 192.168.0.1:80': (False, False), 'reject *4:*': (False, True), 'reject *6:*': (False, True), 'reject6 *4:*': (False, True), 'reject6 *6:*': (False, True), 'reject 127.0.0.1/0:*': (False, True), 'reject 127.0.0.1/0.0.0.0:*': (False, True), 'reject 127.0.0.1/16:*': (False, True), 'reject 127.0.0.1/32:*': (False, True), 'reject [0000:0000:0000:0000:0000:0000:0000:0000]/0:80': (False, False), 'reject [0000:0000:0000:0000:0000:0000:0000:0000]/64:80': (False, False), 'reject [0000:0000:0000:0000:0000:0000:0000:0000]/128:80': (False, False), 'reject6 *:*': (False, True), 'reject6 *:80': (False, False), 'reject6 [0000:0000:0000:0000:0000:0000:0000:0000]/128:80': (False, False), 'accept 192.168.0.1:0-65535': (False, True), 'accept 192.168.0.1:1-65535': (False, True), 'accept 192.168.0.1:2-65535': (False, False), 'accept 192.168.0.1:1-65534': (False, False)}\n for rule_arg, attr in test_inputs.items():\n is_address_wildcard, is_port_wildcard = attr\n rule = ExitPolicyRule(rule_arg)\n self.assertEqual(is_address_wildcard, rule.is_address_wildcard(), '%s (wildcard expected %s and actually %s)' % (rule_arg, is_address_wildcard, rule.is_address_wildcard()))\n self.assertEqual(is_port_wildcard, rule.is_port_wildcard())\n rule = ExitPolicyRule('reject 127.0.0.1/0:*')\n rule._submask_wildcard = False\n self.assertEqual(False, rule.is_address_wildcard())\n rule = ExitPolicyRule('reject [0000:0000:0000:0000:0000:0000:0000:0000]/0:80')\n rule._submask_wildcard = False\n self.assertEqual(False, rule.is_address_wildcard())\n", "method_code": " def is_address_wildcard(self):\n \"\"\"\n **True** if we'll match against **any** address, **False** otherwise.\n \n Note that this is different than \\\\*4, \\\\*6, or '/0' address which are\n wildcards for only either IPv4 or IPv6.\n \n :returns: **bool** for if our address matching is a wildcard\n \"\"\"\n return self._address_type == _address_type_to_int(AddressType.WILDCARD)\n ", "context": "class ExitPolicyRule(object):\n def is_address_wildcard(self): ...\n def __init__(self, rule): ...\n def is_port_wildcard(self): ...\n def is_match(self, address=None, port=None, strict=False): ...\n def get_address_type(self): ...\n def get_mask(self, cache=True): ...\n def get_masked_bits(self): ...\n def is_private(self): ...\n def is_default(self): ...\n def __str__(self): ...\n def _get_mask_bin(self): ...\n def _get_address_bin(self): ...\n def _apply_addrspec(self, rule, addrspec, is_ipv6_only): ...\n def _apply_portspec(self, rule, portspec): ...\n def __hash__(self): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n\n self.is_accept = rule.startswith('accept')\n self.address = None\n self._address_type = None\n self._masked_bits = None\n self.min_port = self.max_port = None\n self._hash = None\n self._mask = None\n self._skip_rule = False\n self._is_private = False\n self._is_default_suffix = False\n", "repository": "illumineinteractive/stem", "test_name": "test_valid_wildcard", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001014.py"} {"focal_file": "stem/exit_policy.py", "focal_class": "ExitPolicyRule", "focal_method": "is_match", "tests": "import unittest\n\nclass Test_ExitPolicyRule_is_match(unittest.TestCase):\n def test_is_match_wildcard(self):\n test_inputs = {'reject *:*': {('192.168.0.1', 80): True, ('0.0.0.0', 80): True, ('255.255.255.255', 80): True, ('FE80:0000:0000:0000:0202:B3FF:FE1E:8329', 80): True, ('[FE80:0000:0000:0000:0202:B3FF:FE1E:8329]', 80): True, ('192.168.0.1', None): True, (None, 80, False): True, (None, 80, True): True, (None, None, False): True, (None, None, True): True}, 'reject 255.255.255.255/0:*': {('192.168.0.1', 80): True, ('0.0.0.0', 80): True, ('255.255.255.255', 80): True, ('FE80:0000:0000:0000:0202:B3FF:FE1E:8329', 80): False, ('[FE80:0000:0000:0000:0202:B3FF:FE1E:8329]', 80): False, ('192.168.0.1', None): True, (None, 80, False): False, (None, 80, True): True, (None, None, False): False, (None, None, True): True}, 'reject *4:*': {('192.168.0.1', 80): True, ('FE80:0000:0000:0000:0202:B3FF:FE1E:8329', 80): False}, 'reject *6:*': {('192.168.0.1', 80): False, ('FE80:0000:0000:0000:0202:B3FF:FE1E:8329', 80): True}}\n for rule_arg, matches in test_inputs.items():\n rule = ExitPolicyRule(rule_arg)\n rule._submask_wildcard = False\n for match_args, expected_result in matches.items():\n self.assertEqual(expected_result, rule.is_match(*match_args))\n rule = ExitPolicyRule('reject *:*')\n self.assertRaises(ValueError, rule.is_match, '127.0.0.1', 0)\n\n def test_is_match_ipv4(self):\n test_inputs = {'reject 192.168.0.50:*': {('192.168.0.50', 80): True, ('192.168.0.51', 80): False, ('192.168.0.49', 80): False, (None, 80, False): False, (None, 80, True): True, ('192.168.0.50', None): True}, 'reject 0.0.0.0/24:*': {('0.0.0.0', 80): True, ('0.0.0.1', 80): True, ('0.0.0.255', 80): True, ('0.0.1.0', 80): False, ('0.1.0.0', 80): False, ('1.0.0.0', 80): False, (None, 80, False): False, (None, 80, True): True, ('0.0.0.0', None): True}}\n for rule_arg, matches in test_inputs.items():\n rule = ExitPolicyRule(rule_arg)\n for match_args, expected_result in matches.items():\n self.assertEqual(expected_result, rule.is_match(*match_args))\n\n def test_is_match_ipv6(self):\n test_inputs = {'reject [FE80:0000:0000:0000:0202:B3FF:FE1E:8329]:*': {('FE80:0000:0000:0000:0202:B3FF:FE1E:8329', 80): True, ('fe80:0000:0000:0000:0202:b3ff:fe1e:8329', 80): True, ('[FE80:0000:0000:0000:0202:B3FF:FE1E:8329]', 80): True, ('FE80:0000:0000:0000:0202:B3FF:FE1E:8330', 80): False, ('FE80:0000:0000:0000:0202:B3FF:FE1E:8328', 80): False, (None, 80, False): False, (None, 80, True): True, ('FE80:0000:0000:0000:0202:B3FF:FE1E:8329', None): True}, 'reject [FE80:0000:0000:0000:0202:B3FF:FE1E:8329]/112:*': {('FE80:0000:0000:0000:0202:B3FF:FE1E:8329', 80): True, ('FE80:0000:0000:0000:0202:B3FF:FE1E:0000', 80): True, ('FE80:0000:0000:0000:0202:B3FF:FE1E:FFFF', 80): True, ('FE80:0000:0000:0000:0202:B3FF:FE1F:8329', 80): False, ('FE81:0000:0000:0000:0202:B3FF:FE1E:8329', 80): False, (None, 80, False): False, (None, 80, True): True, ('FE80:0000:0000:0000:0202:B3FF:FE1E:8329', None, False): True, ('FE80:0000:0000:0000:0202:B3FF:FE1E:8329', None, True): True}}\n for rule_arg, matches in test_inputs.items():\n rule = ExitPolicyRule(rule_arg)\n for match_args, expected_result in matches.items():\n self.assertEqual(expected_result, rule.is_match(*match_args))\n\n def test_is_match_port(self):\n test_inputs = {'reject *:80': {('192.168.0.50', 80): True, ('192.168.0.50', 81): False, ('192.168.0.50', 79): False, (None, 80): True, ('192.168.0.50', None, False): False, ('192.168.0.50', None, True): True}, 'reject *:80-85': {('192.168.0.50', 79): False, ('192.168.0.50', 80): True, ('192.168.0.50', 83): True, ('192.168.0.50', 85): True, ('192.168.0.50', 86): False, (None, 83): True, ('192.168.0.50', None, False): False, ('192.168.0.50', None, True): True}}\n for rule_arg, matches in test_inputs.items():\n rule = ExitPolicyRule(rule_arg)\n for match_args, expected_result in matches.items():\n self.assertEqual(expected_result, rule.is_match(*match_args))\n", "method_code": " def is_match(self, address=None, port=None, strict=False):\n \"\"\"\n **True** if we match against the given destination, **False** otherwise. If\n the address or port is omitted then this will check if we're allowed to\n exit to any instances of the defined address or port.\n \n :param str address: IPv4 or IPv6 address (with or without brackets)\n :param int port: port number\n :param bool strict: if the address or port is excluded then check if we can\n exit to **all** instances of the defined address or port\n \n :returns: **bool** indicating if we match against this destination\n \n :raises: **ValueError** if provided with a malformed address or port\n \"\"\"\n if self._skip_rule:\n return False\n if address is not None:\n address_type = self.get_address_type()\n if stem.util.connection.is_valid_ipv4_address(address):\n if address_type == AddressType.IPv6:\n return False\n elif stem.util.connection.is_valid_ipv6_address(address, allow_brackets=True):\n if address_type == AddressType.IPv4:\n return False\n address = address.lstrip('[').rstrip(']')\n else:\n raise ValueError(\"'%s' isn't a valid IPv4 or IPv6 address\" % address)\n if port is not None and (not stem.util.connection.is_valid_port(port)):\n raise ValueError(\"'%s' isn't a valid port\" % port)\n fuzzy_match = False\n if not self.is_address_wildcard():\n if address is None:\n fuzzy_match = True\n else:\n comparison_addr_bin = stem.util.connection.address_to_int(address)\n comparison_addr_bin &= self._get_mask_bin()\n if self._get_address_bin() != comparison_addr_bin:\n return False\n if not self.is_port_wildcard():\n if port is None:\n fuzzy_match = True\n elif port < self.min_port or port > self.max_port:\n return False\n if fuzzy_match:\n return strict != self.is_accept\n else:\n return True\n ", "context": "class ExitPolicyRule(object):\n def is_match(self, address=None, port=None, strict=False): ...\n def __init__(self, rule): ...\n def is_address_wildcard(self): ...\n def is_port_wildcard(self): ...\n def get_address_type(self): ...\n def get_mask(self, cache=True): ...\n def get_masked_bits(self): ...\n def is_private(self): ...\n def is_default(self): ...\n def __str__(self): ...\n def _get_mask_bin(self): ...\n def _get_address_bin(self): ...\n def _apply_addrspec(self, rule, addrspec, is_ipv6_only): ...\n def _apply_portspec(self, rule, portspec): ...\n def __hash__(self): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n\n self.is_accept = rule.startswith('accept')\n self.address = None\n self._address_type = None\n self._masked_bits = None\n self.min_port = self.max_port = None\n self._hash = None\n self._mask = None\n self._skip_rule = False\n self._is_private = False\n self._is_default_suffix = False\n", "repository": "illumineinteractive/stem", "test_name": "test_is_match_wildcard", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001015.py"} {"focal_file": "stem/client/datatype.py", "focal_class": null, "focal_method": "pack", "tests": "import unittest\n\nclass Test_pack(unittest.TestCase):\n def test_packing(self):\n cert, content = Certificate.pop(b'\\x02\\x00\\x04\\x00\\x00\\x01\\x01\\x04\\x04aq\\x0f\\x02\\x00\\x00\\x00\\x00')\n self.assertEqual(b'\\x04\\x04aq\\x0f\\x02\\x00\\x00\\x00\\x00', content)\n self.assertEqual(CertType.IDENTITY, cert.type)\n self.assertEqual(2, cert.type_int)\n self.assertEqual(b'\\x00\\x00\\x01\\x01', cert.value)\n self.assertEqual(b'\\x02\\x00\\x04\\x00\\x00\\x01\\x01', cert.pack())\n", "method_code": " def pack(self):\n \"\"\"\n Encodes field into bytes.\n \n :returns: **bytes** that can be communicated over Tor's ORPort\n \n :raises: **ValueError** if incorrect type or size\n \"\"\"\n raise NotImplementedError('Not yet available')\n ", "context": "class Field(object):\n def pack(self): ...\n def unpack(cls, packed): ...\n def pop(packed): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_packing", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001016.py"} {"focal_file": "stem/client/cell.py", "focal_class": null, "focal_method": "by_name", "tests": "import unittest\n\nclass Test_by_name(unittest.TestCase):\n def test_by_name(self):\n cls = Cell.by_name('NETINFO')\n self.assertEqual('NETINFO', cls.NAME)\n self.assertEqual(8, cls.VALUE)\n self.assertEqual(True, cls.IS_FIXED_SIZE)\n self.assertRaises(ValueError, Cell.by_name, 'NOPE')\n self.assertRaises(ValueError, Cell.by_name, 85)\n self.assertRaises(ValueError, Cell.by_name, None)\n", "method_code": " def by_name(name):\n \"\"\"\n Provides cell attributes by its name.\n \n :param str name: cell command to fetch\n \n :raises: **ValueError** if cell type is invalid\n \"\"\"\n for _, cls in inspect.getmembers(sys.modules[__name__]):\n if name == getattr(cls, 'NAME', UNDEFINED):\n return cls\n raise ValueError(\"'%s' isn't a valid cell type\" % name)\n ", "context": "class Cell(object):\n @staticmethod\n def by_name(name): ...\n def __init__(self, unused=b''): ...\n def by_value(value): ...\n def pack(self, link_protocol): ...\n def unpack(content, link_protocol): ...\n def pop(content, link_protocol): ...\n def _pack(cls, link_protocol, payload, unused=b'', circ_id=None): ...\n def _unpack(cls, content, circ_id, link_protocol): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n\n self.unused = unused\n\n NAME = 'UNKNOWN'\n VALUE = -1\n IS_FIXED_SIZE = False\n", "repository": "illumineinteractive/stem", "test_name": "test_by_name", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001017.py"} {"focal_file": "stem/client/cell.py", "focal_class": null, "focal_method": "by_value", "tests": "import unittest\n\nclass Test_by_value(unittest.TestCase):\n def test_by_value(self):\n cls = Cell.by_value(8)\n self.assertEqual('NETINFO', cls.NAME)\n self.assertEqual(8, cls.VALUE)\n self.assertEqual(True, cls.IS_FIXED_SIZE)\n self.assertRaises(ValueError, Cell.by_value, 'NOPE')\n self.assertRaises(ValueError, Cell.by_value, 85)\n self.assertRaises(ValueError, Cell.by_value, None)\n", "method_code": " def by_value(value):\n \"\"\"\n Provides cell attributes by its value.\n \n :param int value: cell value to fetch\n \n :raises: **ValueError** if cell type is invalid\n \"\"\"\n for _, cls in inspect.getmembers(sys.modules[__name__]):\n if value == getattr(cls, 'VALUE', UNDEFINED):\n return cls\n raise ValueError(\"'%s' isn't a valid cell value\" % value)\n ", "context": "class Cell(object):\n @staticmethod\n def by_value(value): ...\n def __init__(self, unused=b''): ...\n def by_name(name): ...\n def pack(self, link_protocol): ...\n def unpack(content, link_protocol): ...\n def pop(content, link_protocol): ...\n def _pack(cls, link_protocol, payload, unused=b'', circ_id=None): ...\n def _unpack(cls, content, circ_id, link_protocol): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n\n self.unused = unused\n\n NAME = 'UNKNOWN'\n VALUE = -1\n IS_FIXED_SIZE = False\n", "repository": "illumineinteractive/stem", "test_name": "test_by_value", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001018.py"} {"focal_file": "stem/client/datatype.py", "focal_class": "Size", "focal_method": "pack", "tests": "import unittest\n\nclass Test_Size_pack(unittest.TestCase):\n def test_pack(self):\n self.assertEqual(b'\\x12', Size.CHAR.pack(18))\n self.assertEqual(b'\\x00\\x12', Size.SHORT.pack(18))\n self.assertEqual(b'\\x00\\x00\\x00\\x12', Size.LONG.pack(18))\n self.assertEqual(b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x12', Size.LONG_LONG.pack(18))\n self.assertRaisesWith(ValueError, 'Size.pack encodes an integer, but was a str', Size.CHAR.pack, 'hi')\n self.assertRaisesWith(ValueError, 'Packed values must be positive (attempted to pack -1 as a CHAR)', Size.CHAR.pack, -1)\n bad_size = Size('BAD_SIZE', 1, '!H')\n self.assertRaisesRegexp(ValueError, re.escape(\"'\\\\x00\\\\x12' is the wrong size for a BAD_SIZE field\"), bad_size.pack, 18)\n", "method_code": " def pack(self):\n \"\"\"\n Encodes field into bytes.\n \n :returns: **bytes** that can be communicated over Tor's ORPort\n \n :raises: **ValueError** if incorrect type or size\n \"\"\"\n raise NotImplementedError('Not yet available')\n ", "context": "class Field(object):\n def pack(self): ...\n def unpack(cls, packed): ...\n def pop(packed): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_pack", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001019.py"} {"focal_file": "stem/client/datatype.py", "focal_class": null, "focal_method": "unpack", "tests": "import unittest\n\nclass Test_unpack(unittest.TestCase):\n def test_unpack(self):\n self.assertEqual(18, Size.CHAR.unpack(b'\\x12'))\n self.assertEqual(18, Size.SHORT.unpack(b'\\x00\\x12'))\n self.assertEqual(18, Size.LONG.unpack(b'\\x00\\x00\\x00\\x12'))\n self.assertEqual(18, Size.LONG_LONG.unpack(b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x12'))\n self.assertEqual(ord('a'), Size.CHAR.unpack(b'a'))\n self.assertEqual(24930, Size.SHORT.unpack(b'ab'))\n self.assertRaisesWith(ValueError, \"'\\\\x00\\\\x12' is the wrong size for a CHAR field\", Size.CHAR.unpack, '\\x00\\x12')\n", "method_code": " def unpack(cls, packed):\n \"\"\"\n Decodes bytes into a field of this type.\n \n :param bytes packed: content to decode\n \n :returns: instance of this class\n \n :raises: **ValueError** if packed data is malformed\n \"\"\"\n unpacked, remainder = cls.pop(packed)\n if remainder:\n raise ValueError('%s is the wrong size for a %s field' % (repr(packed), cls.__name__))\n return unpacked\n ", "context": "class Field(object):\n @classmethod\n def unpack(cls, packed): ...\n def pack(self): ...\n def pop(packed): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_unpack", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001020.py"} {"focal_file": "stem/client/datatype.py", "focal_class": null, "focal_method": "pop", "tests": "import unittest\n\nclass Test_pop(unittest.TestCase):\n def test_pop(self):\n self.assertEqual((18, b''), Size.CHAR.pop(b'\\x12'))\n self.assertEqual((0, b'\\x12'), Size.CHAR.pop(b'\\x00\\x12'))\n self.assertEqual((18, b''), Size.SHORT.pop(b'\\x00\\x12'))\n self.assertRaisesWith(ValueError, \"'' is the wrong size for a CHAR field\", Size.CHAR.pop, '')\n self.assertRaisesWith(ValueError, \"'\\\\x12' is the wrong size for a SHORT field\", Size.SHORT.pop, '\\x12')\n", "method_code": " def pop(packed):\n \"\"\"\n Decodes bytes as this field type, providing it and the remainder.\n \n :param bytes packed: content to decode\n \n :returns: tuple of the form (unpacked, remainder)\n \n :raises: **ValueError** if packed data is malformed\n \"\"\"\n raise NotImplementedError('Not yet available')\n ", "context": "class Field(object):\n @staticmethod\n def pop(packed): ...\n def pack(self): ...\n def unpack(cls, packed): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_pop", "smells": [1, 0, 0, 0, 1, 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": [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": "stem/control.py", "focal_class": null, "focal_method": "event_description", "tests": "import unittest\n\nclass Test_event_description(unittest.TestCase):\n def test_event_description(self):\n self.assertEqual(\"Logging at the debug runlevel. This is low level, high volume information about tor's internals that generally isn't useful to users.\", stem.control.event_description('DEBUG'))\n self.assertEqual('Event emitted every second with the bytes sent and received by tor.', stem.control.event_description('BW'))\n self.assertEqual('Event emitted every second with the bytes sent and received by tor.', stem.control.event_description('bw'))\n\n def test_event_description_includes_all_events(self):\n self.assertEqual(None, stem.control.event_description('NO_SUCH_EVENT'))\n for event in stem.control.EventType:\n self.assertTrue(stem.control.event_description(event) is not None)\n", "method_code": "def event_description(event):\n \"\"\"\n Provides a description for Tor events.\n\n :param str event: the event for which a description is needed\n\n :returns: **str** The event description or **None** if this is an event name\n we don't have a description for\n \"\"\"\n global EVENT_DESCRIPTIONS\n if EVENT_DESCRIPTIONS is None:\n config = stem.util.conf.Config()\n config_path = os.path.join(os.path.dirname(__file__), 'settings.cfg')\n try:\n config.load(config_path)\n EVENT_DESCRIPTIONS = dict([(key.lower()[18:], config.get_value(key)) for key in config.keys() if key.startswith('event.description.')])\n except Exception as exc:\n log.warn(\"BUG: stem failed to load its internal manual information from '%s': %s\" % (config_path, exc))\n return None\n return EVENT_DESCRIPTIONS.get(event.lower())", "context": "def event_description(event): ...\ndef with_default(yields=False): ...\ndef event_description(event): ...\ndef _parse_circ_path(path): ...\ndef _parse_circ_entry(entry): ...\ndef _case_insensitive_lookup(entries, key, default=UNDEFINED): ...\ndef _get_with_timeout(event_queue, timeout, start_time): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_event_description", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001022.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "get_accounting_stats", "tests": "import unittest\n\nclass Test_get_accounting_stats(unittest.TestCase):\n @patch('stem.control.Controller.get_info')\n @patch('time.time', Mock(return_value=1410723598.276578))\n def test_get_accounting_stats(self, get_info_mock):\n \"\"\"\n Exercises the get_accounting_stats() method.\n \"\"\"\n get_info_mock.side_effect = lambda param, **kwargs: {'accounting/enabled': '1', 'accounting/hibernating': 'awake', 'accounting/interval-end': '2014-09-14 19:41:00', 'accounting/bytes': '4837 2050', 'accounting/bytes-left': '102944 7440'}[param]\n expected = stem.control.AccountingStats(1410723598.276578, 'awake', datetime.datetime(2014, 9, 14, 19, 41), 62, 4837, 102944, 107781, 2050, 7440, 9490)\n self.assertEqual(expected, self.controller.get_accounting_stats())\n get_info_mock.side_effect = ControllerError('nope, too bad')\n self.assertRaises(ControllerError, self.controller.get_accounting_stats)\n self.assertEqual('my default', self.controller.get_accounting_stats('my default'))\n", "method_code": " def get_accounting_stats(self, default=UNDEFINED):\n \"\"\"\n get_accounting_stats(default = UNDEFINED)\n \n Provides stats related to our relaying limitations if AccountingMax was set\n in our torrc.\n \n .. versionadded:: 1.3.0\n \n :param object default: response if the query fails\n \n :returns: :class:`~stem.control.AccountingStats` with our accounting stats\n \n :raises: :class:`stem.ControllerError` if unable to determine the listeners\n and no default was provided\n \"\"\"\n if self.get_info('accounting/enabled') != '1':\n raise stem.ControllerError(\"Accounting isn't enabled\")\n retrieved = time.time()\n status = self.get_info('accounting/hibernating')\n interval_end = self.get_info('accounting/interval-end')\n used = self.get_info('accounting/bytes')\n left = self.get_info('accounting/bytes-left')\n interval_end = stem.util.str_tools._parse_timestamp(interval_end)\n used_read, used_written = [int(val) for val in used.split(' ', 1)]\n left_read, left_written = [int(val) for val in left.split(' ', 1)]\n return AccountingStats(retrieved=retrieved, status=status, interval_end=interval_end, time_until_reset=calendar.timegm(interval_end.timetuple()) - int(retrieved), read_bytes=used_read, read_bytes_left=left_read, read_limit=used_read + left_read, written_bytes=used_written, write_bytes_left=left_written, write_limit=used_written + left_written)\n ", "context": "class Controller(BaseController):\n @with_default()\n def get_accounting_stats(self, default=UNDEFINED): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001023.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "_parse_circ_path", "tests": "import unittest\n\nclass Test_parse_circ_path(unittest.TestCase):\n def test_parse_circ_path(self):\n \"\"\"\n Exercises the _parse_circ_path() helper function.\n \"\"\"\n self.assertEqual([], _parse_circ_path(None))\n self.assertEqual([], _parse_circ_path(''))\n pydoc_examples = {'$999A226EBED397F331B612FE1E4CFAE5C1F201BA=piyaz': [('999A226EBED397F331B612FE1E4CFAE5C1F201BA', 'piyaz')], '$E57A476CD4DFBD99B4EE52A100A58610AD6E80B9,hamburgerphone,PrivacyRepublic14': [('E57A476CD4DFBD99B4EE52A100A58610AD6E80B9', None), (None, 'hamburgerphone'), (None, 'PrivacyRepublic14')]}\n for test_input, expected in pydoc_examples.items():\n self.assertEqual(expected, _parse_circ_path(test_input))\n malformed_inputs = ['=piyaz', '999A226EBED397F331B612FE1E4CFAE5C1F201BA=piyaz', '$999A226EBED397F331B612FE1E4CFAE5C1F201BAA=piyaz', '$999A226EBED397F331B612FE1E4CFAE5C1F201B=piyaz', '$999A226EBED397F331B612FE1E4CFAE5C1F201Bz=piyaz', '$999A226EBED397F331B612FE1E4CFAE5C1F201BA=']\n for test_input in malformed_inputs:\n self.assertRaises(ProtocolError, _parse_circ_path, test_input)\n", "method_code": "def _parse_circ_path(path):\n \"\"\"\n Parses a circuit path as a list of **(fingerprint, nickname)** tuples. Tor\n circuit paths are defined as being of the form...\n\n ::\n\n Path = LongName *(\",\" LongName)\n LongName = Fingerprint [ ( \"=\" / \"~\" ) Nickname ]\n\n example:\n $999A226EBED397F331B612FE1E4CFAE5C1F201BA=piyaz\n\n ... *unless* this is prior to tor version 0.2.2.1 with the VERBOSE_NAMES\n feature turned off (or before version 0.1.2.2 where the feature was\n introduced). In that case either the fingerprint or nickname in the tuple\n will be **None**, depending on which is missing.\n\n ::\n\n Path = ServerID *(\",\" ServerID)\n ServerID = Nickname / Fingerprint\n\n example:\n $E57A476CD4DFBD99B4EE52A100A58610AD6E80B9,hamburgerphone,PrivacyRepublic14\n\n :param str path: circuit path to be parsed\n\n :returns: list of **(fingerprint, nickname)** tuples, fingerprints do not have a proceeding '$'\n\n :raises: :class:`stem.ProtocolError` if the path is malformed\n \"\"\"\n if path:\n try:\n return [_parse_circ_entry(entry) for entry in path.split(',')]\n except stem.ProtocolError as exc:\n raise stem.ProtocolError('%s: %s' % (exc, path))\n else:\n return []", "context": "def _parse_circ_path(path): ...\ndef with_default(yields=False): ...\ndef event_description(event): ...\ndef _parse_circ_path(path): ...\ndef _parse_circ_entry(entry): ...\ndef _case_insensitive_lookup(entries, key, default=UNDEFINED): ...\ndef _get_with_timeout(event_queue, timeout, start_time): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_parse_circ_path", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001024.py"} {"focal_file": "stem/control.py", "focal_class": null, "focal_method": "get_effective_rate", "tests": "import unittest\n\nclass Test_get_effective_rate(unittest.TestCase):\n @patch('stem.control.Controller.get_conf')\n def test_get_effective_rate(self, get_conf_mock):\n \"\"\"\n Exercise the get_effective_rate() method.\n \"\"\"\n get_conf_mock.side_effect = lambda param, **kwargs: {'BandwidthRate': '1073741824', 'BandwidthBurst': '1073741824', 'RelayBandwidthRate': '0', 'RelayBandwidthBurst': '0', 'MaxAdvertisedBandwidth': '1073741824'}[param]\n self.assertEqual(1073741824, self.controller.get_effective_rate())\n self.assertEqual(1073741824, self.controller.get_effective_rate(burst=True))\n get_conf_mock.side_effect = ControllerError('nope, too bad')\n self.assertRaises(ControllerError, self.controller.get_effective_rate)\n self.assertEqual('my_default', self.controller.get_effective_rate('my_default'))\n", "method_code": " def get_effective_rate(self, default=UNDEFINED, burst=False):\n \"\"\"\n get_effective_rate(default = UNDEFINED, burst = False)\n \n Provides the maximum rate this relay is configured to relay in bytes per\n second. This is based on multiple torrc parameters if they're set...\n \n * Effective Rate = min(BandwidthRate, RelayBandwidthRate, MaxAdvertisedBandwidth)\n * Effective Burst = min(BandwidthBurst, RelayBandwidthBurst)\n \n .. versionadded:: 1.3.0\n \n :param object default: response if the query fails\n :param bool burst: provides the burst bandwidth, otherwise this provides\n the standard rate\n \n :returns: **int** with the effective bandwidth rate in bytes per second\n \n :raises: :class:`stem.ControllerError` if the call fails and no default was\n provided\n \"\"\"\n if not burst:\n attributes = ('BandwidthRate', 'RelayBandwidthRate', 'MaxAdvertisedBandwidth')\n else:\n attributes = ('BandwidthBurst', 'RelayBandwidthBurst')\n value = None\n for attr in attributes:\n attr_value = int(self.get_conf(attr))\n if attr_value == 0 and attr.startswith('Relay'):\n continue\n value = min(value, attr_value) if value else attr_value\n return value\n ", "context": "class Controller(BaseController):\n @with_default()\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def drop_guards(self): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [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": "stem/control.py", "focal_class": null, "focal_method": "drop_guards", "tests": "import unittest\n\nclass Test_drop_guards(unittest.TestCase):\n @patch('stem.control.Controller.get_version')\n def test_drop_guards(self, get_version_mock):\n \"\"\"\n Exercises the drop_guards() method.\n \"\"\"\n get_version_mock.return_value = stem.version.Version('0.1.0.14')\n self.assertRaises(UnsatisfiableRequest, self.controller.drop_guards)\n with patch('stem.control.Controller.msg', Mock(return_value=None)):\n get_version_mock.return_value = stem.version.Version('0.2.5.2')\n self.controller.drop_guards()\n", "method_code": " def drop_guards(self):\n \"\"\"\n Drops our present guard nodes and picks a new set.\n \n .. versionadded:: 1.2.0\n \n :raises: :class:`stem.ControllerError` if Tor couldn't fulfill the request\n \"\"\"\n if self.get_version() < stem.version.Requirement.DROPGUARDS:\n raise stem.UnsatisfiableRequest(message='DROPGUARDS was added in tor version %s' % stem.version.Requirement.DROPGUARDS)\n self.msg('DROPGUARDS')\n ", "context": "class Controller(BaseController):\n def drop_guards(self): ...\n def from_port(address='127.0.0.1', port='default'): ...\n def from_socket_file(path='/var/run/tor/control'): ...\n def __init__(self, control_socket, is_authenticated=False): ...\n def close(self): ...\n def authenticate(self, *args, **kwargs): ...\n def reconnect(self, *args, **kwargs): ...\n def get_info(self, params, default=UNDEFINED, get_bytes=False): ...\n def get_version(self, default=UNDEFINED): ...\n def get_exit_policy(self, default=UNDEFINED): ...\n def get_ports(self, listener_type, default=UNDEFINED): ...\n def get_listeners(self, listener_type, default=UNDEFINED): ...\n def get_accounting_stats(self, default=UNDEFINED): ...\n def get_socks_listeners(self, default=UNDEFINED): ...\n def get_protocolinfo(self, default=UNDEFINED): ...\n def get_user(self, default=UNDEFINED): ...\n def get_pid(self, default=UNDEFINED): ...\n def get_start_time(self, default=UNDEFINED): ...\n def get_uptime(self, default=UNDEFINED): ...\n def is_user_traffic_allowed(self): ...\n def get_microdescriptor(self, relay=None, default=UNDEFINED): ...\n def get_microdescriptors(self, default=UNDEFINED): ...\n def get_server_descriptor(self, relay=None, default=UNDEFINED): ...\n def get_server_descriptors(self, default=UNDEFINED): ...\n def _is_server_descriptors_available(self): ...\n def get_network_status(self, relay=None, default=UNDEFINED): ...\n def get_network_statuses(self, default=UNDEFINED): ...\n def get_hidden_service_descriptor(self, address, default=UNDEFINED, servers=None, await_result=True, timeout=None): ...\n def get_conf(self, param, default=UNDEFINED, multiple=False): ...\n def get_conf_map(self, params, default=UNDEFINED, multiple=True): ...\n def _get_conf_dict_to_response(self, config_dict, default, multiple): ...\n def is_set(self, param, default=UNDEFINED): ...\n def _get_custom_options(self): ...\n def set_conf(self, param, value): ...\n def reset_conf(self, *params): ...\n def set_options(self, params, reset=False): ...\n def get_hidden_service_conf(self, default=UNDEFINED): ...\n def set_hidden_service_conf(self, conf): ...\n def create_hidden_service(self, path, port, target_address=None, target_port=None, auth_type=None, client_names=None): ...\n def remove_hidden_service(self, path, port=None): ...\n def list_ephemeral_hidden_services(self, default=UNDEFINED, our_services=True, detached=False): ...\n def create_ephemeral_hidden_service(self, ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None): ...\n def remove_ephemeral_hidden_service(self, service_id): ...\n def add_event_listener(self, listener, *events): ...\n def remove_event_listener(self, listener): ...\n def _get_cache(self, param, namespace=None): ...\n def _get_cache_map(self, params, namespace=None): ...\n def _set_cache(self, params, namespace=None): ...\n def _confchanged_cache_invalidation(self, params): ...\n def is_caching_enabled(self): ...\n def set_caching(self, enabled): ...\n def clear_cache(self): ...\n def load_conf(self, configtext): ...\n def save_conf(self, force=False): ...\n def is_feature_enabled(self, feature): ...\n def enable_feature(self, features): ...\n def get_circuit(self, circuit_id, default=UNDEFINED): ...\n def get_circuits(self, default=UNDEFINED): ...\n def new_circuit(self, path=None, purpose='general', await_build=False, timeout=None): ...\n def extend_circuit(self, circuit_id='0', path=None, purpose='general', await_build=False, timeout=None): ...\n def repurpose_circuit(self, circuit_id, purpose): ...\n def close_circuit(self, circuit_id, flag=''): ...\n def get_streams(self, default=UNDEFINED): ...\n def attach_stream(self, stream_id, circuit_id, exiting_hop=None): ...\n def close_stream(self, stream_id, reason=stem.RelayEndReason.MISC, flag=''): ...\n def signal(self, signal): ...\n def is_newnym_available(self): ...\n def get_newnym_wait(self): ...\n def get_effective_rate(self, default=UNDEFINED, burst=False): ...\n def is_geoip_unavailable(self): ...\n def map_address(self, mapping): ...\n def _post_authentication(self): ...\n def _handle_event(self, event_message): ...\n def _attach_listeners(self): ...\n\n self._is_caching_enabled = True\n self._request_cache = {}\n self._last_newnym = 0.0\n self._cache_lock = threading.RLock()\n self._event_listeners = {}\n self._event_listeners_lock = threading.RLock()\n self._enabled_features = []\n self._is_geoip_unavailable = None\n self._last_address_exc = None\n self._last_fingerprint_exc = None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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_001026.py"} {"focal_file": "stem/directory.py", "focal_class": null, "focal_method": "from_cache", "tests": "import unittest\n\nclass Test_from_cache(unittest.TestCase):\n def test_from_cache(self):\n authorities = stem.directory.Authority.from_cache()\n self.assertTrue(len(authorities) > 4)\n self.assertEqual('128.31.0.39', authorities['moria1'].address)\n", "method_code": " def from_cache():\n \"\"\"\n Provides cached Tor directory information. This information is hardcoded\n into Tor and occasionally changes, so the information provided by this\n method may not necessarily match the latest version of tor.\n \n .. versionadded:: 1.5.0\n \n .. versionchanged:: 1.7.0\n Support added to the :class:`~stem.directory.Authority` class.\n \n :returns: **dict** of **str** identifiers to\n :class:`~stem.directory.Directory` instances\n \"\"\"\n raise NotImplementedError('Unsupported Operation: this should be implemented by the Directory subclass')\n ", "context": "class Directory(object):\n @staticmethod\n def from_cache(): ...\n def __init__(self, address, or_port, dir_port, fingerprint, nickname, orport_v6): ...\n def from_remote(timeout=60): ...\n def __hash__(self): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n\n self.address = address\n self.or_port = int(or_port)\n self.dir_port = int(dir_port)\n self.fingerprint = fingerprint\n self.nickname = nickname\n self.orport_v6 = (orport_v6[0], int(orport_v6[1])) if orport_v6 else None\n", "repository": "illumineinteractive/stem", "test_name": "test_from_cache", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001027.py"} {"focal_file": "stem/directory.py", "focal_class": null, "focal_method": "from_remote", "tests": "import unittest\n\nclass Test_from_remote(unittest.TestCase):\n @patch(URL_OPEN, Mock(return_value=io.BytesIO(AUTHORITY_GITWEB_CONTENT)))\n def test_from_remote(self):\n expected = {'moria1': stem.directory.Authority(nickname='moria1', address='128.31.0.39', or_port=9101, dir_port=9131, fingerprint='9695DFC35FFEB861329B9F1AB04C46397020CE31', v3ident='D586D18309DED4CD6D57C18FDB97EFA96D330566'), 'tor26': stem.directory.Authority(nickname='tor26', address='86.59.21.38', or_port=443, dir_port=80, fingerprint='847B1F850344D7876491A54892F904934E4EB85D', orport_v6=('2001:858:2:2:aabb:0:563b:1526', 443), v3ident='14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4')}\n self.assertEqual(expected, stem.directory.Authority.from_remote())\n", "method_code": " def from_remote(timeout=60):\n \"\"\"\n Reads and parses tor's directory data `from gitweb.torproject.org `_.\n Note that while convenient, this reliance on GitWeb means you should alway\n call with a fallback, such as...\n \n ::\n \n try:\n authorities = stem.directory.Authority.from_remote()\n except IOError:\n authorities = stem.directory.Authority.from_cache()\n \n .. versionadded:: 1.5.0\n \n .. versionchanged:: 1.7.0\n Support added to the :class:`~stem.directory.Authority` class.\n \n :param int timeout: seconds to wait before timing out the request\n \n :returns: **dict** of **str** identifiers to their\n :class:`~stem.directory.Directory`\n \n :raises: **IOError** if unable to retrieve the fallback directories\n \"\"\"\n raise NotImplementedError('Unsupported Operation: this should be implemented by the Directory subclass')\n ", "context": "class Directory(object):\n @staticmethod\n def from_remote(timeout=60): ...\n def __init__(self, address, or_port, dir_port, fingerprint, nickname, orport_v6): ...\n def from_cache(): ...\n def __hash__(self): ...\n def __eq__(self, other): ...\n def __ne__(self, other): ...\n\n self.address = address\n self.or_port = int(or_port)\n self.dir_port = int(dir_port)\n self.fingerprint = fingerprint\n self.nickname = nickname\n self.orport_v6 = (orport_v6[0], int(orport_v6[1])) if orport_v6 else None\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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_001028.py"} {"focal_file": "stem/util/__init__.py", "focal_class": null, "focal_method": "datetime_to_unix", "tests": "import unittest\n\nclass Test_datetime_to_unix(unittest.TestCase):\n def test_datetime_to_unix(self):\n self.assertEqual(1344251971.0, datetime_to_unix(datetime.datetime(2012, 8, 6, 11, 19, 31)))\n self.assertEqual(1515894416.0, datetime_to_unix(datetime.datetime(2018, 1, 14, 1, 46, 56)))\n self.assertTrue(time.time() - datetime_to_unix(datetime.datetime.utcnow()) < 2)\n", "method_code": "def datetime_to_unix(timestamp):\n \"\"\"\n Converts a utc datetime object to a unix timestamp.\n\n .. versionadded:: 1.5.0\n\n :param datetime timestamp: timestamp to be converted\n\n :returns: **float** for the unix timestamp of the given datetime object\n \"\"\"\n if stem.prereq._is_python_26():\n delta = timestamp - datetime.datetime(1970, 1, 1)\n return delta.days * 86400 + delta.seconds\n else:\n return (timestamp - datetime.datetime(1970, 1, 1)).total_seconds()", "context": "def datetime_to_unix(timestamp): ...\ndef _hash_value(val): ...\ndef _is_str(val): ...\ndef _is_int(val): ...\ndef datetime_to_unix(timestamp): ...\ndef _hash_attr(obj, *attributes, **kwargs): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_datetime_to_unix", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001029.py"} {"focal_file": "stem/util/tor_tools.py", "focal_class": null, "focal_method": "is_valid_fingerprint", "tests": "import unittest\n\nclass Test_is_valid_fingerprint(unittest.TestCase):\n def test_is_valid_fingerprint(self):\n \"\"\"\n Checks the is_valid_fingerprint function.\n \"\"\"\n valid_fingerprints = ('$A7569A83B5706AB1B1A9CB52EFF7D2D32E4553EB', '$a7569a83b5706ab1b1a9cb52eff7d2d32e4553eb', stem.util.str_tools._to_bytes('$A7569A83B5706AB1B1A9CB52EFF7D2D32E4553EB'), stem.util.str_tools._to_unicode('$A7569A83B5706AB1B1A9CB52EFF7D2D32E4553EB'))\n invalid_fingerprints = (None, '', 5, ['A7569A83B5706AB1B1A9CB52EFF7D2D32E4553EB'], 'A7569A83B5706AB1B1A9CB52EFF7D2D32E4553EB', '$A7569A83B5706AB1B1A9CB52EFF7D2D32E4553E', '$A7569A83B5706AB1B1A9CB52EFF7D2D32E4553E33', '$A7569A83B5706AB1B1A9CB52EFF7D2D32E4553EG')\n for fingerprint in valid_fingerprints:\n self.assertTrue(stem.util.tor_tools.is_valid_fingerprint(fingerprint, True))\n for fingerprint in invalid_fingerprints:\n self.assertFalse(stem.util.tor_tools.is_valid_fingerprint(fingerprint, True))\n", "method_code": "def is_valid_fingerprint(entry, check_prefix=False):\n \"\"\"\n Checks if a string is a properly formatted relay fingerprint. This checks for\n a '$' prefix if check_prefix is true, otherwise this only validates the hex\n digits.\n\n :param str entry: string to be checked\n :param bool check_prefix: checks for a '$' prefix\n\n :returns: **True** if the string could be a relay fingerprint, **False** otherwise\n \"\"\"\n if isinstance(entry, bytes):\n entry = stem.util.str_tools._to_unicode(entry)\n try:\n if check_prefix:\n if not entry or entry[0] != '$':\n return False\n entry = entry[1:]\n return is_hex_digits(entry, 40)\n except TypeError:\n return False", "context": "def is_valid_fingerprint(entry, check_prefix=False): ...\ndef is_valid_fingerprint(entry, check_prefix=False): ...\ndef is_valid_nickname(entry): ...\ndef is_valid_circuit_id(entry): ...\ndef is_valid_stream_id(entry): ...\ndef is_valid_connection_id(entry): ...\ndef is_valid_hidden_service_address(entry): ...\ndef is_hex_digits(entry, count): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_is_valid_fingerprint", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001030.py"} {"focal_file": "stem/util/tor_tools.py", "focal_class": null, "focal_method": "is_valid_nickname", "tests": "import unittest\n\nclass Test_is_valid_nickname(unittest.TestCase):\n def test_is_valid_nickname(self):\n \"\"\"\n Checks the is_valid_nickname function.\n \"\"\"\n valid_nicknames = ('caerSidi', 'a', 'abcABC123', stem.util.str_tools._to_bytes('caerSidi'), stem.util.str_tools._to_unicode('caerSidi'))\n invalid_nicknames = (None, '', 5, 'toolongggggggggggggg', 'bad_character')\n for nickname in valid_nicknames:\n self.assertTrue(stem.util.tor_tools.is_valid_nickname(nickname))\n for nickname in invalid_nicknames:\n self.assertFalse(stem.util.tor_tools.is_valid_nickname(nickname))\n", "method_code": "def is_valid_nickname(entry):\n \"\"\"\n Checks if a string is a valid format for being a nickname.\n\n :param str entry: string to be checked\n\n :returns: **True** if the string could be a nickname, **False** otherwise\n \"\"\"\n if isinstance(entry, bytes):\n entry = stem.util.str_tools._to_unicode(entry)\n try:\n return bool(NICKNAME_PATTERN.match(entry))\n except TypeError:\n return False", "context": "def is_valid_nickname(entry): ...\ndef is_valid_fingerprint(entry, check_prefix=False): ...\ndef is_valid_nickname(entry): ...\ndef is_valid_circuit_id(entry): ...\ndef is_valid_stream_id(entry): ...\ndef is_valid_connection_id(entry): ...\ndef is_valid_hidden_service_address(entry): ...\ndef is_hex_digits(entry, count): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_is_valid_nickname", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001031.py"} {"focal_file": "stem/util/tor_tools.py", "focal_class": null, "focal_method": "is_valid_circuit_id", "tests": "import unittest\n\nclass Test_is_valid_circuit_id(unittest.TestCase):\n def test_is_valid_circuit_id(self):\n \"\"\"\n Checks the is_valid_circuit_id function.\n \"\"\"\n valid_circuit_ids = ('0', '2', 'abcABC123', stem.util.str_tools._to_bytes('2'), stem.util.str_tools._to_unicode('2'))\n invalid_circuit_ids = (None, '', 0, 2, 'toolonggggggggggg', 'bad_character')\n for circuit_id in valid_circuit_ids:\n self.assertTrue(stem.util.tor_tools.is_valid_circuit_id(circuit_id))\n for circuit_id in invalid_circuit_ids:\n self.assertFalse(stem.util.tor_tools.is_valid_circuit_id(circuit_id))\n", "method_code": "def is_valid_circuit_id(entry):\n \"\"\"\n Checks if a string is a valid format for being a circuit identifier.\n\n :returns: **True** if the string could be a circuit id, **False** otherwise\n \"\"\"\n if isinstance(entry, bytes):\n entry = stem.util.str_tools._to_unicode(entry)\n try:\n return bool(CIRC_ID_PATTERN.match(entry))\n except TypeError:\n return False", "context": "def is_valid_circuit_id(entry): ...\ndef is_valid_fingerprint(entry, check_prefix=False): ...\ndef is_valid_nickname(entry): ...\ndef is_valid_circuit_id(entry): ...\ndef is_valid_stream_id(entry): ...\ndef is_valid_connection_id(entry): ...\ndef is_valid_hidden_service_address(entry): ...\ndef is_hex_digits(entry, count): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_is_valid_circuit_id", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001032.py"} {"focal_file": "stem/util/tor_tools.py", "focal_class": null, "focal_method": "is_hex_digits", "tests": "import unittest\n\nclass Test_is_hex_digits(unittest.TestCase):\n def test_is_valid_hex_digits(self):\n \"\"\"\n Checks the is_valid_hex_digits function.\n \"\"\"\n valid_hex_digits = ('12345', 'AbCdE', stem.util.str_tools._to_bytes('AbCdE'), stem.util.str_tools._to_unicode('AbCdE'))\n invalid_hex_digits = (None, '', 5, 'X', '1234', 'ABCDEF', [1, '2', (3, 4)])\n for hex_digits in valid_hex_digits:\n self.assertTrue(stem.util.tor_tools.is_hex_digits(hex_digits, 5))\n for hex_digits in invalid_hex_digits:\n self.assertFalse(stem.util.tor_tools.is_hex_digits(hex_digits, 5))\n", "method_code": "def is_hex_digits(entry, count):\n \"\"\"\n Checks if a string is the given number of hex digits. Digits represented by\n letters are case insensitive.\n\n :param str entry: string to be checked\n :param int count: number of hex digits to be checked for\n\n :returns: **True** if the given number of hex digits, **False** otherwise\n \"\"\"\n try:\n if len(entry) != count:\n return False\n int(entry, 16)\n return True\n except (ValueError, TypeError):\n return False", "context": "def is_hex_digits(entry, count): ...\ndef is_valid_fingerprint(entry, check_prefix=False): ...\ndef is_valid_nickname(entry): ...\ndef is_valid_circuit_id(entry): ...\ndef is_valid_stream_id(entry): ...\ndef is_valid_connection_id(entry): ...\ndef is_valid_hidden_service_address(entry): ...\ndef is_hex_digits(entry, count): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_is_valid_hex_digits", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001033.py"} {"focal_file": "stem/util/connection.py", "focal_class": null, "focal_method": "system_resolvers", "tests": "import unittest\n\nclass Test_system_resolvers(unittest.TestCase):\n @patch('os.access')\n @patch('stem.util.system.is_available')\n @patch('stem.util.proc.is_available')\n def test_system_resolvers(self, proc_mock, is_available_mock, os_mock):\n \"\"\"\n Checks the system_resolvers function.\n \"\"\"\n is_available_mock.return_value = True\n proc_mock.return_value = False\n os_mock.return_value = True\n self.assertEqual([Resolver.NETSTAT_WINDOWS], stem.util.connection.system_resolvers('Windows'))\n self.assertEqual([Resolver.LSOF], stem.util.connection.system_resolvers('Darwin'))\n self.assertEqual([Resolver.BSD_FSTAT], stem.util.connection.system_resolvers('OpenBSD'))\n self.assertEqual([Resolver.BSD_SOCKSTAT, Resolver.BSD_PROCSTAT, Resolver.LSOF], stem.util.connection.system_resolvers('FreeBSD'))\n self.assertEqual([Resolver.NETSTAT, Resolver.SOCKSTAT, Resolver.LSOF, Resolver.SS], stem.util.connection.system_resolvers('Linux'))\n proc_mock.return_value = True\n self.assertEqual([Resolver.PROC, Resolver.NETSTAT, Resolver.SOCKSTAT, Resolver.LSOF, Resolver.SS], stem.util.connection.system_resolvers('Linux'))\n self.assertEqual(stem.util.connection.system_resolvers(platform.system()), stem.util.connection.system_resolvers())\n is_available_mock.return_value = False\n self.assertEqual([Resolver.PROC], stem.util.connection.system_resolvers('Linux'))\n", "method_code": "def system_resolvers(system=None):\n \"\"\"\n Provides the types of connection resolvers likely to be available on this platform.\n\n .. versionadded:: 1.1.0\n\n .. versionchanged:: 1.3.0\n Renamed from get_system_resolvers() to system_resolvers(). The old name\n still works as an alias, but will be dropped in Stem version 2.0.0.\n\n :param str system: system to get resolvers for, this is determined by\n platform.system() if not provided\n\n :returns: **list** of :data:`~stem.util.connection.Resolver` instances available on this platform\n \"\"\"\n if system is None:\n if stem.util.system.is_gentoo():\n system = 'Gentoo'\n else:\n system = platform.system()\n if system == 'Windows':\n resolvers = [Resolver.NETSTAT_WINDOWS]\n elif system == 'Darwin':\n resolvers = [Resolver.LSOF]\n elif system == 'OpenBSD':\n resolvers = [Resolver.BSD_FSTAT]\n elif system == 'FreeBSD':\n resolvers = [Resolver.BSD_SOCKSTAT, Resolver.BSD_PROCSTAT, Resolver.LSOF]\n else:\n resolvers = [Resolver.NETSTAT, Resolver.SOCKSTAT, Resolver.LSOF, Resolver.SS]\n resolvers = [r for r in resolvers if stem.util.system.is_available(RESOLVER_COMMAND[r])]\n if stem.util.proc.is_available() and os.access('/proc/net/tcp', os.R_OK) and os.access('/proc/net/udp', os.R_OK):\n resolvers = [Resolver.PROC] + resolvers\n return resolvers", "context": "def system_resolvers(system=None): ...\ndef get_connections(resolver=None, process_pid=None, process_name=None): ...\ndef system_resolvers(system=None): ...\ndef port_usage(port): ...\ndef is_valid_ipv4_address(address): ...\ndef is_valid_ipv6_address(address, allow_brackets=False): ...\ndef is_valid_port(entry, allow_zero=False): ...\ndef is_private_address(address): ...\ndef address_to_int(address): ...\ndef expand_ipv6_address(address): ...\ndef get_mask_ipv4(bits): ...\ndef get_mask_ipv6(bits): ...\ndef _get_masked_bits(mask): ...\ndef _get_binary(value, bits): ...\ndef _address_to_binary(address): ...\ndef _hmac_sha256(key, msg): ...\ndef _cryptovariables_equal(x, y): ...\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001034.py"} {"focal_file": "stem/util/connection.py", "focal_class": null, "focal_method": "port_usage", "tests": "import unittest\n\nclass Test_port_usage(unittest.TestCase):\n def test_port_usage(self):\n \"\"\"\n Check that port_usage can load our config and provide the expected results.\n \"\"\"\n self.assertEqual('HTTP', stem.util.connection.port_usage(80))\n self.assertEqual('HTTP', stem.util.connection.port_usage('80'))\n self.assertEqual('BitTorrent', stem.util.connection.port_usage(6881))\n self.assertEqual('BitTorrent', stem.util.connection.port_usage(6999))\n self.assertEqual(None, stem.util.connection.port_usage(30000))\n", "method_code": "def port_usage(port):\n \"\"\"\n Provides the common use of a given port. For example, 'HTTP' for port 80 or\n 'SSH' for 22.\n\n .. versionadded:: 1.2.0\n\n :param int port: port number to look up\n\n :returns: **str** with a description for the port, **None** if none is known\n \"\"\"\n global PORT_USES\n if PORT_USES is None:\n config = conf.Config()\n config_path = os.path.join(os.path.dirname(__file__), 'ports.cfg')\n try:\n config.load(config_path)\n port_uses = {}\n for key, value in config.get('port', {}).items():\n if key.isdigit():\n port_uses[int(key)] = value\n elif '-' in key:\n min_port, max_port = key.split('-', 1)\n for port_entry in range(int(min_port), int(max_port) + 1):\n port_uses[port_entry] = value\n else:\n raise ValueError(\"'%s' is an invalid key\" % key)\n PORT_USES = port_uses\n except Exception as exc:\n log.warn(\"BUG: stem failed to load its internal port descriptions from '%s': %s\" % (config_path, exc))\n if not PORT_USES:\n return None\n if isinstance(port, str) and port.isdigit():\n port = int(port)\n return PORT_USES.get(port)", "context": "def port_usage(port): ...\ndef get_connections(resolver=None, process_pid=None, process_name=None): ...\ndef system_resolvers(system=None): ...\ndef port_usage(port): ...\ndef is_valid_ipv4_address(address): ...\ndef is_valid_ipv6_address(address, allow_brackets=False): ...\ndef is_valid_port(entry, allow_zero=False): ...\ndef is_private_address(address): ...\ndef address_to_int(address): ...\ndef expand_ipv6_address(address): ...\ndef get_mask_ipv4(bits): ...\ndef get_mask_ipv6(bits): ...\ndef _get_masked_bits(mask): ...\ndef _get_binary(value, bits): ...\ndef _address_to_binary(address): ...\ndef _hmac_sha256(key, msg): ...\ndef _cryptovariables_equal(x, y): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_port_usage", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001035.py"} {"focal_file": "stem/util/connection.py", "focal_class": "Connection", "focal_method": "get_connections", "tests": "import unittest\n\nclass Test_Connection_get_connections(unittest.TestCase):\n @patch('stem.util.proc.connections')\n def test_get_connections_by_proc(self, proc_mock):\n \"\"\"\n Checks the get_connections function with the proc resolver.\n \"\"\"\n proc_mock.return_value = [('17.17.17.17', 4369, '34.34.34.34', 8738, 'tcp', False), ('187.187.187.187', 48059, '204.204.204.204', 52428, 'tcp', False)]\n expected = [Connection('17.17.17.17', 4369, '34.34.34.34', 8738, 'tcp', False), Connection('187.187.187.187', 48059, '204.204.204.204', 52428, 'tcp', False)]\n self.assertEqual(expected, stem.util.connection.get_connections(Resolver.PROC, process_pid=1111))\n proc_mock.side_effect = IOError('No connections for you!')\n self.assertRaises(IOError, stem.util.connection.get_connections, Resolver.PROC, process_pid=1111)\n\n @patch('stem.util.system.call')\n def test_get_connections_by_netstat(self, call_mock):\n \"\"\"\n Checks the get_connections function with the netstat resolver.\n \"\"\"\n call_mock.return_value = NETSTAT_OUTPUT.split('\\n')\n expected = [Connection('192.168.0.1', 44284, '38.229.79.2', 443, 'tcp', False)]\n self.assertEqual(expected, stem.util.connection.get_connections(Resolver.NETSTAT, process_pid=15843, process_name='tor'))\n self.assertRaises(IOError, stem.util.connection.get_connections, Resolver.NETSTAT, process_pid=15843, process_name='stuff')\n self.assertRaises(IOError, stem.util.connection.get_connections, Resolver.NETSTAT, process_pid=1111, process_name='tor')\n call_mock.side_effect = OSError('Unable to call netstat')\n self.assertRaises(IOError, stem.util.connection.get_connections, Resolver.NETSTAT, process_pid=1111)\n\n @patch('stem.util.system.call', Mock(return_value=NETSTAT_IPV6_OUTPUT.split('\\n')))\n def test_get_connections_by_netstat_ipv6(self):\n \"\"\"\n Checks the get_connections function with the netstat resolver for IPv6.\n \"\"\"\n expected = [Connection('2a01:4f8:190:514a::2', 443, '2001:638:a000:4140::ffff:189', 41046, 'tcp', True), Connection('2a01:4f8:190:514a::2', 443, '2001:858:2:2:aabb:0:563b:1526', 38260, 'tcp', True)]\n self.assertEqual(expected, stem.util.connection.get_connections(Resolver.NETSTAT, process_pid=1904, process_name='tor'))\n\n @patch('stem.util.system.call')\n def test_get_connections_by_windows_netstat(self, call_mock):\n \"\"\"\n Checks the get_connections function with the Windows netstat resolver.\n \"\"\"\n call_mock.return_value = NETSTAT_WINDOWS_OUTPUT.split('\\n')\n expected = [Connection('192.168.0.1', 44284, '38.229.79.2', 443, 'tcp', False)]\n self.assertEqual(expected, stem.util.connection.get_connections(Resolver.NETSTAT_WINDOWS, process_pid=15843, process_name='tor'))\n self.assertRaises(IOError, stem.util.connection.get_connections, Resolver.NETSTAT_WINDOWS, process_pid=1111, process_name='tor')\n call_mock.side_effect = OSError('Unable to call netstat')\n self.assertRaises(IOError, stem.util.connection.get_connections, Resolver.NETSTAT_WINDOWS, process_pid=1111)\n\n @patch('stem.util.system.call')\n def test_get_connections_by_ss(self, call_mock):\n \"\"\"\n Checks the get_connections function with the ss resolver.\n \"\"\"\n call_mock.return_value = SS_OUTPUT.split('\\n')\n expected = [Connection('192.168.0.1', 44092, '23.112.135.72', 443, 'tcp', False), Connection('192.168.0.1', 44415, '38.229.79.2', 443, 'tcp', False)]\n self.assertEqual(expected, stem.util.connection.get_connections(Resolver.SS, process_pid=15843, process_name='tor'))\n self.assertRaises(IOError, stem.util.connection.get_connections, Resolver.SS, process_pid=15843, process_name='stuff')\n self.assertRaises(IOError, stem.util.connection.get_connections, Resolver.SS, process_pid=1111, process_name='tor')\n call_mock.side_effect = OSError('Unable to call ss')\n self.assertRaises(IOError, stem.util.connection.get_connections, Resolver.SS, process_pid=1111)\n\n @patch('stem.util.system.call', Mock(return_value=SS_IPV6_OUTPUT.split('\\n')))\n def test_get_connections_by_ss_ipv6(self):\n \"\"\"\n Checks the get_connections function with the ss resolver results on IPv6\n conections. This also checks with the output from a hardened Gentoo system\n which has subtle differences...\n\n https://trac.torproject.org/projects/tor/ticket/18079\n \"\"\"\n expected = [Connection('5.9.158.75', 443, '107.170.93.13', 56159, 'tcp', False), Connection('5.9.158.75', 443, '159.203.97.91', 37802, 'tcp', False), Connection('2a01:4f8:190:514a::2', 443, '2001:638:a000:4140::ffff:189', 38556, 'tcp', True), Connection('2a01:4f8:190:514a::2', 443, '2001:858:2:2:aabb:0:563b:1526', 51428, 'tcp', True)]\n self.assertEqual(expected, stem.util.connection.get_connections(Resolver.SS, process_pid=25056, process_name='tor'))\n self.assertEqual(2, len(stem.util.connection.get_connections(Resolver.SS, process_name='beam')))\n\n @patch('stem.util.system.call')\n def test_get_connections_by_lsof(self, call_mock):\n \"\"\"\n Checks the get_connections function with the lsof resolver.\n \"\"\"\n call_mock.return_value = LSOF_OUTPUT.split('\\n')\n expected = [Connection('192.168.0.1', 44415, '38.229.79.2', 443, 'tcp', False), Connection('192.168.0.1', 44092, '68.169.35.102', 443, 'tcp', False)]\n self.assertEqual(expected, stem.util.connection.get_connections(Resolver.LSOF, process_pid=15843, process_name='tor'))\n self.assertRaises(IOError, stem.util.connection.get_connections, Resolver.LSOF, process_pid=15843, process_name='stuff')\n self.assertRaises(IOError, stem.util.connection.get_connections, Resolver.LSOF, process_pid=1111, process_name='tor')\n call_mock.side_effect = OSError('Unable to call lsof')\n self.assertRaises(IOError, stem.util.connection.get_connections, Resolver.LSOF, process_pid=1111)\n\n @patch('stem.util.system.call', Mock(return_value=LSOF_IPV6_OUTPUT.split('\\n')))\n def test_get_connections_by_lsof_ipv6(self):\n \"\"\"\n Checks the get_connections function with the lsof resolver for IPv6.\n \"\"\"\n expected = [Connection('2a01:4f8:190:514a::2', 443, '2001:858:2:2:aabb:0:563b:1526', 44811, 'tcp', True)]\n self.assertEqual(expected, stem.util.connection.get_connections(Resolver.LSOF, process_pid=1904, process_name='tor'))\n\n @patch('stem.util.system.call', Mock(return_value=LSOF_OUTPUT_OSX.split('\\n')))\n def test_get_connections_by_lsof_osx(self):\n \"\"\"\n Checks the get_connections function with the lsof resolver on OSX. This\n only includes entries for the tor process.\n \"\"\"\n expected = [Connection('192.168.1.20', 9090, '38.229.79.2', 14010, 'tcp', False), Connection('192.168.1.20', 9090, '68.169.35.102', 14815, 'tcp', False), Connection('192.168.1.20', 9090, '62.135.16.134', 14456, 'tcp', False)]\n self.assertEqual(expected, stem.util.connection.get_connections(Resolver.LSOF, process_pid=129, process_name='tor'))\n\n @patch('stem.util.system.call')\n def test_get_connections_by_sockstat(self, call_mock):\n \"\"\"\n Checks the get_connections function with the sockstat resolver.\n \"\"\"\n call_mock.return_value = SOCKSTAT_OUTPUT.split('\\n')\n expected = [Connection('192.168.0.1', 44415, '38.229.79.2', 443, 'tcp', False), Connection('192.168.0.1', 44092, '68.169.35.102', 443, 'tcp', False)]\n self.assertEqual(expected, stem.util.connection.get_connections(Resolver.SOCKSTAT, process_pid=15843, process_name='tor'))\n self.assertRaises(IOError, stem.util.connection.get_connections, Resolver.SOCKSTAT, process_pid=15843, process_name='stuff')\n self.assertRaises(IOError, stem.util.connection.get_connections, Resolver.SOCKSTAT, process_pid=1111, process_name='tor')\n call_mock.side_effect = OSError('Unable to call sockstat')\n self.assertRaises(IOError, stem.util.connection.get_connections, Resolver.SOCKSTAT, process_pid=1111)\n\n @patch('stem.util.system.call')\n def test_get_connections_by_sockstat_for_bsd(self, call_mock):\n \"\"\"\n Checks the get_connections function with the bsd variant of the sockstat\n resolver.\n \"\"\"\n call_mock.return_value = BSD_SOCKSTAT_OUTPUT.split('\\n')\n expected = [Connection('172.27.72.202', 54011, '38.229.79.2', 9001, 'tcp', False), Connection('172.27.72.202', 59374, '68.169.35.102', 9001, 'tcp', False), Connection('172.27.72.202', 59673, '213.24.100.160', 9001, 'tcp', False), Connection('172.27.72.202', 51946, '32.188.221.72', 443, 'tcp', False), Connection('172.27.72.202', 60344, '21.89.91.78', 9001, 'tcp', False)]\n self.assertEqual(expected, stem.util.connection.get_connections(Resolver.BSD_SOCKSTAT, process_pid=4397, process_name='tor'))\n self.assertRaises(IOError, stem.util.connection.get_connections, Resolver.BSD_SOCKSTAT, process_pid=4397, process_name='stuff')\n self.assertRaises(IOError, stem.util.connection.get_connections, Resolver.BSD_SOCKSTAT, process_pid=1111, process_name='tor')\n call_mock.side_effect = OSError('Unable to call sockstat')\n self.assertRaises(IOError, stem.util.connection.get_connections, Resolver.BSD_SOCKSTAT, process_pid=1111)\n\n @patch('stem.util.system.call')\n def test_get_connections_by_procstat(self, call_mock):\n \"\"\"\n Checks the get_connections function with the procstat resolver.\n \"\"\"\n call_mock.return_value = BSD_PROCSTAT_OUTPUT.split('\\n')\n expected = [Connection('10.0.0.2', 9050, '10.0.0.1', 22370, 'tcp', False), Connection('10.0.0.2', 9050, '10.0.0.1', 44381, 'tcp', False), Connection('10.0.0.2', 33734, '38.229.79.2', 443, 'tcp', False), Connection('10.0.0.2', 47704, '68.169.35.102', 9001, 'tcp', False)]\n self.assertEqual(expected, stem.util.connection.get_connections(Resolver.BSD_PROCSTAT, process_pid=3561, process_name='tor'))\n self.assertRaises(IOError, stem.util.connection.get_connections, Resolver.BSD_PROCSTAT, process_pid=3561, process_name='stuff')\n self.assertRaises(IOError, stem.util.connection.get_connections, Resolver.BSD_PROCSTAT, process_pid=1111, process_name='tor')\n call_mock.side_effect = OSError('Unable to call procstat')\n self.assertRaises(IOError, stem.util.connection.get_connections, Resolver.BSD_PROCSTAT, process_pid=1111)\n\n @patch('stem.util.system.call')\n def test_get_connections_by_fstat(self, call_mock):\n \"\"\"\n Checks the get_connections function with the fstat resolver.\n \"\"\"\n call_mock.return_value = BSD_FSTAT_OUTPUT.split('\\n')\n expected = [Connection('127.0.0.1', 8443, '1.2.3.4', 54581, 'tcp', False), Connection('192.168.1.100', 36174, '4.3.2.1', 443, 'tcp', False)]\n self.assertEqual(expected, stem.util.connection.get_connections(Resolver.BSD_FSTAT, process_pid=15843, process_name='tor'))\n self.assertRaises(IOError, stem.util.connection.get_connections, Resolver.BSD_FSTAT, process_pid=15843, process_name='stuff')\n self.assertRaises(IOError, stem.util.connection.get_connections, Resolver.BSD_FSTAT, process_pid=1111, process_name='tor')\n call_mock.side_effect = OSError('Unable to call fstat')\n self.assertRaises(IOError, stem.util.connection.get_connections, Resolver.BSD_FSTAT, process_pid=1111)\n", "method_code": "def get_connections(resolver=None, process_pid=None, process_name=None):\n \"\"\"\n Retrieves a list of the current connections for a given process. This\n provides a list of :class:`~stem.util.connection.Connection`. Note that\n addresses may be IPv4 *or* IPv6 depending on what the platform supports.\n\n .. versionadded:: 1.1.0\n\n .. versionchanged:: 1.5.0\n Made our resolver argument optional.\n\n .. versionchanged:: 1.5.0\n IPv6 support when resolving via proc, netstat, lsof, or ss.\n\n :param Resolver resolver: method of connection resolution to use, if not\n provided then one is picked from among those that should likely be\n available for the system\n :param int process_pid: pid of the process to retrieve\n :param str process_name: name of the process to retrieve\n\n :returns: **list** of :class:`~stem.util.connection.Connection` instances\n\n :raises:\n * **ValueError** if neither a process_pid nor process_name is provided\n\n * **IOError** if no connections are available or resolution fails\n (generally they're indistinguishable). The common causes are the\n command being unavailable or permissions.\n \"\"\"\n if not resolver:\n available_resolvers = system_resolvers()\n if available_resolvers:\n resolver = available_resolvers[0]\n else:\n raise IOError('Unable to determine a connection resolver')\n if not process_pid and (not process_name):\n raise ValueError('You must provide a pid or process name to provide connections for')\n\n def _log(msg):\n if LOG_CONNECTION_RESOLUTION:\n log.debug(msg)\n _log('=' * 80)\n _log('Querying connections for resolver: %s, pid: %s, name: %s' % (resolver, process_pid, process_name))\n if isinstance(process_pid, str):\n try:\n process_pid = int(process_pid)\n except ValueError:\n raise ValueError('Process pid was non-numeric: %s' % process_pid)\n if process_pid is None:\n all_pids = stem.util.system.pid_by_name(process_name, True)\n if len(all_pids) == 0:\n if resolver in (Resolver.NETSTAT_WINDOWS, Resolver.PROC, Resolver.BSD_PROCSTAT):\n raise IOError(\"Unable to determine the pid of '%s'. %s requires the pid to provide the connections.\" % (process_name, resolver))\n elif len(all_pids) == 1:\n process_pid = all_pids[0]\n elif resolver in (Resolver.NETSTAT_WINDOWS, Resolver.PROC, Resolver.BSD_PROCSTAT):\n raise IOError(\"There's multiple processes named '%s'. %s requires a single pid to provide the connections.\" % (process_name, resolver))\n if resolver == Resolver.PROC:\n return stem.util.proc.connections(pid=process_pid)\n resolver_command = RESOLVER_COMMAND[resolver].format(pid=process_pid)\n try:\n results = stem.util.system.call(resolver_command)\n except OSError as exc:\n raise IOError(\"Unable to query '%s': %s\" % (resolver_command, exc))\n resolver_regex_str = RESOLVER_FILTER[resolver].format(protocol='(?P\\\\S+)', local='(?P[\\\\[\\\\]0-9a-f.:]+)', remote='(?P[\\\\[\\\\]0-9a-f.:]+)', pid=process_pid if process_pid else '[0-9]*', name=process_name if process_name else '\\\\S*')\n _log('Resolver regex: %s' % resolver_regex_str)\n _log('Resolver results:\\n%s' % '\\n'.join(results))\n connections = []\n resolver_regex = re.compile(resolver_regex_str)\n\n def _parse_address_str(addr_type, addr_str, line):\n addr, port = addr_str.rsplit(':', 1)\n if not is_valid_ipv4_address(addr) and (not is_valid_ipv6_address(addr, allow_brackets=True)):\n _log('Invalid %s address (%s): %s' % (addr_type, addr, line))\n return (None, None)\n elif not is_valid_port(port):\n _log('Invalid %s port (%s): %s' % (addr_type, port, line))\n return (None, None)\n else:\n _log('Valid %s:%s: %s' % (addr, port, line))\n return (addr.lstrip('[').rstrip(']'), int(port))\n for line in results:\n match = resolver_regex.match(line)\n if match:\n attr = match.groupdict()\n local_addr, local_port = _parse_address_str('local', attr['local'], line)\n remote_addr, remote_port = _parse_address_str('remote', attr['remote'], line)\n if not (local_addr and local_port and remote_addr and remote_port):\n continue\n protocol = attr['protocol'].lower()\n if protocol == 'tcp6':\n protocol = 'tcp'\n if protocol not in ('tcp', 'udp'):\n _log('Unrecognized protocol (%s): %s' % (protocol, line))\n continue\n conn = Connection(local_addr, local_port, remote_addr, remote_port, protocol, is_valid_ipv6_address(local_addr))\n connections.append(conn)\n _log(str(conn))\n _log('%i connections found' % len(connections))\n if not connections:\n raise IOError('No results found using: %s' % resolver_command)\n return connections", "context": "def get_connections(resolver=None, process_pid=None, process_name=None): ...\ndef get_connections(resolver=None, process_pid=None, process_name=None): ...\ndef system_resolvers(system=None): ...\ndef port_usage(port): ...\ndef is_valid_ipv4_address(address): ...\ndef is_valid_ipv6_address(address, allow_brackets=False): ...\ndef is_valid_port(entry, allow_zero=False): ...\ndef is_private_address(address): ...\ndef address_to_int(address): ...\ndef expand_ipv6_address(address): ...\ndef get_mask_ipv4(bits): ...\ndef get_mask_ipv6(bits): ...\ndef _get_masked_bits(mask): ...\ndef _get_binary(value, bits): ...\ndef _address_to_binary(address): ...\ndef _hmac_sha256(key, msg): ...\ndef _cryptovariables_equal(x, y): ...\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001036.py"} {"focal_file": "stem/util/connection.py", "focal_class": null, "focal_method": "is_valid_ipv4_address", "tests": "import unittest\n\nclass Test_is_valid_ipv4_address(unittest.TestCase):\n def test_is_valid_ipv4_address(self):\n \"\"\"\n Checks the is_valid_ipv4_address function.\n \"\"\"\n valid_addresses = ('0.0.0.0', '1.2.3.4', '1.2.3.4', '192.168.0.1', '255.255.255.255', b'255.255.255.255')\n invalid_addresses = ('0.0.00.0', '0.0.0', '1.2.3.256', '1.2.3.-1', '0.0.0.a', 'a.b.c.d', b'a.b.c.d')\n for address in valid_addresses:\n self.assertTrue(stem.util.connection.is_valid_ipv4_address(address))\n for address in invalid_addresses:\n self.assertFalse(stem.util.connection.is_valid_ipv4_address(address))\n", "method_code": "def is_valid_ipv4_address(address):\n \"\"\"\n Checks if a string is a valid IPv4 address.\n\n :param str address: string to be checked\n\n :returns: **True** if input is a valid IPv4 address, **False** otherwise\n \"\"\"\n if isinstance(address, bytes):\n address = str_tools._to_unicode(address)\n elif not stem.util._is_str(address):\n return False\n if address.count('.') != 3:\n return False\n for entry in address.split('.'):\n if not entry.isdigit() or int(entry) < 0 or int(entry) > 255:\n return False\n elif entry[0] == '0' and len(entry) > 1:\n return False\n return True", "context": "def is_valid_ipv4_address(address): ...\ndef get_connections(resolver=None, process_pid=None, process_name=None): ...\ndef system_resolvers(system=None): ...\ndef port_usage(port): ...\ndef is_valid_ipv4_address(address): ...\ndef is_valid_ipv6_address(address, allow_brackets=False): ...\ndef is_valid_port(entry, allow_zero=False): ...\ndef is_private_address(address): ...\ndef address_to_int(address): ...\ndef expand_ipv6_address(address): ...\ndef get_mask_ipv4(bits): ...\ndef get_mask_ipv6(bits): ...\ndef _get_masked_bits(mask): ...\ndef _get_binary(value, bits): ...\ndef _address_to_binary(address): ...\ndef _hmac_sha256(key, msg): ...\ndef _cryptovariables_equal(x, y): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_is_valid_ipv4_address", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001037.py"} {"focal_file": "stem/util/connection.py", "focal_class": null, "focal_method": "is_valid_ipv6_address", "tests": "import unittest\n\nclass Test_is_valid_ipv6_address(unittest.TestCase):\n def test_is_valid_ipv6_address(self):\n \"\"\"\n Checks the is_valid_ipv6_address function.\n \"\"\"\n valid_addresses = ('fe80:0000:0000:0000:0202:b3ff:fe1e:8329', 'fe80:0:0:0:202:b3ff:fe1e:8329', 'fe80::202:b3ff:fe1e:8329', '::ffff:5.9.158.75', '5.9.158.75::ffff', '::5.9.158.75:ffff', '::')\n invalid_addresses = ('fe80:0000:0000:0000:0202:b3ff:fe1e:829g', 'fe80:0000:0000:0000:0202:b3ff:fe1e: 8329', '2001:db8::aaaa::1', '::ffff:5.9.158.75.12', '::ffff:5.9.158', '::ffff:5.9', ':::', ':', '')\n for address in valid_addresses:\n self.assertTrue(stem.util.connection.is_valid_ipv6_address(address), \"%s isn't a valid IPv6 address\" % address)\n for address in invalid_addresses:\n self.assertFalse(stem.util.connection.is_valid_ipv6_address(address), '%s should be an invalid IPv6 address' % address)\n", "method_code": "def is_valid_ipv6_address(address, allow_brackets=False):\n \"\"\"\n Checks if a string is a valid IPv6 address.\n\n :param str address: string to be checked\n :param bool allow_brackets: ignore brackets which form '[address]'\n\n :returns: **True** if input is a valid IPv6 address, **False** otherwise\n \"\"\"\n if isinstance(address, bytes):\n address = str_tools._to_unicode(address)\n elif not stem.util._is_str(address):\n return False\n if allow_brackets:\n if address.startswith('[') and address.endswith(']'):\n address = address[1:-1]\n if address.count('.') == 3:\n ipv4_start = address.rfind(':', 0, address.find('.')) + 1\n ipv4_end = address.find(':', ipv4_start + 1)\n if ipv4_end == -1:\n ipv4_end = None\n if not is_valid_ipv4_address(address[ipv4_start:ipv4_end]):\n return False\n addr_comp = [address[:ipv4_start - 1] if ipv4_start != 0 else None, 'ff:ff', address[ipv4_end + 1:] if ipv4_end else None]\n address = ':'.join(filter(None, addr_comp))\n colon_count = address.count(':')\n if colon_count > 7:\n return False\n elif colon_count != 7 and '::' not in address:\n return False\n elif address.count('::') > 1 or ':::' in address:\n return False\n for entry in address.split(':'):\n if not re.match('^[0-9a-fA-f]{0,4}$', entry):\n return False\n return True", "context": "def is_valid_ipv6_address(address, allow_brackets=False): ...\ndef get_connections(resolver=None, process_pid=None, process_name=None): ...\ndef system_resolvers(system=None): ...\ndef port_usage(port): ...\ndef is_valid_ipv4_address(address): ...\ndef is_valid_ipv6_address(address, allow_brackets=False): ...\ndef is_valid_port(entry, allow_zero=False): ...\ndef is_private_address(address): ...\ndef address_to_int(address): ...\ndef expand_ipv6_address(address): ...\ndef get_mask_ipv4(bits): ...\ndef get_mask_ipv6(bits): ...\ndef _get_masked_bits(mask): ...\ndef _get_binary(value, bits): ...\ndef _address_to_binary(address): ...\ndef _hmac_sha256(key, msg): ...\ndef _cryptovariables_equal(x, y): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_is_valid_ipv6_address", "smells": [1, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001038.py"} {"focal_file": "stem/util/connection.py", "focal_class": null, "focal_method": "is_valid_port", "tests": "import unittest\n\nclass Test_is_valid_port(unittest.TestCase):\n def test_is_valid_port(self):\n \"\"\"\n Checks the is_valid_port function.\n \"\"\"\n valid_ports = (1, '1', 1234, '1234', 65535, '65535', [1, '2'])\n invalid_ports = (0, '0', 65536, '65536', 'abc', '*', ' 15', '01', True, {})\n for port in valid_ports:\n self.assertTrue(stem.util.connection.is_valid_port(port))\n for port in invalid_ports:\n self.assertFalse(stem.util.connection.is_valid_port(port))\n self.assertTrue(stem.util.connection.is_valid_port(0, allow_zero=True))\n self.assertTrue(stem.util.connection.is_valid_port('0', allow_zero=True))\n", "method_code": "def is_valid_port(entry, allow_zero=False):\n \"\"\"\n Checks if a string or int is a valid port number.\n\n :param list,str,int entry: string, integer or list to be checked\n :param bool allow_zero: accept port number of zero (reserved by definition)\n\n :returns: **True** if input is an integer and within the valid port range, **False** otherwise\n \"\"\"\n try:\n value = int(entry)\n if str(value) != str(entry):\n return False\n elif allow_zero and value == 0:\n return True\n else:\n return value > 0 and value < 65536\n except TypeError:\n if isinstance(entry, (tuple, list)):\n for port in entry:\n if not is_valid_port(port, allow_zero):\n return False\n return True\n else:\n return False\n except ValueError:\n return False", "context": "def is_valid_port(entry, allow_zero=False): ...\ndef get_connections(resolver=None, process_pid=None, process_name=None): ...\ndef system_resolvers(system=None): ...\ndef port_usage(port): ...\ndef is_valid_ipv4_address(address): ...\ndef is_valid_ipv6_address(address, allow_brackets=False): ...\ndef is_valid_port(entry, allow_zero=False): ...\ndef is_private_address(address): ...\ndef address_to_int(address): ...\ndef expand_ipv6_address(address): ...\ndef get_mask_ipv4(bits): ...\ndef get_mask_ipv6(bits): ...\ndef _get_masked_bits(mask): ...\ndef _get_binary(value, bits): ...\ndef _address_to_binary(address): ...\ndef _hmac_sha256(key, msg): ...\ndef _cryptovariables_equal(x, y): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_is_valid_port", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001039.py"} {"focal_file": "stem/util/connection.py", "focal_class": null, "focal_method": "is_private_address", "tests": "import unittest\n\nclass Test_is_private_address(unittest.TestCase):\n def test_is_private_address(self):\n \"\"\"\n Checks the is_private_address function.\n \"\"\"\n self.assertTrue(stem.util.connection.is_private_address('127.0.0.1'))\n self.assertTrue(stem.util.connection.is_private_address('10.0.0.0'))\n self.assertTrue(stem.util.connection.is_private_address('172.16.0.0'))\n self.assertTrue(stem.util.connection.is_private_address('172.31.0.0'))\n self.assertTrue(stem.util.connection.is_private_address('192.168.0.50'))\n self.assertFalse(stem.util.connection.is_private_address('74.125.28.103'))\n self.assertFalse(stem.util.connection.is_private_address('172.15.0.0'))\n self.assertFalse(stem.util.connection.is_private_address('172.32.0.0'))\n self.assertRaises(ValueError, stem.util.connection.is_private_address, '')\n self.assertRaises(ValueError, stem.util.connection.is_private_address, 'blarg')\n self.assertRaises(ValueError, stem.util.connection.is_private_address, '127.0.0')\n self.assertRaises(ValueError, stem.util.connection.is_private_address, 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329')\n", "method_code": "def is_private_address(address):\n \"\"\"\n Checks if the IPv4 address is in a range belonging to the local network or\n loopback. These include:\n\n * Private ranges: 10.*, 172.16.* - 172.31.*, 192.168.*\n * Loopback: 127.*\n\n .. versionadded:: 1.1.0\n\n :param str address: string to be checked\n\n :returns: **True** if input is in a private range, **False** otherwise\n\n :raises: **ValueError** if the address isn't a valid IPv4 address\n \"\"\"\n if not is_valid_ipv4_address(address):\n raise ValueError(\"'%s' isn't a valid IPv4 address\" % address)\n if address.startswith('10.') or address.startswith('192.168.') or address.startswith('127.'):\n return True\n if address.startswith('172.'):\n second_octet = int(address.split('.')[1])\n if second_octet >= 16 and second_octet <= 31:\n return True\n return False", "context": "def is_private_address(address): ...\ndef get_connections(resolver=None, process_pid=None, process_name=None): ...\ndef system_resolvers(system=None): ...\ndef port_usage(port): ...\ndef is_valid_ipv4_address(address): ...\ndef is_valid_ipv6_address(address, allow_brackets=False): ...\ndef is_valid_port(entry, allow_zero=False): ...\ndef is_private_address(address): ...\ndef address_to_int(address): ...\ndef expand_ipv6_address(address): ...\ndef get_mask_ipv4(bits): ...\ndef get_mask_ipv6(bits): ...\ndef _get_masked_bits(mask): ...\ndef _get_binary(value, bits): ...\ndef _address_to_binary(address): ...\ndef _hmac_sha256(key, msg): ...\ndef _cryptovariables_equal(x, y): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_is_private_address", "smells": [1, 0, 0, 0, 1, 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": [1, 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": "stem/util/connection.py", "focal_class": null, "focal_method": "address_to_int", "tests": "import unittest\n\nclass Test_address_to_int(unittest.TestCase):\n def test_address_to_int(self):\n \"\"\"\n Checks the address_to_int function.\n \"\"\"\n self.assertEqual(1, stem.util.connection.address_to_int('0.0.0.1'))\n self.assertEqual(2, stem.util.connection.address_to_int('0.0.0.2'))\n self.assertEqual(256, stem.util.connection.address_to_int('0.0.1.0'))\n self.assertEqual(2130706433, stem.util.connection.address_to_int('127.0.0.1'))\n self.assertEqual(338288524927261089654163772891438416681, stem.util.connection.address_to_int('fe80:0000:0000:0000:0202:b3ff:fe1e:8329'))\n", "method_code": "def address_to_int(address):\n \"\"\"\n Provides an integer representation of a IPv4 or IPv6 address that can be used\n for sorting.\n\n .. versionadded:: 1.5.0\n\n :param str address: IPv4 or IPv6 address\n\n :returns: **int** representation of the address\n \"\"\"\n return int(_address_to_binary(address), 2)", "context": "def address_to_int(address): ...\ndef get_connections(resolver=None, process_pid=None, process_name=None): ...\ndef system_resolvers(system=None): ...\ndef port_usage(port): ...\ndef is_valid_ipv4_address(address): ...\ndef is_valid_ipv6_address(address, allow_brackets=False): ...\ndef is_valid_port(entry, allow_zero=False): ...\ndef is_private_address(address): ...\ndef address_to_int(address): ...\ndef expand_ipv6_address(address): ...\ndef get_mask_ipv4(bits): ...\ndef get_mask_ipv6(bits): ...\ndef _get_masked_bits(mask): ...\ndef _get_binary(value, bits): ...\ndef _address_to_binary(address): ...\ndef _hmac_sha256(key, msg): ...\ndef _cryptovariables_equal(x, y): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_address_to_int", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001041.py"} {"focal_file": "stem/util/connection.py", "focal_class": null, "focal_method": "expand_ipv6_address", "tests": "import unittest\n\nclass Test_expand_ipv6_address(unittest.TestCase):\n def test_expand_ipv6_address(self):\n \"\"\"\n Checks the expand_ipv6_address function.\n \"\"\"\n test_values = {'2001:db8::ff00:42:8329': '2001:0db8:0000:0000:0000:ff00:0042:8329', '::': '0000:0000:0000:0000:0000:0000:0000:0000', '::1': '0000:0000:0000:0000:0000:0000:0000:0001', '1::1': '0001:0000:0000:0000:0000:0000:0000:0001', '::ffff:5.9.158.75': '0000:0000:0000:0000:0000:ffff:0509:9e4b', '5.9.158.75::ffff': '0509:9e4b:0000:0000:0000:0000:0000:ffff', '::5.9.158.75:ffff': '0000:0000:0000:0000:0000:0509:9e4b:ffff'}\n for test_arg, expected in test_values.items():\n self.assertEqual(expected, stem.util.connection.expand_ipv6_address(test_arg))\n self.assertRaises(ValueError, stem.util.connection.expand_ipv6_address, '127.0.0.1')\n", "method_code": "def expand_ipv6_address(address):\n \"\"\"\n Expands abbreviated IPv6 addresses to their full colon separated hex format.\n For instance...\n\n ::\n\n >>> expand_ipv6_address('2001:db8::ff00:42:8329')\n '2001:0db8:0000:0000:0000:ff00:0042:8329'\n\n >>> expand_ipv6_address('::')\n '0000:0000:0000:0000:0000:0000:0000:0000'\n\n >>> expand_ipv6_address('::ffff:5.9.158.75')\n '0000:0000:0000:0000:0000:ffff:0509:9e4b'\n\n :param str address: IPv6 address to be expanded\n\n :raises: **ValueError** if the address can't be expanded due to being malformed\n \"\"\"\n if not is_valid_ipv6_address(address):\n raise ValueError(\"'%s' isn't a valid IPv6 address\" % address)\n if address.count('.') == 3:\n ipv4_start = address.rfind(':', 0, address.find('.')) + 1\n ipv4_end = address.find(':', ipv4_start + 1)\n if ipv4_end == -1:\n ipv4_end = None\n ipv4_bin = _address_to_binary(address[ipv4_start:ipv4_end])\n groupings = [ipv4_bin[16 * i:16 * (i + 1)] for i in range(2)]\n ipv6_snippet = ':'.join(['%04x' % int(group, 2) for group in groupings])\n addr_comp = [address[:ipv4_start - 1] if ipv4_start != 0 else None, ipv6_snippet, address[ipv4_end + 1:] if ipv4_end else None]\n address = ':'.join(filter(None, addr_comp))\n if '::' in address:\n missing_groups = 7 - address.count(':')\n address = address.replace('::', '::' + ':' * missing_groups)\n for index in range(8):\n start = index * 5\n end = address.index(':', start) if index != 7 else len(address)\n missing_zeros = 4 - (end - start)\n if missing_zeros > 0:\n address = address[:start] + '0' * missing_zeros + address[start:]\n return address", "context": "def expand_ipv6_address(address): ...\ndef get_connections(resolver=None, process_pid=None, process_name=None): ...\ndef system_resolvers(system=None): ...\ndef port_usage(port): ...\ndef is_valid_ipv4_address(address): ...\ndef is_valid_ipv6_address(address, allow_brackets=False): ...\ndef is_valid_port(entry, allow_zero=False): ...\ndef is_private_address(address): ...\ndef address_to_int(address): ...\ndef expand_ipv6_address(address): ...\ndef get_mask_ipv4(bits): ...\ndef get_mask_ipv6(bits): ...\ndef _get_masked_bits(mask): ...\ndef _get_binary(value, bits): ...\ndef _address_to_binary(address): ...\ndef _hmac_sha256(key, msg): ...\ndef _cryptovariables_equal(x, y): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_expand_ipv6_address", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001042.py"} {"focal_file": "stem/util/connection.py", "focal_class": null, "focal_method": "get_mask_ipv4", "tests": "import unittest\n\nclass Test_get_mask_ipv4(unittest.TestCase):\n def test_get_mask_ipv4(self):\n \"\"\"\n Checks the get_mask_ipv4 function.\n \"\"\"\n self.assertEqual('255.255.255.255', stem.util.connection.get_mask_ipv4(32))\n self.assertEqual('255.255.255.248', stem.util.connection.get_mask_ipv4(29))\n self.assertEqual('255.255.254.0', stem.util.connection.get_mask_ipv4(23))\n self.assertEqual('0.0.0.0', stem.util.connection.get_mask_ipv4(0))\n self.assertRaises(ValueError, stem.util.connection.get_mask_ipv4, -1)\n self.assertRaises(ValueError, stem.util.connection.get_mask_ipv4, 33)\n", "method_code": "def get_mask_ipv4(bits):\n \"\"\"\n Provides the IPv4 mask for a given number of bits, in the dotted-quad format.\n\n :param int bits: number of bits to be converted\n\n :returns: **str** with the subnet mask representation for this many bits\n\n :raises: **ValueError** if given a number of bits outside the range of 0-32\n \"\"\"\n if bits > 32 or bits < 0:\n raise ValueError('A mask can only be 0-32 bits, got %i' % bits)\n elif bits == 32:\n return FULL_IPv4_MASK\n mask_bin = _get_binary(2 ** bits - 1, 32)[::-1]\n octets = [mask_bin[8 * i:8 * (i + 1)] for i in range(4)]\n return '.'.join([str(int(octet, 2)) for octet in octets])", "context": "def get_mask_ipv4(bits): ...\ndef get_connections(resolver=None, process_pid=None, process_name=None): ...\ndef system_resolvers(system=None): ...\ndef port_usage(port): ...\ndef is_valid_ipv4_address(address): ...\ndef is_valid_ipv6_address(address, allow_brackets=False): ...\ndef is_valid_port(entry, allow_zero=False): ...\ndef is_private_address(address): ...\ndef address_to_int(address): ...\ndef expand_ipv6_address(address): ...\ndef get_mask_ipv4(bits): ...\ndef get_mask_ipv6(bits): ...\ndef _get_masked_bits(mask): ...\ndef _get_binary(value, bits): ...\ndef _address_to_binary(address): ...\ndef _hmac_sha256(key, msg): ...\ndef _cryptovariables_equal(x, y): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_get_mask_ipv4", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001043.py"} {"focal_file": "stem/util/connection.py", "focal_class": null, "focal_method": "get_mask_ipv6", "tests": "import unittest\n\nclass Test_get_mask_ipv6(unittest.TestCase):\n def test_get_mask_ipv6(self):\n \"\"\"\n Checks the get_mask_ipv6 function.\n \"\"\"\n self.assertEqual('FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF', stem.util.connection.get_mask_ipv6(128))\n self.assertEqual('FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFE:0000', stem.util.connection.get_mask_ipv6(111))\n self.assertEqual('0000:0000:0000:0000:0000:0000:0000:0000', stem.util.connection.get_mask_ipv6(0))\n self.assertRaises(ValueError, stem.util.connection.get_mask_ipv6, -1)\n self.assertRaises(ValueError, stem.util.connection.get_mask_ipv6, 129)\n", "method_code": "def get_mask_ipv6(bits):\n \"\"\"\n Provides the IPv6 mask for a given number of bits, in the hex colon-delimited\n format.\n\n :param int bits: number of bits to be converted\n\n :returns: **str** with the subnet mask representation for this many bits\n\n :raises: **ValueError** if given a number of bits outside the range of 0-128\n \"\"\"\n if bits > 128 or bits < 0:\n raise ValueError('A mask can only be 0-128 bits, got %i' % bits)\n elif bits == 128:\n return FULL_IPv6_MASK\n mask_bin = _get_binary(2 ** bits - 1, 128)[::-1]\n groupings = [mask_bin[16 * i:16 * (i + 1)] for i in range(8)]\n return ':'.join(['%04x' % int(group, 2) for group in groupings]).upper()", "context": "def get_mask_ipv6(bits): ...\ndef get_connections(resolver=None, process_pid=None, process_name=None): ...\ndef system_resolvers(system=None): ...\ndef port_usage(port): ...\ndef is_valid_ipv4_address(address): ...\ndef is_valid_ipv6_address(address, allow_brackets=False): ...\ndef is_valid_port(entry, allow_zero=False): ...\ndef is_private_address(address): ...\ndef address_to_int(address): ...\ndef expand_ipv6_address(address): ...\ndef get_mask_ipv4(bits): ...\ndef get_mask_ipv6(bits): ...\ndef _get_masked_bits(mask): ...\ndef _get_binary(value, bits): ...\ndef _address_to_binary(address): ...\ndef _hmac_sha256(key, msg): ...\ndef _cryptovariables_equal(x, y): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_get_mask_ipv6", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001044.py"} {"focal_file": "stem/util/connection.py", "focal_class": null, "focal_method": "_get_masked_bits", "tests": "import unittest\n\nclass Test_get_masked_bits(unittest.TestCase):\n def test_get_masked_bits(self):\n \"\"\"\n Checks the _get_masked_bits function.\n \"\"\"\n self.assertEqual(32, stem.util.connection._get_masked_bits('255.255.255.255'))\n self.assertEqual(29, stem.util.connection._get_masked_bits('255.255.255.248'))\n self.assertEqual(23, stem.util.connection._get_masked_bits('255.255.254.0'))\n self.assertEqual(0, stem.util.connection._get_masked_bits('0.0.0.0'))\n self.assertRaises(ValueError, stem.util.connection._get_masked_bits, 'blarg')\n self.assertRaises(ValueError, stem.util.connection._get_masked_bits, '255.255.0.255')\n", "method_code": "def _get_masked_bits(mask):\n \"\"\"\n Provides the number of bits that an IPv4 subnet mask represents. Note that\n not all masks can be represented by a bit count.\n\n :param str mask: mask to be converted\n\n :returns: **int** with the number of bits represented by the mask\n\n :raises: **ValueError** if the mask is invalid or can't be converted\n \"\"\"\n if not is_valid_ipv4_address(mask):\n raise ValueError(\"'%s' is an invalid subnet mask\" % mask)\n mask_bin = _address_to_binary(mask)\n mask_match = re.match('^(1*)(0*)$', mask_bin)\n if mask_match:\n return 32 - len(mask_match.groups()[1])\n else:\n raise ValueError('Unable to convert mask to a bit count: %s' % mask)", "context": "def _get_masked_bits(mask): ...\ndef get_connections(resolver=None, process_pid=None, process_name=None): ...\ndef system_resolvers(system=None): ...\ndef port_usage(port): ...\ndef is_valid_ipv4_address(address): ...\ndef is_valid_ipv6_address(address, allow_brackets=False): ...\ndef is_valid_port(entry, allow_zero=False): ...\ndef is_private_address(address): ...\ndef address_to_int(address): ...\ndef expand_ipv6_address(address): ...\ndef get_mask_ipv4(bits): ...\ndef get_mask_ipv6(bits): ...\ndef _get_masked_bits(mask): ...\ndef _get_binary(value, bits): ...\ndef _address_to_binary(address): ...\ndef _hmac_sha256(key, msg): ...\ndef _cryptovariables_equal(x, y): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_get_masked_bits", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001045.py"} {"focal_file": "stem/util/connection.py", "focal_class": null, "focal_method": "_address_to_binary", "tests": "import unittest\n\nclass Test_address_to_binary(unittest.TestCase):\n def test_address_to_binary(self):\n \"\"\"\n Checks the _address_to_binary function.\n \"\"\"\n test_values = {'0.0.0.0': '00000000000000000000000000000000', '1.2.3.4': '00000001000000100000001100000100', '127.0.0.1': '01111111000000000000000000000001', '255.255.255.255': '11111111111111111111111111111111', '::': '0' * 128, '::1': '0' * 127 + '1', '1::1': '0000000000000001' + '0' * 111 + '1', '2001:db8::ff00:42:8329': '00100000000000010000110110111000000000000000000000000000000000000000000000000000111111110000000000000000010000101000001100101001'}\n for test_arg, expected in test_values.items():\n self.assertEqual(expected, stem.util.connection._address_to_binary(test_arg))\n self.assertRaises(ValueError, stem.util.connection._address_to_binary, '')\n self.assertRaises(ValueError, stem.util.connection._address_to_binary, 'blarg')\n", "method_code": "def _address_to_binary(address):\n \"\"\"\n Provides the binary value for an IPv4 or IPv6 address.\n\n :returns: **str** with the binary representation of this address\n\n :raises: **ValueError** if address is neither an IPv4 nor IPv6 address\n \"\"\"\n if is_valid_ipv4_address(address):\n return ''.join([_get_binary(int(octet), 8) for octet in address.split('.')])\n elif is_valid_ipv6_address(address):\n address = expand_ipv6_address(address)\n return ''.join([_get_binary(int(grouping, 16), 16) for grouping in address.split(':')])\n else:\n raise ValueError(\"'%s' is neither an IPv4 or IPv6 address\" % address)", "context": "def _address_to_binary(address): ...\ndef get_connections(resolver=None, process_pid=None, process_name=None): ...\ndef system_resolvers(system=None): ...\ndef port_usage(port): ...\ndef is_valid_ipv4_address(address): ...\ndef is_valid_ipv6_address(address, allow_brackets=False): ...\ndef is_valid_port(entry, allow_zero=False): ...\ndef is_private_address(address): ...\ndef address_to_int(address): ...\ndef expand_ipv6_address(address): ...\ndef get_mask_ipv4(bits): ...\ndef get_mask_ipv6(bits): ...\ndef _get_masked_bits(mask): ...\ndef _get_binary(value, bits): ...\ndef _address_to_binary(address): ...\ndef _hmac_sha256(key, msg): ...\ndef _cryptovariables_equal(x, y): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_address_to_binary", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001046.py"} {"focal_file": "stem/util/term.py", "focal_class": null, "focal_method": "encoding", "tests": "import unittest\n\nclass Test_encoding(unittest.TestCase):\n def test_encoding(self):\n \"\"\"\n Exercises our encoding function.\n \"\"\"\n self.assertEqual(None, stem.util.term.encoding())\n self.assertEqual('\\x1b[31m', stem.util.term.encoding(Color.RED))\n self.assertEqual('\\x1b[31;1m', stem.util.term.encoding(Color.RED, Attr.BOLD))\n", "method_code": "def encoding(*attrs):\n \"\"\"\n Provides the ANSI escape sequence for these terminal color or attributes.\n\n .. versionadded:: 1.5.0\n\n :param list attr: :data:`~stem.util.terminal.Color`,\n :data:`~stem.util.terminal.BgColor`, or :data:`~stem.util.terminal.Attr` to\n provide an ecoding for\n\n :returns: **str** of the ANSI escape sequence, **None** no attributes are\n recognized\n \"\"\"\n term_encodings = []\n for attr in attrs:\n if attr == 'HILIGHT':\n attr = 'HIGHLIGHT'\n attr = stem.util.str_tools._to_camel_case(attr)\n term_encoding = FG_ENCODING.get(attr, None)\n term_encoding = BG_ENCODING.get(attr, term_encoding)\n term_encoding = ATTR_ENCODING.get(attr, term_encoding)\n if term_encoding:\n term_encodings.append(term_encoding)\n if term_encodings:\n return CSI % ';'.join(term_encodings)", "context": "def encoding(*attrs): ...\ndef encoding(*attrs): ...\ndef format(msg, *attr): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_encoding", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001047.py"} {"focal_file": "stem/util/term.py", "focal_class": null, "focal_method": "format", "tests": "import unittest\n\nclass Test_format(unittest.TestCase):\n def test_format(self):\n \"\"\"\n Exercises our format function.\n \"\"\"\n self.assertEqual('hi!', stem.util.term.format('hi!'))\n self.assertEqual('\\x1b[31mhi!\\x1b[0m', stem.util.term.format('hi!', Color.RED))\n self.assertEqual('\\x1b[31;1mhi!\\x1b[0m', stem.util.term.format('hi!', Color.RED, Attr.BOLD))\n self.assertEqual('\\x1b[31mhi\\nthere!\\x1b[0m', stem.util.term.format('hi\\nthere!', Color.RED))\n self.assertEqual('\\x1b[31mhi\\x1b[0m\\n\\x1b[31mthere!\\x1b[0m', stem.util.term.format('hi\\nthere!', Color.RED, Attr.LINES))\n self.assertEqual('\\x01\\x1b[31m\\x02hi!\\x01\\x1b[0m\\x02', stem.util.term.format('hi!', Color.RED, Attr.READLINE_ESCAPE))\n", "method_code": "def format(msg, *attr):\n \"\"\"\n Simple terminal text formatting using `ANSI escape sequences\n `_.\n The following are some toolkits providing similar capabilities:\n\n * `django.utils.termcolors `_\n * `termcolor `_\n * `colorama `_\n\n .. versionchanged:: 1.6.0\n Normalized return value to be unicode to better support python 2/3\n compatibility.\n\n :param str msg: string to be formatted\n :param str attr: text attributes, this can be :data:`~stem.util.term.Color`,\n :data:`~stem.util.term.BgColor`, or :data:`~stem.util.term.Attr` enums\n and are case insensitive (so strings like 'red' are fine)\n\n :returns: **unicode** wrapped with ANSI escape encodings, starting with the given\n attributes and ending with a reset\n \"\"\"\n msg = stem.util.str_tools._to_unicode(msg)\n if DISABLE_COLOR_SUPPORT:\n return msg\n if Attr.LINES in attr:\n attr = list(attr)\n attr.remove(Attr.LINES)\n lines = [format(line, *attr) for line in msg.split('\\n')]\n return '\\n'.join(lines)\n if RESET in msg:\n return ''.join([format(comp, *attr) for comp in msg.split(RESET)])\n prefix, suffix = (encoding(*attr), RESET)\n if prefix:\n if Attr.READLINE_ESCAPE in attr:\n prefix = '\\x01%s\\x02' % prefix\n suffix = '\\x01%s\\x02' % suffix\n return prefix + msg + suffix\n else:\n return msg", "context": "def format(msg, *attr): ...\ndef encoding(*attrs): ...\ndef format(msg, *attr): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_format", "smells": [1, 0, 0, 0, 1, 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": [1, 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": "stem/util/log.py", "focal_class": "stem.util.log._NullHandler", "focal_method": "is_tracing", "tests": "import unittest\n\nclass Test_stem_util_log_NullHandler_is_tracing(unittest.TestCase):\n def test_is_tracing(self):\n logger = log.get_logger()\n original_handlers = logger.handlers\n logger.handlers = [log._NullHandler()]\n try:\n self.assertFalse(log.is_tracing())\n logger.addHandler(log.LogBuffer(log.DEBUG))\n self.assertFalse(log.is_tracing())\n logger.addHandler(log.LogBuffer(log.TRACE))\n self.assertTrue(log.is_tracing())\n finally:\n logger.handlers = original_handlers\n", "method_code": "def is_tracing():\n \"\"\"\n Checks if we're logging at the trace runlevel.\n\n .. versionadded:: 1.6.0\n\n :returns: **True** if we're logging at the trace runlevel and **False** otherwise\n \"\"\"\n for handler in get_logger().handlers:\n if handler.level <= logging_level(TRACE):\n return True\n return False", "context": "def is_tracing(): ...\ndef get_logger(): ...\ndef logging_level(runlevel): ...\ndef is_tracing(): ...\ndef escape(message): ...\ndef log(runlevel, message): ...\ndef log_once(message_id, runlevel, message): ...\ndef trace(message): ...\ndef debug(message): ...\ndef info(message): ...\ndef notice(message): ...\ndef warn(message): ...\ndef error(message): ...\ndef log_to_stdout(runlevel): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_is_tracing", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001049.py"} {"focal_file": "stem/util/system.py", "focal_class": null, "focal_method": "size_of", "tests": "import unittest\n\nclass Test_size_of(unittest.TestCase):\n def test_size_of(self):\n \"\"\"\n Exercises the size_of function.\n \"\"\"\n if stem.prereq.is_pypy():\n self.assertRaises(NotImplementedError, system.size_of, 'hello')\n else:\n self.assertTrue(system.size_of('') < system.size_of('hello') < system.size_of('hello world'))\n self.assertTrue(system.size_of([]) < system.size_of(['hello']) < system.size_of(['hello', 'world']))\n self.assertTrue(system.size_of({}) < system.size_of({'hello': 'world'}) < system.size_of({'hello': 'world', 'more': 'stuff'}))\n", "method_code": "def size_of(obj, exclude=None):\n \"\"\"\n Provides the `approximate memory usage of an object\n `_. This can recurse tuples,\n lists, deques, dicts, and sets. To teach this function to inspect additional\n object types expand SIZE_RECURSES...\n\n ::\n\n stem.util.system.SIZE_RECURSES[SomeClass] = SomeClass.get_elements\n\n .. versionadded:: 1.6.0\n\n :param object obj: object to provide the size of\n :param set exclude: object ids to exclude from size estimation\n\n :returns: **int** with the size of the object in bytes\n\n :raises: **NotImplementedError** if using PyPy\n \"\"\"\n if stem.prereq.is_pypy():\n raise NotImplementedError('PyPy does not implement sys.getsizeof()')\n if exclude is None:\n exclude = set()\n elif id(obj) in exclude:\n return 0\n try:\n size = sys.getsizeof(obj)\n except TypeError:\n size = sys.getsizeof(0)\n exclude.add(id(obj))\n if type(obj) in SIZE_RECURSES:\n for entry in SIZE_RECURSES[type(obj)](obj):\n size += size_of(entry, exclude)\n return size", "context": "def size_of(obj, exclude=None): ...\ndef is_windows(): ...\ndef is_mac(): ...\ndef is_gentoo(): ...\ndef is_slackware(): ...\ndef is_bsd(): ...\ndef is_available(command, cached=True): ...\ndef is_running(command): ...\ndef size_of(obj, exclude=None): ...\ndef name_by_pid(pid): ...\ndef pid_by_name(process_name, multiple=False): ...\ndef pid_by_port(port): ...\ndef pid_by_open_file(path): ...\ndef pids_by_user(user): ...\ndef cwd(pid): ...\ndef user(pid): ...\ndef start_time(pid): ...\ndef tail(target, lines=None): ...\ndef bsd_jail_id(pid): ...\ndef bsd_jail_path(jid): ...\ndef is_tarfile(path): ...\ndef expand_path(path, cwd=None): ...\ndef files_with_suffix(base_path, suffix): ...\ndef call(command, default=UNDEFINED, ignore_exit_status=False, timeout=None, cwd=None, env=None): ...\ndef get_process_name(): ...\ndef set_process_name(process_name): ...\ndef _set_argv(process_name): ...\ndef _set_prctl_name(process_name): ...\ndef _set_proc_title(process_name): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_size_of", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001050.py"} {"focal_file": "stem/util/system.py", "focal_class": null, "focal_method": "name_by_pid", "tests": "import unittest\n\nclass Test_name_by_pid(unittest.TestCase):\n @patch('stem.util.system.call')\n @patch('stem.util.proc.is_available', Mock(return_value=False))\n @patch('stem.util.system.is_available', Mock(return_value=True))\n def test_name_by_pid_ps(self, call_mock):\n \"\"\"\n Tests the name_by_pid function with ps responses.\n \"\"\"\n responses = {'success': ['COMMAND', 'vim'], 'malformed_command_1': ['COMMAND'], 'malformed_command_2': ['foobar'], 'malformed_command_3': ['NOT_COMMAND', 'vim'], 'no_results': [], 'command_fails': None}\n call_mock.side_effect = mock_call(system.GET_NAME_BY_PID_PS, responses)\n for test_input in responses:\n expected_response = 'vim' if test_input == 'success' else None\n self.assertEqual(expected_response, system.name_by_pid(test_input))\n", "method_code": "def name_by_pid(pid):\n \"\"\"\n Attempts to determine the name a given process is running under (not\n including arguments). This uses...\n\n ::\n\n 1. Information from /proc\n 2. ps -p -o command\n\n :param int pid: process id of the process to be queried\n\n :returns: **str** with the process name, **None** if it can't be determined\n \"\"\"\n process_name = None\n if stem.util.proc.is_available():\n try:\n process_name = stem.util.proc.stats(pid, stem.util.proc.Stat.COMMAND)[0]\n except IOError:\n pass\n if not process_name:\n try:\n results = call(GET_NAME_BY_PID_PS % pid)\n except OSError:\n results = None\n if results and len(results) == 2 and (results[0] == 'COMMAND'):\n process_name = results[1].strip()\n return process_name", "context": "def name_by_pid(pid): ...\ndef is_windows(): ...\ndef is_mac(): ...\ndef is_gentoo(): ...\ndef is_slackware(): ...\ndef is_bsd(): ...\ndef is_available(command, cached=True): ...\ndef is_running(command): ...\ndef size_of(obj, exclude=None): ...\ndef name_by_pid(pid): ...\ndef pid_by_name(process_name, multiple=False): ...\ndef pid_by_port(port): ...\ndef pid_by_open_file(path): ...\ndef pids_by_user(user): ...\ndef cwd(pid): ...\ndef user(pid): ...\ndef start_time(pid): ...\ndef tail(target, lines=None): ...\ndef bsd_jail_id(pid): ...\ndef bsd_jail_path(jid): ...\ndef is_tarfile(path): ...\ndef expand_path(path, cwd=None): ...\ndef files_with_suffix(base_path, suffix): ...\ndef call(command, default=UNDEFINED, ignore_exit_status=False, timeout=None, cwd=None, env=None): ...\ndef get_process_name(): ...\ndef set_process_name(process_name): ...\ndef _set_argv(process_name): ...\ndef _set_prctl_name(process_name): ...\ndef _set_proc_title(process_name): ...\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001051.py"} {"focal_file": "stem/util/system.py", "focal_class": null, "focal_method": "tail", "tests": "import unittest\n\nclass Test_tail(unittest.TestCase):\n def test_tail(self):\n \"\"\"\n Exercise our tail() function with a variety of inputs.\n \"\"\"\n path = os.path.join(os.path.dirname(__file__), 'text_file')\n with open(path, 'rb') as riddle_file:\n self.assertEqual([' both the wicked and sweet.'], list(system.tail(riddle_file, 1)))\n self.assertEqual([], list(system.tail(path, 0)))\n self.assertEqual([' both the wicked and sweet.'], list(system.tail(path, 1)))\n self.assertEqual([' both the wicked and sweet.', \"but I'm with people you meet\"], list(system.tail(path, 2)))\n self.assertEqual(14, len(list(system.tail(path))))\n self.assertEqual(14, len(list(system.tail(path, 200))))\n self.assertRaises(IOError, list, system.tail('/path/doesnt/exist'))\n fd, temp_path = tempfile.mkstemp()\n os.chmod(temp_path, 63)\n self.assertRaises(IOError, list, system.tail(temp_path))\n os.close(fd)\n os.remove(temp_path)\n", "method_code": "def tail(target, lines=None):\n \"\"\"\n Provides lines of a file starting with the end. For instance,\n 'tail -n 50 /tmp/my_log' could be done with...\n\n ::\n\n reversed(list(tail('/tmp/my_log', 50)))\n\n :param str,file target: path or file object to read from\n :param int lines: number of lines to read\n\n :returns: **generator** that reads lines, starting with the end\n\n :raises: **IOError** if unable to read the file\n \"\"\"\n if isinstance(target, str):\n with open(target, 'rb') as target_file:\n for line in tail(target_file, lines):\n yield line\n return\n target.seek(0, 2)\n block_end_byte = target.tell()\n block_number = -1\n content = b''\n while (lines is None or lines > 0) and block_end_byte > 0:\n if block_end_byte - BLOCK_SIZE > 0:\n target.seek(block_number * BLOCK_SIZE, 2)\n content, completed_lines = (target.read(BLOCK_SIZE) + content).split(b'\\n', 1)\n else:\n target.seek(0, 0)\n completed_lines = target.read(block_end_byte) + content\n for line in reversed(completed_lines.splitlines()):\n if lines is None or lines > 0:\n if lines is not None:\n lines -= 1\n yield stem.util.str_tools._to_unicode(line)\n block_end_byte -= BLOCK_SIZE\n block_number -= 1", "context": "def tail(target, lines=None): ...\ndef is_windows(): ...\ndef is_mac(): ...\ndef is_gentoo(): ...\ndef is_slackware(): ...\ndef is_bsd(): ...\ndef is_available(command, cached=True): ...\ndef is_running(command): ...\ndef size_of(obj, exclude=None): ...\ndef name_by_pid(pid): ...\ndef pid_by_name(process_name, multiple=False): ...\ndef pid_by_port(port): ...\ndef pid_by_open_file(path): ...\ndef pids_by_user(user): ...\ndef cwd(pid): ...\ndef user(pid): ...\ndef start_time(pid): ...\ndef tail(target, lines=None): ...\ndef bsd_jail_id(pid): ...\ndef bsd_jail_path(jid): ...\ndef is_tarfile(path): ...\ndef expand_path(path, cwd=None): ...\ndef files_with_suffix(base_path, suffix): ...\ndef call(command, default=UNDEFINED, ignore_exit_status=False, timeout=None, cwd=None, env=None): ...\ndef get_process_name(): ...\ndef set_process_name(process_name): ...\ndef _set_argv(process_name): ...\ndef _set_prctl_name(process_name): ...\ndef _set_proc_title(process_name): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_tail", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001052.py"} {"focal_file": "stem/util/system.py", "focal_class": null, "focal_method": "bsd_jail_path", "tests": "import unittest\n\nclass Test_bsd_jail_path(unittest.TestCase):\n @patch('stem.util.system.call')\n @patch('stem.util.system.is_available', Mock(return_value=True))\n def test_bsd_jail_path(self, call_mock):\n \"\"\"\n Tests the bsd_jail_path function.\n \"\"\"\n call_mock.return_value = []\n self.assertEqual(None, system.bsd_jail_path(1))\n call_mock.side_effect = mock_call(system.GET_BSD_JAIL_PATH % '1', GET_BSD_JAIL_PATH_RESULTS)\n self.assertEqual('/usr/jails/tor-jail', system.bsd_jail_path(1))\n", "method_code": "def bsd_jail_path(jid):\n \"\"\"\n Provides the path of the given FreeBSD jail.\n\n :param int jid: jail id to be queried\n\n :returns: **str** of the path prefix, **None** if this can't be determined\n \"\"\"\n if jid != 0:\n jls_output = call(GET_BSD_JAIL_PATH % jid, [])\n if len(jls_output) == 2 and len(jls_output[1].split()) == 4:\n return jls_output[1].split()[3]\n return None", "context": "def bsd_jail_path(jid): ...\ndef is_windows(): ...\ndef is_mac(): ...\ndef is_gentoo(): ...\ndef is_slackware(): ...\ndef is_bsd(): ...\ndef is_available(command, cached=True): ...\ndef is_running(command): ...\ndef size_of(obj, exclude=None): ...\ndef name_by_pid(pid): ...\ndef pid_by_name(process_name, multiple=False): ...\ndef pid_by_port(port): ...\ndef pid_by_open_file(path): ...\ndef pids_by_user(user): ...\ndef cwd(pid): ...\ndef user(pid): ...\ndef start_time(pid): ...\ndef tail(target, lines=None): ...\ndef bsd_jail_id(pid): ...\ndef bsd_jail_path(jid): ...\ndef is_tarfile(path): ...\ndef expand_path(path, cwd=None): ...\ndef files_with_suffix(base_path, suffix): ...\ndef call(command, default=UNDEFINED, ignore_exit_status=False, timeout=None, cwd=None, env=None): ...\ndef get_process_name(): ...\ndef set_process_name(process_name): ...\ndef _set_argv(process_name): ...\ndef _set_prctl_name(process_name): ...\ndef _set_proc_title(process_name): ...\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001053.py"} {"focal_file": "stem/util/conf.py", "focal_class": null, "focal_method": "config_dict", "tests": "import unittest\n\nclass Test_config_dict(unittest.TestCase):\n def test_config_dict(self):\n \"\"\"\n Tests the config_dict function.\n \"\"\"\n my_config = {'bool_value': False, 'int_value': 5, 'str_value': 'hello', 'list_value': []}\n test_config = stem.util.conf.get_config('unit_testing')\n test_config.set('bool_value', 'true')\n my_config = stem.util.conf.config_dict('unit_testing', my_config)\n self.assertEqual(True, my_config['bool_value'])\n test_config.set('str_value', 'me')\n self.assertEqual('me', my_config['str_value'])\n test_config.set('int_value', '7a')\n self.assertEqual(5, my_config['int_value'])\n test_config.set('list_value', 'a', False)\n self.assertEqual(['a'], my_config['list_value'])\n test_config.set('list_value', 'b', False)\n self.assertEqual(['a', 'b'], my_config['list_value'])\n test_config.set('list_value', 'c', False)\n self.assertEqual(['a', 'b', 'c'], my_config['list_value'])\n", "method_code": "def config_dict(handle, conf_mappings, handler=None):\n \"\"\"\n Makes a dictionary that stays synchronized with a configuration.\n\n This takes a dictionary of 'config_key => default_value' mappings and\n changes the values to reflect our current configuration. This will leave\n the previous values alone if...\n\n * we don't have a value for that config_key\n * we can't convert our value to be the same type as the default_value\n\n If a handler is provided then this is called just prior to assigning new\n values to the config_dict. The handler function is expected to accept the\n (key, value) for the new values and return what we should actually insert\n into the dictionary. If this returns None then the value is updated as\n normal.\n\n For more information about how we convert types see our\n :func:`~stem.util.conf.Config.get` method.\n\n **The dictionary you get from this is manged by the Config class and should\n be treated as being read-only.**\n\n :param str handle: unique identifier for a config instance\n :param dict conf_mappings: config key/value mappings used as our defaults\n :param functor handler: function referred to prior to assigning values\n \"\"\"\n selected_config = get_config(handle)\n selected_config.add_listener(_SyncListener(conf_mappings, handler).update)\n return conf_mappings", "context": "def config_dict(handle, conf_mappings, handler=None): ...\ndef config_dict(handle, conf_mappings, handler=None): ...\ndef get_config(handle): ...\ndef uses_settings(handle, path, lazy_load=True): ...\ndef parse_enum(key, value, enumeration): ...\ndef parse_enum_csv(key, value, enumeration, count=None): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_config_dict", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001054.py"} {"focal_file": "stem/util/conf.py", "focal_class": null, "focal_method": "parse_enum", "tests": "import unittest\n\nclass Test_parse_enum(unittest.TestCase):\n def test_parse_enum(self):\n \"\"\"\n Tests the parse_enum function.\n \"\"\"\n Insects = stem.util.enum.Enum('BUTTERFLY', 'LADYBUG', 'CRICKET')\n self.assertEqual(Insects.LADYBUG, parse_enum('my_option', 'ladybug', Insects))\n self.assertRaises(ValueError, parse_enum, 'my_option', 'ugabuga', Insects)\n self.assertRaises(ValueError, parse_enum, 'my_option', 'ladybug, cricket', Insects)\n", "method_code": "def parse_enum(key, value, enumeration):\n \"\"\"\n Provides the enumeration value for a given key. This is a case insensitive\n lookup and raises an exception if the enum key doesn't exist.\n\n :param str key: configuration key being looked up\n :param str value: value to be parsed\n :param stem.util.enum.Enum enumeration: enumeration the values should be in\n\n :returns: enumeration value\n\n :raises: **ValueError** if the **value** isn't among the enumeration keys\n \"\"\"\n return parse_enum_csv(key, value, enumeration, 1)[0]", "context": "def parse_enum(key, value, enumeration): ...\ndef config_dict(handle, conf_mappings, handler=None): ...\ndef get_config(handle): ...\ndef uses_settings(handle, path, lazy_load=True): ...\ndef parse_enum(key, value, enumeration): ...\ndef parse_enum_csv(key, value, enumeration, count=None): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_parse_enum", "smells": [1, 0, 0, 0, 1, 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": [1, 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": "stem/util/conf.py", "focal_class": null, "focal_method": "parse_enum_csv", "tests": "import unittest\n\nclass Test_parse_enum_csv(unittest.TestCase):\n def test_parse_enum_csv(self):\n \"\"\"\n Tests the parse_enum_csv function.\n \"\"\"\n Insects = stem.util.enum.Enum('BUTTERFLY', 'LADYBUG', 'CRICKET')\n self.assertEqual([Insects.LADYBUG], parse_enum_csv('my_option', 'ladybug', Insects))\n self.assertEqual([Insects.LADYBUG], parse_enum_csv('my_option', 'Ladybug', Insects))\n self.assertEqual([Insects.LADYBUG], parse_enum_csv('my_option', 'LaDyBuG', Insects))\n self.assertEqual([Insects.LADYBUG], parse_enum_csv('my_option', 'LADYBUG', Insects))\n self.assertEqual([], parse_enum_csv('my_option', '', Insects))\n self.assertEqual([Insects.LADYBUG], parse_enum_csv('my_option', 'ladybug', Insects))\n self.assertEqual([Insects.LADYBUG, Insects.BUTTERFLY], parse_enum_csv('my_option', 'ladybug, butterfly', Insects))\n self.assertEqual([Insects.LADYBUG, Insects.BUTTERFLY, Insects.CRICKET], parse_enum_csv('my_option', 'ladybug, butterfly, cricket', Insects))\n self.assertEqual([Insects.LADYBUG, Insects.BUTTERFLY], parse_enum_csv('my_option', 'ladybug, butterfly', Insects, 2))\n self.assertEqual([Insects.LADYBUG, Insects.BUTTERFLY], parse_enum_csv('my_option', 'ladybug, butterfly', Insects, (1, 2)))\n self.assertEqual([Insects.LADYBUG, Insects.BUTTERFLY], parse_enum_csv('my_option', 'ladybug, butterfly', Insects, (2, 3)))\n self.assertEqual([Insects.LADYBUG, Insects.BUTTERFLY], parse_enum_csv('my_option', 'ladybug, butterfly', Insects, (2, 2)))\n self.assertRaises(ValueError, parse_enum_csv, 'my_option', 'ugabuga', Insects)\n self.assertRaises(ValueError, parse_enum_csv, 'my_option', 'ladybug, ugabuga', Insects)\n self.assertRaises(ValueError, parse_enum_csv, 'my_option', 'ladybug butterfly', Insects)\n self.assertRaises(ValueError, parse_enum_csv, 'my_option', 'ladybug', Insects, 2)\n self.assertRaises(ValueError, parse_enum_csv, 'my_option', 'ladybug', Insects, (2, 3))\n", "method_code": "def parse_enum_csv(key, value, enumeration, count=None):\n \"\"\"\n Parses a given value as being a comma separated listing of enumeration keys,\n returning the corresponding enumeration values. This is intended to be a\n helper for config handlers. The checks this does are case insensitive.\n\n The **count** attribute can be used to make assertions based on the number of\n values. This can be...\n\n * None to indicate that there's no restrictions.\n * An int to indicate that we should have this many values.\n * An (int, int) tuple to indicate the range that values can be in. This range\n is inclusive and either can be None to indicate the lack of a lower or\n upper bound.\n\n :param str key: configuration key being looked up\n :param str value: value to be parsed\n :param stem.util.enum.Enum enumeration: enumeration the values should be in\n :param int,tuple count: validates that we have this many items\n\n :returns: list with the enumeration values\n\n :raises: **ValueError** if the count assertion fails or the **value** entries\n don't match the enumeration keys\n \"\"\"\n values = [val.upper().strip() for val in value.split(',')]\n if values == ['']:\n return []\n if count is None:\n pass\n elif isinstance(count, int):\n if len(values) != count:\n raise ValueError(\"Config entry '%s' is expected to be %i comma separated values, got '%s'\" % (key, count, value))\n elif isinstance(count, tuple) and len(count) == 2:\n minimum, maximum = count\n if minimum is not None and len(values) < minimum:\n raise ValueError(\"Config entry '%s' must have at least %i comma separated values, got '%s'\" % (key, minimum, value))\n if maximum is not None and len(values) > maximum:\n raise ValueError(\"Config entry '%s' can have at most %i comma separated values, got '%s'\" % (key, maximum, value))\n else:\n raise ValueError(\"The count must be None, an int, or two value tuple. Got '%s' (%s)'\" % (count, type(count)))\n result = []\n enum_keys = [k.upper() for k in list(enumeration.keys())]\n enum_values = list(enumeration)\n for val in values:\n if val in enum_keys:\n result.append(enum_values[enum_keys.index(val)])\n else:\n raise ValueError(\"The '%s' entry of config entry '%s' wasn't in the enumeration (expected %s)\" % (val, key, ', '.join(enum_keys)))\n return result", "context": "def parse_enum_csv(key, value, enumeration, count=None): ...\ndef config_dict(handle, conf_mappings, handler=None): ...\ndef get_config(handle): ...\ndef uses_settings(handle, path, lazy_load=True): ...\ndef parse_enum(key, value, enumeration): ...\ndef parse_enum_csv(key, value, enumeration, count=None): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_parse_enum_csv", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001056.py"} {"focal_file": "stem/util/conf.py", "focal_class": null, "focal_method": "clear", "tests": "import unittest\n\nclass Test_clear(unittest.TestCase):\n def test_clear(self):\n \"\"\"\n Tests the clear method.\n \"\"\"\n test_config = stem.util.conf.get_config('unit_testing')\n self.assertEqual([], list(test_config.keys()))\n test_config.clear()\n self.assertEqual([], list(test_config.keys()))\n test_config.set('hello', 'world')\n self.assertEqual(['hello'], list(test_config.keys()))\n test_config.clear()\n self.assertEqual([], list(test_config.keys()))\n", "method_code": " def clear(self):\n \"\"\"\n Drops the configuration contents and reverts back to a blank, unloaded\n state.\n \"\"\"\n with self._contents_lock:\n self._contents.clear()\n self._requested_keys = set()\n ", "context": "class Config(object):\n def clear(self): ...\n def __init__(self): ...\n def load(self, path=None, commenting=True): ...\n def save(self, path=None): ...\n def add_listener(self, listener, backfill=True): ...\n def clear_listeners(self): ...\n def keys(self): ...\n def unused_keys(self): ...\n def set(self, key, value, overwrite=True): ...\n def get(self, key, default=None): ...\n def get_value(self, key, default=None, multiple=False): ...\n def __getitem__(self, key): ...\n\n self._path = None\n self._contents = OrderedDict()\n self._listeners = []\n self._contents_lock = threading.RLock()\n self._requested_keys = set()\n self._settings_loaded = False\n", "repository": "illumineinteractive/stem", "test_name": "test_clear", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001057.py"} {"focal_file": "stem/util/conf.py", "focal_class": null, "focal_method": "add_listener", "tests": "import unittest\n\nclass Test_add_listener(unittest.TestCase):\n def test_listeners(self):\n \"\"\"\n Tests the add_listener and clear_listeners methods.\n \"\"\"\n listener_received_keys = []\n\n def test_listener(config, key):\n self.assertEqual(config, stem.util.conf.get_config('unit_testing'))\n listener_received_keys.append(key)\n test_config = stem.util.conf.get_config('unit_testing')\n test_config.add_listener(test_listener)\n self.assertEqual([], listener_received_keys)\n test_config.set('hello', 'world')\n self.assertEqual(['hello'], listener_received_keys)\n test_config.clear_listeners()\n test_config.set('foo', 'bar')\n self.assertEqual(['hello'], listener_received_keys)\n", "method_code": " def add_listener(self, listener, backfill=True):\n \"\"\"\n Registers the function to be notified of configuration updates. Listeners\n are expected to be functors which accept (config, key).\n \n :param functor listener: function to be notified when our configuration is changed\n :param bool backfill: calls the function with our current values if **True**\n \"\"\"\n with self._contents_lock:\n self._listeners.append(listener)\n if backfill:\n for key in self.keys():\n listener(self, key)\n ", "context": "class Config(object):\n def add_listener(self, listener, backfill=True): ...\n def __init__(self): ...\n def load(self, path=None, commenting=True): ...\n def save(self, path=None): ...\n def clear(self): ...\n def clear_listeners(self): ...\n def keys(self): ...\n def unused_keys(self): ...\n def set(self, key, value, overwrite=True): ...\n def get(self, key, default=None): ...\n def get_value(self, key, default=None, multiple=False): ...\n def __getitem__(self, key): ...\n\n self._path = None\n self._contents = OrderedDict()\n self._listeners = []\n self._contents_lock = threading.RLock()\n self._requested_keys = set()\n self._settings_loaded = False\n", "repository": "illumineinteractive/stem", "test_name": "test_listeners", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001058.py"} {"focal_file": "stem/util/conf.py", "focal_class": null, "focal_method": "unused_keys", "tests": "import unittest\n\nclass Test_unused_keys(unittest.TestCase):\n def test_unused_keys(self):\n \"\"\"\n Tests the unused_keys method.\n \"\"\"\n test_config = stem.util.conf.get_config('unit_testing')\n test_config.set('hello', 'world')\n test_config.set('foo', 'bar')\n test_config.set('pw', '12345')\n test_config.get('hello')\n test_config.get_value('foo')\n self.assertEqual(set(['pw']), test_config.unused_keys())\n test_config.get('pw')\n self.assertEqual(set(), test_config.unused_keys())\n", "method_code": " def unused_keys(self):\n \"\"\"\n Provides the configuration keys that have never been provided to a caller\n via :func:`~stem.util.conf.config_dict` or the\n :func:`~stem.util.conf.Config.get` and\n :func:`~stem.util.conf.Config.get_value` methods.\n \n :returns: **set** of configuration keys we've loaded but have never been requested\n \"\"\"\n return set(self.keys()).difference(self._requested_keys)\n ", "context": "class Config(object):\n def unused_keys(self): ...\n def __init__(self): ...\n def load(self, path=None, commenting=True): ...\n def save(self, path=None): ...\n def clear(self): ...\n def add_listener(self, listener, backfill=True): ...\n def clear_listeners(self): ...\n def keys(self): ...\n def set(self, key, value, overwrite=True): ...\n def get(self, key, default=None): ...\n def get_value(self, key, default=None, multiple=False): ...\n def __getitem__(self, key): ...\n\n self._path = None\n self._contents = OrderedDict()\n self._listeners = []\n self._contents_lock = threading.RLock()\n self._requested_keys = set()\n self._settings_loaded = False\n", "repository": "illumineinteractive/stem", "test_name": "test_unused_keys", "smells": [1, 0, 0, 0, 1, 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": [1, 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": "stem/util/conf.py", "focal_class": null, "focal_method": "get", "tests": "import unittest\n\nclass Test_get(unittest.TestCase):\n def test_get(self):\n \"\"\"\n Tests the get and get_value methods.\n \"\"\"\n test_config = stem.util.conf.get_config('unit_testing')\n test_config.set('bool_value', 'true')\n test_config.set('int_value', '11')\n test_config.set('float_value', '11.1')\n test_config.set('str_value', 'world')\n test_config.set('list_value', 'a', False)\n test_config.set('list_value', 'b', False)\n test_config.set('list_value', 'c', False)\n test_config.set('map_value', 'foo => bar')\n self.assertEqual(5, test_config.get('foo', 5))\n self.assertEqual(5, test_config.get('bool_value', 5))\n self.assertEqual('11', test_config.get('int_value'))\n self.assertEqual(True, test_config.get('bool_value', False))\n self.assertEqual(11, test_config.get('int_value', 0))\n self.assertEqual(11.1, test_config.get('float_value', 0.0))\n self.assertEqual('world', test_config.get('str_value', ''))\n self.assertEqual(['a', 'b', 'c'], test_config.get('list_value', []))\n self.assertEqual(('a', 'b', 'c'), test_config.get('list_value', ()))\n self.assertEqual({'foo': 'bar'}, test_config.get('map_value', {}))\n self.assertEqual('c', test_config.get_value('list_value'))\n self.assertEqual(['a', 'b', 'c'], test_config.get_value('list_value', multiple=True))\n self.assertEqual(None, test_config.get_value('foo'))\n self.assertEqual('hello', test_config.get_value('foo', 'hello'))\n", "method_code": " def get(self, key, default=None):\n \"\"\"\n Fetches the given configuration, using the key and default value to\n determine the type it should be. Recognized inferences are:\n \n * **default is a boolean => boolean**\n \n * values are case insensitive\n * provides the default if the value isn't \"true\" or \"false\"\n \n * **default is an integer => int**\n \n * provides the default if the value can't be converted to an int\n \n * **default is a float => float**\n \n * provides the default if the value can't be converted to a float\n \n * **default is a list => list**\n \n * string contents for all configuration values with this key\n \n * **default is a tuple => tuple**\n \n * string contents for all configuration values with this key\n \n * **default is a dictionary => dict**\n \n * values without \"=>\" in them are ignored\n * values are split into key/value pairs on \"=>\" with extra whitespace\n stripped\n \n :param str key: config setting to be fetched\n :param default object: value provided if no such key exists or fails to be converted\n \n :returns: given configuration value with its type inferred with the above rules\n \"\"\"\n is_multivalue = isinstance(default, (list, tuple, dict))\n val = self.get_value(key, default, is_multivalue)\n if val == default:\n return val\n if isinstance(default, bool):\n if val.lower() == 'true':\n val = True\n elif val.lower() == 'false':\n val = False\n else:\n log.debug(\"Config entry '%s' is expected to be a boolean, defaulting to '%s'\" % (key, str(default)))\n val = default\n elif isinstance(default, int):\n try:\n val = int(val)\n except ValueError:\n log.debug(\"Config entry '%s' is expected to be an integer, defaulting to '%i'\" % (key, default))\n val = default\n elif isinstance(default, float):\n try:\n val = float(val)\n except ValueError:\n log.debug(\"Config entry '%s' is expected to be a float, defaulting to '%f'\" % (key, default))\n val = default\n elif isinstance(default, list):\n val = list(val)\n elif isinstance(default, tuple):\n val = tuple(val)\n elif isinstance(default, dict):\n val_map = OrderedDict()\n for entry in val:\n if '=>' in entry:\n entry_key, entry_val = entry.split('=>', 1)\n val_map[entry_key.strip()] = entry_val.strip()\n else:\n log.debug('Ignoring invalid %s config entry (expected a mapping, but \"%s\" was missing \"=>\")' % (key, entry))\n val = val_map\n return val\n ", "context": "class Config(object):\n def get(self, key, default=None): ...\n def __init__(self): ...\n def load(self, path=None, commenting=True): ...\n def save(self, path=None): ...\n def clear(self): ...\n def add_listener(self, listener, backfill=True): ...\n def clear_listeners(self): ...\n def keys(self): ...\n def unused_keys(self): ...\n def set(self, key, value, overwrite=True): ...\n def get_value(self, key, default=None, multiple=False): ...\n def __getitem__(self, key): ...\n\n self._path = None\n self._contents = OrderedDict()\n self._listeners = []\n self._contents_lock = threading.RLock()\n self._requested_keys = set()\n self._settings_loaded = False\n", "repository": "illumineinteractive/stem", "test_name": "test_get", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001060.py"} {"focal_file": "stem/util/str_tools.py", "focal_class": null, "focal_method": "_to_int", "tests": "import unittest\n\nclass Test_to_int(unittest.TestCase):\n def test_to_int(self):\n \"\"\"\n Checks the _to_int() function.\n \"\"\"\n test_inputs = {'': 0, 'h': 104, 'hi': 26729, 'hello': 448378203247, str_tools._to_bytes('hello'): 448378203247, str_tools._to_unicode('hello'): 448378203247}\n for arg, expected in test_inputs.items():\n self.assertEqual(expected, str_tools._to_int(arg))\n", "method_code": "def _to_int(msg):\n \"\"\"\n Serializes a string to a number.\n\n :param str msg: string to be serialized\n\n :returns: **int** representation of the string\n \"\"\"\n if stem.prereq.is_python_3() and isinstance(msg, bytes):\n return sum([pow(256, len(msg) - i - 1) * c for i, c in enumerate(msg)])\n else:\n return sum([pow(256, len(msg) - i - 1) * ord(c) for i, c in enumerate(msg)])", "context": "def _to_int(msg): ...\ndef _to_bytes(msg): ...\ndef _to_unicode(msg): ...\ndef _to_int(msg): ...\ndef _to_camel_case(label, divider='_', joiner=' '): ...\ndef _split_by_length(msg, size): ...\ndef crop(msg, size, min_word_length=4, min_crop=0, ending=Ending.ELLIPSE, get_remainder=False): ...\ndef size_label(byte_count, decimal=0, is_long=False, is_bytes=True, round=False): ...\ndef time_label(seconds, decimal=0, is_long=False): ...\ndef time_labels(seconds, is_long=False): ...\ndef short_time_label(seconds): ...\ndef parse_short_time_label(label): ...\ndef _parse_timestamp(entry): ...\ndef _parse_iso_timestamp(entry): ...\ndef _get_label(units, count, decimal, is_long, round=False): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_to_int", "smells": [1, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001061.py"} {"focal_file": "stem/util/str_tools.py", "focal_class": null, "focal_method": "_to_camel_case", "tests": "import unittest\n\nclass Test_to_camel_case(unittest.TestCase):\n def test_to_camel_case(self):\n \"\"\"\n Checks the _to_camel_case() function.\n \"\"\"\n self.assertEqual('I Like Pepperjack!', str_tools._to_camel_case('I_LIKE_PEPPERJACK!'))\n self.assertEqual('', str_tools._to_camel_case(''))\n self.assertEqual('Hello', str_tools._to_camel_case('hello'))\n self.assertEqual('Hello', str_tools._to_camel_case('HELLO'))\n self.assertEqual('Hello World', str_tools._to_camel_case('hello__world'))\n self.assertEqual('Hello\\tworld', str_tools._to_camel_case('hello\\tWORLD'))\n self.assertEqual('Hello\\t\\tWorld', str_tools._to_camel_case('hello__world', '_', '\\t'))\n", "method_code": "def _to_camel_case(label, divider='_', joiner=' '):\n \"\"\"\n Converts the given string to camel case, ie:\n\n ::\n\n >>> _to_camel_case('I_LIKE_PEPPERJACK!')\n 'I Like Pepperjack!'\n\n :param str label: input string to be converted\n :param str divider: word boundary\n :param str joiner: replacement for word boundaries\n\n :returns: camel cased string\n \"\"\"\n words = []\n for entry in label.split(divider):\n if len(entry) == 0:\n words.append('')\n elif len(entry) == 1:\n words.append(entry.upper())\n else:\n words.append(entry[0].upper() + entry[1:].lower())\n return joiner.join(words)", "context": "def _to_camel_case(label, divider='_', joiner=' '): ...\ndef _to_bytes(msg): ...\ndef _to_unicode(msg): ...\ndef _to_int(msg): ...\ndef _to_camel_case(label, divider='_', joiner=' '): ...\ndef _split_by_length(msg, size): ...\ndef crop(msg, size, min_word_length=4, min_crop=0, ending=Ending.ELLIPSE, get_remainder=False): ...\ndef size_label(byte_count, decimal=0, is_long=False, is_bytes=True, round=False): ...\ndef time_label(seconds, decimal=0, is_long=False): ...\ndef time_labels(seconds, is_long=False): ...\ndef short_time_label(seconds): ...\ndef parse_short_time_label(label): ...\ndef _parse_timestamp(entry): ...\ndef _parse_iso_timestamp(entry): ...\ndef _get_label(units, count, decimal, is_long, round=False): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_to_camel_case", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001062.py"} {"focal_file": "stem/util/str_tools.py", "focal_class": null, "focal_method": "_split_by_length", "tests": "import unittest\n\nclass Test_split_by_length(unittest.TestCase):\n def test_split_by_length(self):\n self.assertEqual(['h', 'e', 'l', 'l', 'o'], str_tools._split_by_length('hello', 1))\n self.assertEqual(['he', 'll', 'o'], str_tools._split_by_length('hello', 2))\n self.assertEqual(['hel', 'lo'], str_tools._split_by_length('hello', 3))\n self.assertEqual(['hell', 'o'], str_tools._split_by_length('hello', 4))\n self.assertEqual(['hello'], str_tools._split_by_length('hello', 5))\n self.assertEqual(['hello'], str_tools._split_by_length('hello', 6))\n", "method_code": "def _split_by_length(msg, size):\n \"\"\"\n Splits a string into a list of strings up to the given size.\n\n ::\n\n >>> _split_by_length('hello', 2)\n ['he', 'll', 'o']\n\n :param str msg: string to split\n :param int size: number of characters to chunk into\n\n :returns: **list** with chunked string components\n \"\"\"\n return [msg[i:i + size] for i in range(0, len(msg), size)]", "context": "def _split_by_length(msg, size): ...\ndef _to_bytes(msg): ...\ndef _to_unicode(msg): ...\ndef _to_int(msg): ...\ndef _to_camel_case(label, divider='_', joiner=' '): ...\ndef _split_by_length(msg, size): ...\ndef crop(msg, size, min_word_length=4, min_crop=0, ending=Ending.ELLIPSE, get_remainder=False): ...\ndef size_label(byte_count, decimal=0, is_long=False, is_bytes=True, round=False): ...\ndef time_label(seconds, decimal=0, is_long=False): ...\ndef time_labels(seconds, is_long=False): ...\ndef short_time_label(seconds): ...\ndef parse_short_time_label(label): ...\ndef _parse_timestamp(entry): ...\ndef _parse_iso_timestamp(entry): ...\ndef _get_label(units, count, decimal, is_long, round=False): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_split_by_length", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001063.py"} {"focal_file": "stem/util/str_tools.py", "focal_class": null, "focal_method": "crop", "tests": "import unittest\n\nclass Test_crop(unittest.TestCase):\n def test_crop(self):\n self.assertEqual('This is a looo...', str_tools.crop('This is a looooong message', 17))\n self.assertEqual('This is a...', str_tools.crop('This is a looooong message', 12))\n self.assertEqual('', str_tools.crop('This is a looooong message', 3))\n self.assertEqual('', str_tools.crop('This is a looooong message', 0))\n", "method_code": "def crop(msg, size, min_word_length=4, min_crop=0, ending=Ending.ELLIPSE, get_remainder=False):\n \"\"\"\n Shortens a string to a given length.\n\n If we crop content then a given ending is included (counting itself toward\n the size limitation). This crops on word breaks so we only include a word if\n we can display at least **min_word_length** characters of it.\n\n If there isn't room for even a truncated single word (or one word plus the\n ellipse if including those) then this provides an empty string.\n\n If a cropped string ends with a comma or period then it's stripped (unless\n we're providing the remainder back). For example...\n\n >>> crop('This is a looooong message', 17)\n 'This is a looo...'\n\n >>> crop('This is a looooong message', 12)\n 'This is a...'\n\n >>> crop('This is a looooong message', 3)\n ''\n\n The whole point of this method is to provide human friendly croppings, and as\n such details of how this works might change in the future. Callers should not\n rely on the details of how this crops.\n\n .. versionadded:: 1.3.0\n\n :param str msg: text to be processed\n :param int size: space available for text\n :param int min_word_length: minimum characters before which a word is\n dropped, requires whole word if **None**\n :param int min_crop: minimum characters that must be dropped if a word is\n cropped\n :param Ending ending: type of ending used when truncating, no special\n truncation is used if **None**\n :param bool get_remainder: returns a tuple with the second part being the\n cropped portion of the message\n\n :returns: **str** of the text truncated to the given length\n \"\"\"\n if len(msg) <= size:\n return (msg, '') if get_remainder else msg\n if size < 0:\n raise ValueError(\"Crop size can't be negative (received %i)\" % size)\n elif min_word_length and min_word_length < 0:\n raise ValueError(\"Crop's min_word_length can't be negative (received %i)\" % min_word_length)\n elif min_crop < 0:\n raise ValueError(\"Crop's min_crop can't be negative (received %i)\" % min_crop)\n if ending == Ending.ELLIPSE:\n if size < 3:\n return ('', msg) if get_remainder else ''\n size -= 3\n elif min_word_length and ending == Ending.HYPHEN:\n min_word_length += 1\n if min_word_length is None:\n min_word_length = sys.maxsize\n last_wordbreak = msg.rfind(' ', 0, size + 1)\n if last_wordbreak == -1:\n if size < min_word_length:\n return ('', msg) if get_remainder else ''\n include_crop = True\n else:\n last_wordbreak = len(msg[:last_wordbreak].rstrip())\n include_crop = size - last_wordbreak - 1 >= min_word_length\n if include_crop and min_crop:\n next_wordbreak = msg.find(' ', size)\n if next_wordbreak == -1:\n next_wordbreak = len(msg)\n include_crop = next_wordbreak - size + 1 >= min_crop\n if include_crop:\n return_msg, remainder = (msg[:size], msg[size:])\n if ending == Ending.HYPHEN:\n remainder = return_msg[-1] + remainder\n return_msg = return_msg[:-1].rstrip() + '-'\n else:\n return_msg, remainder = (msg[:last_wordbreak], msg[last_wordbreak:])\n if not get_remainder and return_msg and (return_msg[-1] in (',', '.')):\n return_msg = return_msg[:-1]\n if ending == Ending.ELLIPSE:\n return_msg = return_msg.rstrip() + '...'\n return (return_msg, remainder) if get_remainder else return_msg", "context": "def crop(msg, size, min_word_length=4, min_crop=0, ending=Ending.ELLIPSE, get_remainder=False): ...\ndef _to_bytes(msg): ...\ndef _to_unicode(msg): ...\ndef _to_int(msg): ...\ndef _to_camel_case(label, divider='_', joiner=' '): ...\ndef _split_by_length(msg, size): ...\ndef crop(msg, size, min_word_length=4, min_crop=0, ending=Ending.ELLIPSE, get_remainder=False): ...\ndef size_label(byte_count, decimal=0, is_long=False, is_bytes=True, round=False): ...\ndef time_label(seconds, decimal=0, is_long=False): ...\ndef time_labels(seconds, is_long=False): ...\ndef short_time_label(seconds): ...\ndef parse_short_time_label(label): ...\ndef _parse_timestamp(entry): ...\ndef _parse_iso_timestamp(entry): ...\ndef _get_label(units, count, decimal, is_long, round=False): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_crop", "smells": [1, 0, 0, 0, 1, 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": [1, 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": "stem/util/str_tools.py", "focal_class": null, "focal_method": "size_label", "tests": "import unittest\n\nclass Test_size_label(unittest.TestCase):\n def test_size_label(self):\n \"\"\"\n Checks the size_label() function.\n \"\"\"\n self.assertEqual('1 MB', str_tools.size_label(2000000))\n self.assertEqual('1.02 KB', str_tools.size_label(1050, 2))\n self.assertEqual('1.025 Kilobytes', str_tools.size_label(1050, 3, True))\n self.assertEqual('1 KB', str_tools.size_label(1050, 0, round=True))\n self.assertEqual('1.0 KB', str_tools.size_label(1050, 1, round=True))\n self.assertEqual('1.03 KB', str_tools.size_label(1050, 2, round=True))\n self.assertEqual('1.025 KB', str_tools.size_label(1050, 3, round=True))\n self.assertEqual('0 B', str_tools.size_label(0))\n self.assertEqual('0 Bytes', str_tools.size_label(0, is_long=True))\n self.assertEqual('0.00 B', str_tools.size_label(0, 2))\n self.assertEqual('-10 B', str_tools.size_label(-10))\n self.assertEqual('80 b', str_tools.size_label(10, is_bytes=False))\n self.assertEqual('-1 MB', str_tools.size_label(-2000000))\n self.assertEqual('23.43 Kb', str_tools.size_label(3000, 2, is_bytes=False))\n self.assertRaises(TypeError, str_tools.size_label, None)\n self.assertRaises(TypeError, str_tools.size_label, 'hello world')\n", "method_code": "def size_label(byte_count, decimal=0, is_long=False, is_bytes=True, round=False):\n \"\"\"\n Converts a number of bytes into a human readable label in its most\n significant units. For instance, 7500 bytes would return \"7 KB\". If the\n is_long option is used this expands unit labels to be the properly pluralized\n full word (for instance 'Kilobytes' rather than 'KB'). Units go up through\n petabytes.\n\n ::\n\n >>> size_label(2000000)\n '1 MB'\n\n >>> size_label(1050, 2)\n '1.02 KB'\n\n >>> size_label(1050, 3, True)\n '1.025 Kilobytes'\n\n .. versionchanged:: 1.6.0\n Added round argument.\n\n :param int byte_count: number of bytes to be converted\n :param int decimal: number of decimal digits to be included\n :param bool is_long: expands units label\n :param bool is_bytes: provides units in bytes if **True**, bits otherwise\n :param bool round: rounds normally if **True**, otherwise rounds down\n\n :returns: **str** with human readable representation of the size\n \"\"\"\n if is_bytes:\n return _get_label(SIZE_UNITS_BYTES, byte_count, decimal, is_long, round)\n else:\n return _get_label(SIZE_UNITS_BITS, byte_count, decimal, is_long, round)", "context": "def size_label(byte_count, decimal=0, is_long=False, is_bytes=True, round=False): ...\ndef _to_bytes(msg): ...\ndef _to_unicode(msg): ...\ndef _to_int(msg): ...\ndef _to_camel_case(label, divider='_', joiner=' '): ...\ndef _split_by_length(msg, size): ...\ndef crop(msg, size, min_word_length=4, min_crop=0, ending=Ending.ELLIPSE, get_remainder=False): ...\ndef size_label(byte_count, decimal=0, is_long=False, is_bytes=True, round=False): ...\ndef time_label(seconds, decimal=0, is_long=False): ...\ndef time_labels(seconds, is_long=False): ...\ndef short_time_label(seconds): ...\ndef parse_short_time_label(label): ...\ndef _parse_timestamp(entry): ...\ndef _parse_iso_timestamp(entry): ...\ndef _get_label(units, count, decimal, is_long, round=False): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_size_label", "smells": [1, 0, 0, 0, 1, 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": [1, 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": "stem/util/str_tools.py", "focal_class": null, "focal_method": "time_label", "tests": "import unittest\n\nclass Test_time_label(unittest.TestCase):\n def test_time_label(self):\n \"\"\"\n Checks the time_label() function.\n \"\"\"\n self.assertEqual('2h', str_tools.time_label(10000))\n self.assertEqual('1.0 minute', str_tools.time_label(61, 1, True))\n self.assertEqual('1.01 minutes', str_tools.time_label(61, 2, True))\n self.assertEqual('0s', str_tools.time_label(0))\n self.assertEqual('0 seconds', str_tools.time_label(0, is_long=True))\n self.assertEqual('0.00s', str_tools.time_label(0, 2))\n self.assertEqual('-10s', str_tools.time_label(-10))\n self.assertRaises(TypeError, str_tools.time_label, None)\n self.assertRaises(TypeError, str_tools.time_label, 'hello world')\n", "method_code": "def time_label(seconds, decimal=0, is_long=False):\n \"\"\"\n Converts seconds into a time label truncated to its most significant units.\n For instance, 7500 seconds would return \"2h\". Units go up through days.\n\n This defaults to presenting single character labels, but if the is_long\n option is used this expands labels to be the full word (space included and\n properly pluralized). For instance, \"4h\" would be \"4 hours\" and \"1m\" would\n become \"1 minute\".\n\n ::\n\n >>> time_label(10000)\n '2h'\n\n >>> time_label(61, 1, True)\n '1.0 minute'\n\n >>> time_label(61, 2, True)\n '1.01 minutes'\n\n :param int seconds: number of seconds to be converted\n :param int decimal: number of decimal digits to be included\n :param bool is_long: expands units label\n\n :returns: **str** with human readable representation of the time\n \"\"\"\n return _get_label(TIME_UNITS, seconds, decimal, is_long)", "context": "def time_label(seconds, decimal=0, is_long=False): ...\ndef _to_bytes(msg): ...\ndef _to_unicode(msg): ...\ndef _to_int(msg): ...\ndef _to_camel_case(label, divider='_', joiner=' '): ...\ndef _split_by_length(msg, size): ...\ndef crop(msg, size, min_word_length=4, min_crop=0, ending=Ending.ELLIPSE, get_remainder=False): ...\ndef size_label(byte_count, decimal=0, is_long=False, is_bytes=True, round=False): ...\ndef time_label(seconds, decimal=0, is_long=False): ...\ndef time_labels(seconds, is_long=False): ...\ndef short_time_label(seconds): ...\ndef parse_short_time_label(label): ...\ndef _parse_timestamp(entry): ...\ndef _parse_iso_timestamp(entry): ...\ndef _get_label(units, count, decimal, is_long, round=False): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_time_label", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001066.py"} {"focal_file": "stem/util/str_tools.py", "focal_class": null, "focal_method": "time_labels", "tests": "import unittest\n\nclass Test_time_labels(unittest.TestCase):\n def test_time_labels(self):\n \"\"\"\n Checks the time_labels() function.\n \"\"\"\n self.assertEqual(['6m', '40s'], str_tools.time_labels(400))\n self.assertEqual(['1 hour', '40 seconds'], str_tools.time_labels(3640, True))\n self.assertEqual([], str_tools.time_labels(0))\n self.assertEqual(['-10s'], str_tools.time_labels(-10))\n self.assertRaises(TypeError, str_tools.time_labels, None)\n self.assertRaises(TypeError, str_tools.time_labels, 'hello world')\n", "method_code": "def time_labels(seconds, is_long=False):\n \"\"\"\n Provides a list of label conversions for each time unit, starting with its\n most significant units on down. Any counts that evaluate to zero are omitted.\n For example...\n\n ::\n\n >>> time_labels(400)\n ['6m', '40s']\n\n >>> time_labels(3640, True)\n ['1 hour', '40 seconds']\n\n :param int seconds: number of seconds to be converted\n :param bool is_long: expands units label\n\n :returns: **list** of strings with human readable representations of the time\n \"\"\"\n time_labels = []\n for count_per_unit, _, _ in TIME_UNITS:\n if abs(seconds) >= count_per_unit:\n time_labels.append(_get_label(TIME_UNITS, seconds, 0, is_long))\n seconds %= count_per_unit\n return time_labels", "context": "def time_labels(seconds, is_long=False): ...\ndef _to_bytes(msg): ...\ndef _to_unicode(msg): ...\ndef _to_int(msg): ...\ndef _to_camel_case(label, divider='_', joiner=' '): ...\ndef _split_by_length(msg, size): ...\ndef crop(msg, size, min_word_length=4, min_crop=0, ending=Ending.ELLIPSE, get_remainder=False): ...\ndef size_label(byte_count, decimal=0, is_long=False, is_bytes=True, round=False): ...\ndef time_label(seconds, decimal=0, is_long=False): ...\ndef time_labels(seconds, is_long=False): ...\ndef short_time_label(seconds): ...\ndef parse_short_time_label(label): ...\ndef _parse_timestamp(entry): ...\ndef _parse_iso_timestamp(entry): ...\ndef _get_label(units, count, decimal, is_long, round=False): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_time_labels", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001067.py"} {"focal_file": "stem/util/str_tools.py", "focal_class": null, "focal_method": "short_time_label", "tests": "import unittest\n\nclass Test_short_time_label(unittest.TestCase):\n def test_short_time_label(self):\n \"\"\"\n Checks the short_time_label() function.\n \"\"\"\n self.assertEqual('01:51', str_tools.short_time_label(111))\n self.assertEqual('6-07:08:20', str_tools.short_time_label(544100))\n self.assertEqual('00:00', str_tools.short_time_label(0))\n self.assertRaises(TypeError, str_tools.short_time_label, None)\n self.assertRaises(TypeError, str_tools.short_time_label, 'hello world')\n self.assertRaises(ValueError, str_tools.short_time_label, -5)\n", "method_code": "def short_time_label(seconds):\n \"\"\"\n Provides a time in the following format:\n [[dd-]hh:]mm:ss\n\n ::\n\n >>> short_time_label(111)\n '01:51'\n\n >>> short_time_label(544100)\n '6-07:08:20'\n\n :param int seconds: number of seconds to be converted\n\n :returns: **str** with the short representation for the time\n\n :raises: **ValueError** if the input is negative\n \"\"\"\n if seconds < 0:\n raise ValueError(\"Input needs to be a non-negative integer, got '%i'\" % seconds)\n time_comp = {}\n for amount, _, label in TIME_UNITS:\n count = int(seconds / amount)\n seconds %= amount\n time_comp[label.strip()] = count\n label = '%02i:%02i' % (time_comp['minute'], time_comp['second'])\n if time_comp['day']:\n label = '%i-%02i:%s' % (time_comp['day'], time_comp['hour'], label)\n elif time_comp['hour']:\n label = '%02i:%s' % (time_comp['hour'], label)\n return label", "context": "def short_time_label(seconds): ...\ndef _to_bytes(msg): ...\ndef _to_unicode(msg): ...\ndef _to_int(msg): ...\ndef _to_camel_case(label, divider='_', joiner=' '): ...\ndef _split_by_length(msg, size): ...\ndef crop(msg, size, min_word_length=4, min_crop=0, ending=Ending.ELLIPSE, get_remainder=False): ...\ndef size_label(byte_count, decimal=0, is_long=False, is_bytes=True, round=False): ...\ndef time_label(seconds, decimal=0, is_long=False): ...\ndef time_labels(seconds, is_long=False): ...\ndef short_time_label(seconds): ...\ndef parse_short_time_label(label): ...\ndef _parse_timestamp(entry): ...\ndef _parse_iso_timestamp(entry): ...\ndef _get_label(units, count, decimal, is_long, round=False): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_short_time_label", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001068.py"} {"focal_file": "stem/util/str_tools.py", "focal_class": null, "focal_method": "parse_short_time_label", "tests": "import unittest\n\nclass Test_parse_short_time_label(unittest.TestCase):\n def test_parse_short_time_label(self):\n \"\"\"\n Checks the parse_short_time_label() function.\n \"\"\"\n self.assertEqual(111, str_tools.parse_short_time_label('01:51'))\n self.assertEqual(544100, str_tools.parse_short_time_label('6-07:08:20'))\n self.assertEqual(110, str_tools.parse_short_time_label('01:50.62'))\n self.assertEqual(0, str_tools.parse_short_time_label('00:00'))\n self.assertEqual(300, str_tools.parse_short_time_label('05:0'))\n self.assertEqual(300, str_tools.parse_short_time_label('5:00'))\n self.assertRaises(TypeError, str_tools.parse_short_time_label, None)\n self.assertRaises(TypeError, str_tools.parse_short_time_label, 100)\n self.assertRaises(ValueError, str_tools.parse_short_time_label, 'blarg')\n self.assertRaises(ValueError, str_tools.parse_short_time_label, '00')\n self.assertRaises(ValueError, str_tools.parse_short_time_label, '05:')\n self.assertRaises(ValueError, str_tools.parse_short_time_label, '05a:00')\n self.assertRaises(ValueError, str_tools.parse_short_time_label, '-05:00')\n", "method_code": "def parse_short_time_label(label):\n \"\"\"\n Provides the number of seconds corresponding to the formatting used for the\n cputime and etime fields of ps:\n [[dd-]hh:]mm:ss or mm:ss.ss\n\n ::\n\n >>> parse_short_time_label('01:51')\n 111\n\n >>> parse_short_time_label('6-07:08:20')\n 544100\n\n :param str label: time entry to be parsed\n\n :returns: **int** with the number of seconds represented by the label\n\n :raises: **ValueError** if input is malformed\n \"\"\"\n days, hours, minutes, seconds = ('0', '0', '0', '0')\n if '-' in label:\n days, label = label.split('-', 1)\n time_comp = label.split(':')\n if len(time_comp) == 3:\n hours, minutes, seconds = time_comp\n elif len(time_comp) == 2:\n minutes, seconds = time_comp\n else:\n raise ValueError(\"Invalid time format, we expected '[[dd-]hh:]mm:ss' or 'mm:ss.ss': %s\" % label)\n try:\n time_sum = int(float(seconds))\n time_sum += int(minutes) * 60\n time_sum += int(hours) * 3600\n time_sum += int(days) * 86400\n return time_sum\n except ValueError:\n raise ValueError('Non-numeric value in time entry: %s' % label)", "context": "def parse_short_time_label(label): ...\ndef _to_bytes(msg): ...\ndef _to_unicode(msg): ...\ndef _to_int(msg): ...\ndef _to_camel_case(label, divider='_', joiner=' '): ...\ndef _split_by_length(msg, size): ...\ndef crop(msg, size, min_word_length=4, min_crop=0, ending=Ending.ELLIPSE, get_remainder=False): ...\ndef size_label(byte_count, decimal=0, is_long=False, is_bytes=True, round=False): ...\ndef time_label(seconds, decimal=0, is_long=False): ...\ndef time_labels(seconds, is_long=False): ...\ndef short_time_label(seconds): ...\ndef parse_short_time_label(label): ...\ndef _parse_timestamp(entry): ...\ndef _parse_iso_timestamp(entry): ...\ndef _get_label(units, count, decimal, is_long, round=False): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_parse_short_time_label", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001069.py"} {"focal_file": "stem/util/str_tools.py", "focal_class": null, "focal_method": "_parse_iso_timestamp", "tests": "import unittest\n\nclass Test_parse_iso_timestamp(unittest.TestCase):\n def test_parse_iso_timestamp(self):\n \"\"\"\n Checks the _parse_iso_timestamp() function.\n \"\"\"\n test_inputs = {'2012-11-08T16:48:41.420251': datetime.datetime(2012, 11, 8, 16, 48, 41, 420251), '2012-11-08T16:48:41.000000': datetime.datetime(2012, 11, 8, 16, 48, 41, 0), '2012-11-08T16:48:41': datetime.datetime(2012, 11, 8, 16, 48, 41, 0)}\n for arg, expected in test_inputs.items():\n self.assertEqual(expected, str_tools._parse_iso_timestamp(arg))\n invalid_input = [None, 32, 'boom', 'hello world', '2012-11-08T16:48:41.42025', '2012-11-08T16:48:41.4202511', '2012-11-08T16:48']\n for arg in invalid_input:\n self.assertRaises(ValueError, str_tools._parse_iso_timestamp, arg)\n", "method_code": "def _parse_iso_timestamp(entry):\n \"\"\"\n Parses the ISO 8601 standard that provides for timestamps like...\n\n ::\n\n 2012-11-08T16:48:41.420251\n\n :param str entry: timestamp to be parsed\n\n :returns: **datetime** for the time represented by the timestamp\n\n :raises: **ValueError** if the timestamp is malformed\n \"\"\"\n if not stem.util._is_str(entry):\n raise ValueError('parse_iso_timestamp() input must be a str, got a %s' % type(entry))\n if '.' in entry:\n timestamp_str, microseconds = entry.split('.')\n else:\n timestamp_str, microseconds = (entry, '000000')\n if len(microseconds) != 6 or not microseconds.isdigit():\n raise ValueError(\"timestamp's microseconds should be six digits\")\n if len(timestamp_str) > 10 and timestamp_str[10] == 'T':\n timestamp_str = timestamp_str[:10] + ' ' + timestamp_str[11:]\n else:\n raise ValueError(\"timestamp didn't contain delimeter 'T' between date and time\")\n timestamp = _parse_timestamp(timestamp_str)\n return timestamp + datetime.timedelta(microseconds=int(microseconds))", "context": "def _parse_iso_timestamp(entry): ...\ndef _to_bytes(msg): ...\ndef _to_unicode(msg): ...\ndef _to_int(msg): ...\ndef _to_camel_case(label, divider='_', joiner=' '): ...\ndef _split_by_length(msg, size): ...\ndef crop(msg, size, min_word_length=4, min_crop=0, ending=Ending.ELLIPSE, get_remainder=False): ...\ndef size_label(byte_count, decimal=0, is_long=False, is_bytes=True, round=False): ...\ndef time_label(seconds, decimal=0, is_long=False): ...\ndef time_labels(seconds, is_long=False): ...\ndef short_time_label(seconds): ...\ndef parse_short_time_label(label): ...\ndef _parse_timestamp(entry): ...\ndef _parse_iso_timestamp(entry): ...\ndef _get_label(units, count, decimal, is_long, round=False): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_parse_iso_timestamp", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001070.py"} {"focal_file": "stem/util/proc.py", "focal_class": null, "focal_method": "system_start_time", "tests": "import unittest\n\nclass Test_system_start_time(unittest.TestCase):\n @patch('stem.util.proc._get_line')\n def test_system_start_time(self, get_line_mock):\n \"\"\"\n Tests the system_start_time function.\n \"\"\"\n get_line_mock.side_effect = lambda *params: {('/proc/stat', 'btime', 'system start time'): 'btime 1001001'}[params]\n self.assertEqual(1001001, proc.system_start_time())\n", "method_code": "def system_start_time():\n \"\"\"\n Provides the unix time (seconds since epoch) when the system started.\n\n :returns: **float** for the unix time of when the system started\n\n :raises: **IOError** if it can't be determined\n \"\"\"\n start_time, parameter = (time.time(), 'system start time')\n btime_line = _get_line('/proc/stat', 'btime', parameter)\n try:\n result = float(btime_line.strip().split()[1])\n _log_runtime(parameter, '/proc/stat[btime]', start_time)\n return result\n except:\n exc = IOError('unable to parse the /proc/stat btime entry: %s' % btime_line)\n _log_failure(parameter, exc)\n raise exc", "context": "@lru_cache()\ndef system_start_time(): ...\ndef is_available(): ...\ndef system_start_time(): ...\ndef physical_memory(): ...\ndef cwd(pid): ...\ndef uid(pid): ...\ndef memory_usage(pid): ...\ndef stats(pid, *stat_types): ...\ndef file_descriptors_used(pid): ...\ndef connections(pid=None, user=None): ...\ndef _inodes_for_sockets(pid): ...\ndef _unpack_addr(addr): ...\ndef _is_float(*value): ...\ndef _get_line(file_path, line_prefix, parameter): ...\ndef _get_lines(file_path, line_prefixes, parameter): ...\ndef _log_runtime(parameter, proc_location, start_time): ...\ndef _log_failure(parameter, exc): ...\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001071.py"} {"focal_file": "stem/util/proc.py", "focal_class": null, "focal_method": "physical_memory", "tests": "import unittest\n\nclass Test_physical_memory(unittest.TestCase):\n @patch('stem.util.proc._get_line')\n def test_physical_memory(self, get_line_mock):\n \"\"\"\n Tests the physical_memory function.\n \"\"\"\n get_line_mock.side_effect = lambda *params: {('/proc/meminfo', 'MemTotal:', 'system physical memory'): 'MemTotal: 12345 kB'}[params]\n self.assertEqual(12345 * 1024, proc.physical_memory())\n", "method_code": "def physical_memory():\n \"\"\"\n Provides the total physical memory on the system in bytes.\n\n :returns: **int** for the bytes of physical memory this system has\n\n :raises: **IOError** if it can't be determined\n \"\"\"\n start_time, parameter = (time.time(), 'system physical memory')\n mem_total_line = _get_line('/proc/meminfo', 'MemTotal:', parameter)\n try:\n result = int(mem_total_line.split()[1]) * 1024\n _log_runtime(parameter, '/proc/meminfo[MemTotal]', start_time)\n return result\n except:\n exc = IOError('unable to parse the /proc/meminfo MemTotal entry: %s' % mem_total_line)\n _log_failure(parameter, exc)\n raise exc", "context": "@lru_cache()\ndef physical_memory(): ...\ndef is_available(): ...\ndef system_start_time(): ...\ndef physical_memory(): ...\ndef cwd(pid): ...\ndef uid(pid): ...\ndef memory_usage(pid): ...\ndef stats(pid, *stat_types): ...\ndef file_descriptors_used(pid): ...\ndef connections(pid=None, user=None): ...\ndef _inodes_for_sockets(pid): ...\ndef _unpack_addr(addr): ...\ndef _is_float(*value): ...\ndef _get_line(file_path, line_prefix, parameter): ...\ndef _get_lines(file_path, line_prefixes, parameter): ...\ndef _log_runtime(parameter, proc_location, start_time): ...\ndef _log_failure(parameter, exc): ...\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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_001072.py"} {"focal_file": "stem/util/proc.py", "focal_class": null, "focal_method": "file_descriptors_used", "tests": "import unittest\n\nclass Test_file_descriptors_used(unittest.TestCase):\n @patch('os.listdir')\n def test_file_descriptors_used(self, listdir_mock):\n \"\"\"\n Tests the file_descriptors_used function.\n \"\"\"\n for arg in (None, -100, 'hello'):\n self.assertRaises(IOError, proc.file_descriptors_used, arg)\n error_msg = \"OSError: [Errno 2] No such file or directory: '/proc/2118/fd'\"\n listdir_mock.side_effect = OSError(error_msg)\n exc_msg = 'Unable to check number of file descriptors used: %s' % error_msg\n self.assertRaisesWith(IOError, exc_msg, proc.file_descriptors_used, 2118)\n listdir_mock.return_value = ['0', '1', '2', '3', '4', '5']\n listdir_mock.side_effect = None\n self.assertEqual(6, proc.file_descriptors_used(2118))\n self.assertEqual(6, proc.file_descriptors_used('2118'))\n", "method_code": "def file_descriptors_used(pid):\n \"\"\"\n Provides the number of file descriptors currently being used by a process.\n\n .. versionadded:: 1.3.0\n\n :param int pid: process id of the process to be queried\n\n :returns: **int** of the number of file descriptors used\n\n :raises: **IOError** if it can't be determined\n \"\"\"\n try:\n pid = int(pid)\n if pid < 0:\n raise IOError(\"Process pids can't be negative: %s\" % pid)\n except (ValueError, TypeError):\n raise IOError('Process pid was non-numeric: %s' % pid)\n try:\n return len(os.listdir('/proc/%i/fd' % pid))\n except Exception as exc:\n raise IOError('Unable to check number of file descriptors used: %s' % exc)", "context": "def file_descriptors_used(pid): ...\ndef is_available(): ...\ndef system_start_time(): ...\ndef physical_memory(): ...\ndef cwd(pid): ...\ndef uid(pid): ...\ndef memory_usage(pid): ...\ndef stats(pid, *stat_types): ...\ndef file_descriptors_used(pid): ...\ndef connections(pid=None, user=None): ...\ndef _inodes_for_sockets(pid): ...\ndef _unpack_addr(addr): ...\ndef _is_float(*value): ...\ndef _get_line(file_path, line_prefix, parameter): ...\ndef _get_lines(file_path, line_prefixes, parameter): ...\ndef _log_runtime(parameter, proc_location, start_time): ...\ndef _log_failure(parameter, exc): ...\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001073.py"} {"focal_file": "stem/util/enum.py", "focal_class": null, "focal_method": "UppercaseEnum", "tests": "import unittest\n\nclass Test_UppercaseEnum(unittest.TestCase):\n def test_uppercase_enum_example(self):\n \"\"\"\n Checks that the pydoc example for the UppercaseEnum constructor function is\n accurate.\n \"\"\"\n runlevels = stem.util.enum.UppercaseEnum('DEBUG', 'INFO', 'NOTICE', 'WARN', 'ERROR')\n self.assertEqual('DEBUG', runlevels.DEBUG)\n", "method_code": "def UppercaseEnum(*args):\n \"\"\"\n Provides an :class:`~stem.util.enum.Enum` instance where the values are\n identical to the keys. Since the keys are uppercase by convention this means\n the values are too. For instance...\n\n ::\n\n >>> from stem.util import enum\n >>> runlevels = enum.UppercaseEnum('DEBUG', 'INFO', 'NOTICE', 'WARN', 'ERROR')\n >>> runlevels.DEBUG\n 'DEBUG'\n\n :param list args: enum keys to initialize with\n\n :returns: :class:`~stem.util.enum.Enum` instance with the given keys\n \"\"\"\n return Enum(*[(v, v) for v in args])", "context": "def UppercaseEnum(*args): ...\ndef UppercaseEnum(*args): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_uppercase_enum_example", "smells": [1, 0, 0, 0, 1, 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_001074.py"} {"focal_file": "stem/descriptor/router_status_entry.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 \"\"\"\n Exercise our RouterStatusEntry.from_str().\n \"\"\"\n desc = RouterStatusEntryV3.create()\n content = desc.get_bytes()\n self.assertEqual(desc, RouterStatusEntryV3.from_str(content))\n self.assertRaisesWith(NotImplementedError, 'Please use the from_str() method from RouterStatusEntry subclasses, not RouterStatusEntry itself', RouterStatusEntry.from_str, content)\n self.assertRaisesWith(ValueError, \"Router status entries don't have their own @type annotation. As such providing a 'descriptor_type' argument with RouterStatusEntry.from_str() does not work. Please drop the 'descriptor_type' argument when using this these subclasses' from_str() method.\", RouterStatusEntryV3.from_str, content, descriptor_type='network-status-consensus-3 1.0')\n", "method_code": " def from_str(cls, content, **kwargs):\n if cls == RouterStatusEntry:\n raise NotImplementedError('Please use the from_str() method from RouterStatusEntry subclasses, not RouterStatusEntry itself')\n elif 'descriptor_type' in kwargs:\n raise ValueError(\"Router status entries don't have their own @type annotation. As such providing a 'descriptor_type' argument with RouterStatusEntry.from_str() does not work. Please drop the 'descriptor_type' argument when using this these subclasses' from_str() method.\")\n is_multiple = kwargs.pop('multiple', False)\n validate = kwargs.pop('validate', False)\n results = list(_parse_file(io.BytesIO(stem.util.str_tools._to_bytes(content)), validate, cls, **kwargs))\n if is_multiple:\n return results\n elif len(results) == 1:\n return results[0]\n else:\n raise ValueError(\"Descriptor.from_str() expected a single descriptor, but had %i instead. Please include 'multiple = True' if you want a list of results instead.\" % len(results))\n ", "context": "class RouterStatusEntry(Descriptor):\n @classmethod\n def from_str(cls, content, **kwargs): ...\n def __init__(self, content, validate=False, document=None): ...\n def _name(self, is_plural=False): ...\n def _required_fields(self): ...\n def _single_fields(self): ...\n\n self.document = document\n\n ATTRIBUTES = {'nickname': (None, _parse_r_line), 'fingerprint': (None, _parse_r_line), 'published': (None, _parse_r_line), 'address': (None, _parse_r_line), 'or_port': (None, _parse_r_line), 'dir_port': (None, _parse_r_line), 'flags': (None, _parse_s_line), 'version_line': (None, _parse_v_line), 'version': (None, _parse_v_line)}\n PARSER_FOR_LINE = {'r': _parse_r_line, 's': _parse_s_line, 'v': _parse_v_line}\n", "repository": "illumineinteractive/stem", "test_name": "test_from_str", "smells": [1, 0, 0, 0, 1, 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_001075.py"} {"focal_file": "stem/descriptor/hidden_service_descriptor.py", "focal_class": null, "focal_method": "create", "tests": "import unittest\n\nclass Test_create(unittest.TestCase):\n def test_minimal_hidden_service_descriptor(self):\n \"\"\"\n Basic sanity check that we can parse a hidden service descriptor with minimal attributes.\n \"\"\"\n desc = HiddenServiceDescriptor.create()\n self.assertEqual('y3olqqblqw2gbh6phimfuiroechjjafa', desc.descriptor_id)\n self.assertEqual(2, desc.version)\n self.assertEqual('e24kgecavwsznj7gpbktqsiwgvngsf4e', desc.secret_id_part)\n self.assertEqual([2, 3], desc.protocol_versions)\n self.assertEqual('-----BEGIN MESSAGE-----\\n-----END MESSAGE-----', desc.introduction_points_encoded)\n self.assertEqual([], desc.introduction_points_auth)\n self.assertEqual(b'', desc.introduction_points_content)\n self.assertEqual([], desc.introduction_points())\n self.assertEqual('@type hidden-service-descriptor 1.0', str(desc.type_annotation()))\n", "method_code": " def create(cls, attr=None, exclude=(), validate=True, sign=False):\n return cls(cls.content(attr, exclude, sign), validate=validate, skip_crypto_validation=not sign)\n ", "context": "class HiddenServiceDescriptor(Descriptor):\n @classmethod\n def create(cls, attr=None, exclude=(), validate=True, sign=False): ...\n def content(cls, attr=None, exclude=(), sign=False): ...\n def __init__(self, raw_contents, validate=False, skip_crypto_validation=False): ...\n def introduction_points(self, authentication_cookie=None): ...\n def _decrypt_basic_auth(content, authentication_cookie): ...\n def _decrypt_stealth_auth(content, authentication_cookie): ...\n def _parse_introduction_points(content): ...\n\n TYPE_ANNOTATION_NAME = 'hidden-service-descriptor'\n ATTRIBUTES = {'descriptor_id': (None, _parse_rendezvous_service_descriptor_line), 'version': (None, _parse_version_line), 'permanent_key': (None, _parse_permanent_key_line), 'secret_id_part': (None, _parse_secret_id_part_line), 'published': (None, _parse_publication_time_line), 'protocol_versions': ([], _parse_protocol_versions_line), 'introduction_points_encoded': (None, _parse_introduction_points_line), 'introduction_points_auth': ([], _parse_introduction_points_line), 'introduction_points_content': (None, _parse_introduction_points_line), 'signature': (None, _parse_signature_line)}\n PARSER_FOR_LINE = {'rendezvous-service-descriptor': _parse_rendezvous_service_descriptor_line, 'version': _parse_version_line, 'permanent-key': _parse_permanent_key_line, 'secret-id-part': _parse_secret_id_part_line, 'publication-time': _parse_publication_time_line, 'protocol-versions': _parse_protocol_versions_line, 'introduction-points': _parse_introduction_points_line, 'signature': _parse_signature_line}\n", "repository": "illumineinteractive/stem", "test_name": "test_minimal_hidden_service_descriptor", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001076.py"} {"focal_file": "stem/descriptor/hidden_service_descriptor.py", "focal_class": null, "focal_method": "introduction_points", "tests": "import unittest\n\nclass Test_introduction_points(unittest.TestCase):\n def test_introduction_points_when_empty(self):\n \"\"\"\n It's valid to advertise zero introduciton points. I'm not clear if this\n would mean an empty protocol-versions field or that it's omitted but either\n are valid according to the spec.\n \"\"\"\n missing_field_desc = HiddenServiceDescriptor.create(exclude=('introduction-points',))\n self.assertEqual(None, missing_field_desc.introduction_points_encoded)\n self.assertEqual([], missing_field_desc.introduction_points_auth)\n self.assertEqual(None, missing_field_desc.introduction_points_content)\n self.assertEqual([], missing_field_desc.introduction_points())\n empty_field_desc = HiddenServiceDescriptor.create({'introduction-points': MESSAGE_BLOCK % ''})\n self.assertEqual((MESSAGE_BLOCK % '').strip(), empty_field_desc.introduction_points_encoded)\n self.assertEqual([], empty_field_desc.introduction_points_auth)\n self.assertEqual(b'', empty_field_desc.introduction_points_content)\n self.assertEqual([], empty_field_desc.introduction_points())\n\n def test_introduction_points_when_not_base64(self):\n \"\"\"\n Checks the introduction-points field when the content isn't base64 encoded.\n \"\"\"\n test_values = (MESSAGE_BLOCK % '12345', MESSAGE_BLOCK % 'hello')\n for test_value in test_values:\n desc = expect_invalid_attr(self, {'introduction-points': test_value}, 'introduction_points_encoded', test_value.strip())\n self.assertEqual([], desc.introduction_points_auth)\n self.assertEqual(None, desc.introduction_points_content)\n self.assertEqual([], desc.introduction_points())\n", "method_code": " def introduction_points(self, authentication_cookie=None):\n \"\"\"\n Provided this service's introduction points.\n \n :returns: **list** of :class:`~stem.descriptor.hidden_service_descriptor.IntroductionPoints`\n \n :raises:\n * **ValueError** if the our introduction-points is malformed\n * **DecryptionFailure** if unable to decrypt this field\n \"\"\"\n content = self.introduction_points_content\n if not content:\n return []\n elif authentication_cookie:\n if not stem.prereq.is_crypto_available():\n raise DecryptionFailure('Decrypting introduction-points requires the cryptography module')\n try:\n missing_padding = len(authentication_cookie) % 4\n authentication_cookie = base64.b64decode(stem.util.str_tools._to_bytes(authentication_cookie) + b'=' * missing_padding)\n except TypeError as exc:\n raise DecryptionFailure('authentication_cookie must be a base64 encoded string (%s)' % exc)\n authentication_type = int(binascii.hexlify(content[0:1]), 16)\n if authentication_type == BASIC_AUTH:\n content = HiddenServiceDescriptor._decrypt_basic_auth(content, authentication_cookie)\n elif authentication_type == STEALTH_AUTH:\n content = HiddenServiceDescriptor._decrypt_stealth_auth(content, authentication_cookie)\n else:\n raise DecryptionFailure(\"Unrecognized authentication type '%s', currently we only support basic auth (%s) and stealth auth (%s)\" % (authentication_type, BASIC_AUTH, STEALTH_AUTH))\n if not content.startswith(b'introduction-point '):\n raise DecryptionFailure('Unable to decrypt the introduction-points, maybe this is the wrong key?')\n elif not content.startswith(b'introduction-point '):\n raise DecryptionFailure('introduction-points content is encrypted, you need to provide its authentication_cookie')\n return HiddenServiceDescriptor._parse_introduction_points(content)\n ", "context": "class HiddenServiceDescriptor(Descriptor):\n @lru_cache()\n def introduction_points(self, authentication_cookie=None): ...\n def content(cls, attr=None, exclude=(), sign=False): ...\n def create(cls, attr=None, exclude=(), validate=True, sign=False): ...\n def __init__(self, raw_contents, validate=False, skip_crypto_validation=False): ...\n def _decrypt_basic_auth(content, authentication_cookie): ...\n def _decrypt_stealth_auth(content, authentication_cookie): ...\n def _parse_introduction_points(content): ...\n\n TYPE_ANNOTATION_NAME = 'hidden-service-descriptor'\n ATTRIBUTES = {'descriptor_id': (None, _parse_rendezvous_service_descriptor_line), 'version': (None, _parse_version_line), 'permanent_key': (None, _parse_permanent_key_line), 'secret_id_part': (None, _parse_secret_id_part_line), 'published': (None, _parse_publication_time_line), 'protocol_versions': ([], _parse_protocol_versions_line), 'introduction_points_encoded': (None, _parse_introduction_points_line), 'introduction_points_auth': ([], _parse_introduction_points_line), 'introduction_points_content': (None, _parse_introduction_points_line), 'signature': (None, _parse_signature_line)}\n PARSER_FOR_LINE = {'rendezvous-service-descriptor': _parse_rendezvous_service_descriptor_line, 'version': _parse_version_line, 'permanent-key': _parse_permanent_key_line, 'secret-id-part': _parse_secret_id_part_line, 'publication-time': _parse_publication_time_line, 'protocol-versions': _parse_protocol_versions_line, 'introduction-points': _parse_introduction_points_line, 'signature': _parse_signature_line}\n", "repository": "illumineinteractive/stem", "test_name": "test_introduction_points_when_empty", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001077.py"} {"focal_file": "stem/descriptor/reader.py", "focal_class": null, "focal_method": "load_processed_files", "tests": "import unittest\n\nclass Test_load_processed_files(unittest.TestCase):\n @patch('stem.descriptor.reader.open', create=True)\n def test_load_processed_files(self, open_mock):\n \"\"\"\n Successful load of content.\n \"\"\"\n test_lines = ('/dir/ 0', '/dir/file 12345', '/dir/file with spaces 7138743', ' /dir/with extra space 12345 ', ' \\t ', '', '/dir/after empty line 12345')\n expected_value = {'/dir/': 0, '/dir/file': 12345, '/dir/file with spaces': 7138743, '/dir/with extra space': 12345, '/dir/after empty line': 12345}\n open_mock.return_value = io.BytesIO(stem.util.str_tools._to_bytes('\\n'.join(test_lines)))\n self.assertEqual(expected_value, stem.descriptor.reader.load_processed_files(''))\n\n @patch('stem.descriptor.reader.open', create=True)\n def test_load_processed_files_empty(self, open_mock):\n \"\"\"\n Tests the load_processed_files() function with an empty file.\n \"\"\"\n open_mock.return_value = io.BytesIO(stem.util.str_tools._to_bytes(''))\n self.assertEqual({}, stem.descriptor.reader.load_processed_files(''))\n\n def test_load_processed_files_from_data(self):\n \"\"\"\n Basic sanity test for loading a processed files listing from disk.\n \"\"\"\n test_listing_path = self._make_processed_files_listing(BASIC_LISTING)\n loaded_listing = stem.descriptor.reader.load_processed_files(test_listing_path)\n expected_listing = {'/tmp': 123, '/bin/grep': 4567, '/file with spaces/and \\\\ stuff': 890}\n self.assertEqual(expected_listing, loaded_listing)\n", "method_code": "def load_processed_files(path):\n \"\"\"\n Loads a dictionary of 'path => last modified timestamp' mappings, as\n persisted by :func:`~stem.descriptor.reader.save_processed_files`, from a\n file.\n\n :param str path: location to load the processed files dictionary from\n\n :returns: **dict** of 'path (**str**) => last modified unix timestamp\n (**int**)' mappings\n\n :raises:\n * **IOError** if unable to read the file\n * **TypeError** if unable to parse the file's contents\n \"\"\"\n processed_files = {}\n with open(path, 'rb') as input_file:\n for line in input_file.readlines():\n line = stem.util.str_tools._to_unicode(line.strip())\n if not line:\n continue\n if ' ' not in line:\n raise TypeError('Malformed line: %s' % line)\n path, timestamp = line.rsplit(' ', 1)\n if not os.path.isabs(path):\n raise TypeError(\"'%s' is not an absolute path\" % path)\n elif not timestamp.isdigit():\n raise TypeError(\"'%s' is not an integer timestamp\" % timestamp)\n processed_files[path] = int(timestamp)\n return processed_files", "context": "def load_processed_files(path): ...\ndef load_processed_files(path): ...\ndef save_processed_files(path, processed_files): ...\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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_001078.py"} {"focal_file": "stem/descriptor/reader.py", "focal_class": null, "focal_method": "save_processed_files", "tests": "import unittest\n\nclass Test_save_processed_files(unittest.TestCase):\n def test_save_processed_files(self):\n \"\"\"\n Basic sanity test for persisting files listings to disk.\n \"\"\"\n initial_listing = {'/tmp': 123, '/bin/grep': 4567, '/file with spaces/and \\\\ stuff': 890}\n stem.descriptor.reader.save_processed_files(self.test_listing_path, initial_listing)\n loaded_listing = stem.descriptor.reader.load_processed_files(self.test_listing_path)\n self.assertEqual(initial_listing, loaded_listing)\n", "method_code": "def save_processed_files(path, processed_files):\n \"\"\"\n Persists a dictionary of 'path => last modified timestamp' mappings (as\n provided by the DescriptorReader's\n :func:`~stem.descriptor.reader.DescriptorReader.get_processed_files` method)\n so that they can be loaded later and applied to another\n :class:`~stem.descriptor.reader.DescriptorReader`.\n\n :param str path: location to save the processed files dictionary to\n :param dict processed_files: 'path => last modified' mappings\n\n :raises:\n * **IOError** if unable to write to the file\n * **TypeError** if processed_files is of the wrong type\n \"\"\"\n try:\n path_dir = os.path.dirname(path)\n if not os.path.exists(path_dir):\n os.makedirs(path_dir)\n except OSError as exc:\n raise IOError(exc)\n with open(path, 'w') as output_file:\n for path, timestamp in list(processed_files.items()):\n if not os.path.isabs(path):\n raise TypeError('Only absolute paths are acceptable: %s' % path)\n output_file.write('%s %i\\n' % (path, timestamp))", "context": "def save_processed_files(path, processed_files): ...\ndef load_processed_files(path): ...\ndef save_processed_files(path, processed_files): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_save_processed_files", "smells": [1, 0, 0, 0, 1, 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_001079.py"} {"focal_file": "stem/descriptor/reader.py", "focal_class": null, "focal_method": "stop", "tests": "import unittest\n\nclass Test_stop(unittest.TestCase):\n def test_stop(self):\n \"\"\"\n Runs a DescriptorReader over the root directory, then checks that calling\n stop() makes it terminate in a timely fashion.\n \"\"\"\n if stem.util.system.is_windows():\n self.skipTest('(SIGALRM unavailable)')\n is_test_running = True\n reader = stem.descriptor.reader.DescriptorReader('/usr')\n\n def timeout_handler(signum, frame):\n if is_test_running:\n self.fail()\n signal.signal(signal.SIGALRM, timeout_handler)\n signal.alarm(2)\n reader.start()\n time.sleep(0.001)\n reader.stop()\n is_test_running = False\n", "method_code": " def stop(self):\n \"\"\"\n Stops further reading of descriptor files.\n \"\"\"\n with self._reader_thread_lock:\n self._is_stopped.set()\n self._iter_notice.set()\n try:\n while True:\n self._unreturned_descriptors.get_nowait()\n except queue.Empty:\n pass\n self._reader_thread.join()\n self._reader_thread = None\n if self._persistence_path:\n try:\n processed_files = self.get_processed_files()\n save_processed_files(self._persistence_path, processed_files)\n except:\n pass\n ", "context": "class DescriptorReader(object):\n def stop(self): ...\n def __init__(self, target, validate=False, follow_links=False, buffer_size=100, persistence_path=None, document_handler=stem.descriptor.DocumentHandler.ENTRIES, **kwargs): ...\n def get_processed_files(self): ...\n def set_processed_files(self, processed_files): ...\n def register_read_listener(self, listener): ...\n def register_skip_listener(self, listener): ...\n def get_buffered_descriptor_count(self): ...\n def start(self): ...\n def _read_descriptor_files(self): ...\n def __iter__(self): ...\n def _handle_walker(self, walker, new_processed_files): ...\n def _handle_file(self, target, new_processed_files): ...\n def _handle_descriptor_file(self, target, mime_type): ...\n def _handle_archive(self, target): ...\n def _notify_read_listeners(self, path): ...\n def _notify_skip_listeners(self, path, exception): ...\n def __enter__(self): ...\n def __exit__(self, exit_type, value, traceback): ...\n\n self._targets = [target] if stem.util._is_str(target) else target\n self._targets = list(map(os.path.abspath, self._targets))\n self._validate = validate\n self._follow_links = follow_links\n self._persistence_path = persistence_path\n self._document_handler = document_handler\n self._kwargs = kwargs\n self._read_listeners = []\n self._skip_listeners = []\n self._processed_files = {}\n self._reader_thread = None\n self._reader_thread_lock = threading.RLock()\n self._iter_lock = threading.RLock()\n self._iter_notice = threading.Event()\n self._is_stopped = threading.Event()\n self._unreturned_descriptors = queue.Queue(buffer_size)\n", "repository": "illumineinteractive/stem", "test_name": "test_stop", "smells": [1, 0, 0, 0, 1, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "pynose_source_file": "test_001080.py"} {"focal_file": "stem/descriptor/reader.py", "focal_class": null, "focal_method": "get_processed_files", "tests": "import unittest\n\nclass Test_get_processed_files(unittest.TestCase):\n def test_get_processed_files(self):\n \"\"\"\n Checks that get_processed_files() provides the expected results after\n iterating over our test data.\n \"\"\"\n desc_path = os.path.join(DESCRIPTOR_TEST_DATA, 'example_descriptor')\n last_modified = int(os.stat(desc_path).st_mtime)\n reader = stem.descriptor.reader.DescriptorReader(desc_path)\n with reader:\n list(reader)\n self.assertEqual({desc_path: last_modified}, reader.get_processed_files())\n", "method_code": " def get_processed_files(self):\n \"\"\"\n For each file that we have read descriptor data from this provides a\n mapping of the form...\n \n ::\n \n absolute path (str) => last modified unix timestamp (int)\n \n This includes entries set through the\n :func:`~stem.descriptor.reader.DescriptorReader.set_processed_files`\n method. Each run resets this to only the files that were present during\n that run.\n \n :returns: **dict** with the absolute paths and unix timestamp for the last\n modified times of the files we have processed\n \"\"\"\n return dict(((os.path.abspath(k), v) for k, v in list(self._processed_files.items())))\n ", "context": "class DescriptorReader(object):\n def get_processed_files(self): ...\n def __init__(self, target, validate=False, follow_links=False, buffer_size=100, persistence_path=None, document_handler=stem.descriptor.DocumentHandler.ENTRIES, **kwargs): ...\n def set_processed_files(self, processed_files): ...\n def register_read_listener(self, listener): ...\n def register_skip_listener(self, listener): ...\n def get_buffered_descriptor_count(self): ...\n def start(self): ...\n def stop(self): ...\n def _read_descriptor_files(self): ...\n def __iter__(self): ...\n def _handle_walker(self, walker, new_processed_files): ...\n def _handle_file(self, target, new_processed_files): ...\n def _handle_descriptor_file(self, target, mime_type): ...\n def _handle_archive(self, target): ...\n def _notify_read_listeners(self, path): ...\n def _notify_skip_listeners(self, path, exception): ...\n def __enter__(self): ...\n def __exit__(self, exit_type, value, traceback): ...\n\n self._targets = [target] if stem.util._is_str(target) else target\n self._targets = list(map(os.path.abspath, self._targets))\n self._validate = validate\n self._follow_links = follow_links\n self._persistence_path = persistence_path\n self._document_handler = document_handler\n self._kwargs = kwargs\n self._read_listeners = []\n self._skip_listeners = []\n self._processed_files = {}\n self._reader_thread = None\n self._reader_thread_lock = threading.RLock()\n self._iter_lock = threading.RLock()\n self._iter_notice = threading.Event()\n self._is_stopped = threading.Event()\n self._unreturned_descriptors = queue.Queue(buffer_size)\n", "repository": "illumineinteractive/stem", "test_name": "test_get_processed_files", "smells": [1, 0, 0, 0, 1, 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_001081.py"} {"focal_file": "stem/descriptor/reader.py", "focal_class": null, "focal_method": "register_skip_listener", "tests": "import unittest\n\nclass Test_register_skip_listener(unittest.TestCase):\n def test_skip_listener_already_read(self):\n \"\"\"\n Checks that calling set_processed_files() prior to reading makes us skip\n those files. This also doubles for testing that skip listeners are notified\n of files that we've already read.\n \"\"\"\n test_path = os.path.join(DESCRIPTOR_TEST_DATA, 'example_descriptor')\n initial_processed_files = {test_path: sys.maxsize}\n skip_listener = SkipListener()\n reader = stem.descriptor.reader.DescriptorReader(test_path)\n reader.register_skip_listener(skip_listener.listener)\n reader.set_processed_files(initial_processed_files)\n self.assertEqual(initial_processed_files, reader.get_processed_files())\n with reader:\n list(reader)\n self.assertEqual(1, len(skip_listener.results))\n skipped_path, skip_exception = skip_listener.results[0]\n self.assertEqual(test_path, skipped_path)\n self.assertTrue(isinstance(skip_exception, stem.descriptor.reader.AlreadyRead))\n self.assertEqual(sys.maxsize, skip_exception.last_modified_when_read)\n\n def test_skip_listener_unrecognized_type(self):\n \"\"\"\n Listens for a file that's skipped because its file type isn't recognized.\n \"\"\"\n test_path = os.path.join(self.temp_directory, 'test.png')\n try:\n test_file = open(test_path, 'w')\n test_file.write('test data for test_skip_listener_unrecognized_type()')\n test_file.close()\n skip_listener = SkipListener()\n reader = stem.descriptor.reader.DescriptorReader(test_path)\n reader.register_skip_listener(skip_listener.listener)\n with reader:\n list(reader)\n self.assertEqual(1, len(skip_listener.results))\n skipped_path, skip_exception = skip_listener.results[0]\n self.assertEqual(test_path, skipped_path)\n self.assertTrue(isinstance(skip_exception, stem.descriptor.reader.UnrecognizedType))\n self.assertTrue(skip_exception.mime_type in (('image/png', None), ('image/x-png', None)))\n finally:\n if os.path.exists(test_path):\n os.remove(test_path)\n\n def test_skip_listener_read_failure(self):\n \"\"\"\n Listens for a file that's skipped because we lack read permissions.\n \"\"\"\n if getpass.getuser() == 'root':\n self.skipTest('(running as root)')\n return\n elif stem.util.system.is_windows():\n self.skipTest('(chmod not functional)')\n return\n test_path = os.path.join(self.temp_directory, 'secret_file')\n try:\n test_file = open(test_path, 'w')\n test_file.write('test data for test_skip_listener_unrecognized_type()')\n test_file.close()\n os.chmod(test_path, 63)\n skip_listener = SkipListener()\n reader = stem.descriptor.reader.DescriptorReader(test_path)\n reader.register_skip_listener(skip_listener.listener)\n with reader:\n list(reader)\n self.assertEqual(1, len(skip_listener.results))\n skipped_path, skip_exception = skip_listener.results[0]\n self.assertEqual(test_path, skipped_path)\n self.assertTrue(isinstance(skip_exception, stem.descriptor.reader.ReadFailed))\n self.assertTrue(isinstance(skip_exception.exception, IOError))\n finally:\n if os.path.exists(test_path):\n os.remove(test_path)\n\n def test_skip_listener_file_missing(self):\n \"\"\"\n Listens for a file that's skipped because the file doesn't exist.\n \"\"\"\n test_path = '/non-existant/path'\n skip_listener = SkipListener()\n reader = stem.descriptor.reader.DescriptorReader(test_path)\n reader.register_skip_listener(skip_listener.listener)\n with reader:\n list(reader)\n self.assertEqual(1, len(skip_listener.results))\n skipped_path, skip_exception = skip_listener.results[0]\n self.assertEqual(test_path, skipped_path)\n self.assertTrue(isinstance(skip_exception, stem.descriptor.reader.FileMissing))\n", "method_code": " def register_skip_listener(self, listener):\n \"\"\"\n Registers a listener for files that are skipped. This listener is expected\n to be a functor of the form...\n \n ::\n \n my_listener(path, exception)\n \n :param functor listener: functor to be notified of files that are skipped\n to read errors or because they couldn't be parsed as valid descriptor data\n \"\"\"\n self._skip_listeners.append(listener)\n ", "context": "class DescriptorReader(object):\n def register_skip_listener(self, listener): ...\n def __init__(self, target, validate=False, follow_links=False, buffer_size=100, persistence_path=None, document_handler=stem.descriptor.DocumentHandler.ENTRIES, **kwargs): ...\n def get_processed_files(self): ...\n def set_processed_files(self, processed_files): ...\n def register_read_listener(self, listener): ...\n def get_buffered_descriptor_count(self): ...\n def start(self): ...\n def stop(self): ...\n def _read_descriptor_files(self): ...\n def __iter__(self): ...\n def _handle_walker(self, walker, new_processed_files): ...\n def _handle_file(self, target, new_processed_files): ...\n def _handle_descriptor_file(self, target, mime_type): ...\n def _handle_archive(self, target): ...\n def _notify_read_listeners(self, path): ...\n def _notify_skip_listeners(self, path, exception): ...\n def __enter__(self): ...\n def __exit__(self, exit_type, value, traceback): ...\n\n self._targets = [target] if stem.util._is_str(target) else target\n self._targets = list(map(os.path.abspath, self._targets))\n self._validate = validate\n self._follow_links = follow_links\n self._persistence_path = persistence_path\n self._document_handler = document_handler\n self._kwargs = kwargs\n self._read_listeners = []\n self._skip_listeners = []\n self._processed_files = {}\n self._reader_thread = None\n self._reader_thread_lock = threading.RLock()\n self._iter_lock = threading.RLock()\n self._iter_notice = threading.Event()\n self._is_stopped = threading.Event()\n self._unreturned_descriptors = queue.Queue(buffer_size)\n", "repository": "illumineinteractive/stem", "test_name": "test_skip_listener_already_read", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001082.py"} {"focal_file": "stem/descriptor/tordnsel.py", "focal_class": null, "focal_method": "_parse_file", "tests": "import unittest\n\nclass Test_parse_file(unittest.TestCase):\n def test_parse_file(self):\n \"\"\"\n Try parsing a document via the _parse_file() function.\n \"\"\"\n descriptors = list(_parse_file(io.BytesIO(TEST_DESC)))\n self.assertEqual(3, len(descriptors))\n self.assertTrue(isinstance(descriptors[0], TorDNSEL))\n desc = descriptors[1]\n self.assertTrue(is_valid_fingerprint(desc.fingerprint))\n self.assertEqual('00FF300624FECA7F40515C8D854EE925332580D6', desc.fingerprint)\n self.assertEqual(datetime.datetime(2013, 8, 18, 7, 2, 14), desc.published)\n self.assertEqual(datetime.datetime(2013, 8, 18, 9, 2, 58), desc.last_status)\n self.assertEqual(3, len(desc.exit_addresses))\n exit = desc.exit_addresses[0]\n self.assertEqual('82.252.181.153', exit[0])\n self.assertEqual(datetime.datetime(2013, 8, 18, 8, 3, 1), exit[1])\n extra = b'ExtraContent goes here\\n'\n descriptors = _parse_file(io.BytesIO(TEST_DESC + extra), validate=True)\n self.assertRaises(ValueError, list, descriptors)\n extra = b'ExitNode 030B22437D99B2DB2908B747B6'\n self.assertRaises(ValueError, list, _parse_file(io.BytesIO(TEST_DESC + extra), validate=True))\n self.assertRaises(ValueError, list, _parse_file(io.BytesIO(TEST_DESC + MALFORMED_ENTRY_1), validate=True))\n desc = next(_parse_file(io.BytesIO(MALFORMED_ENTRY_2), validate=False))\n self.assertTrue(is_valid_fingerprint(desc.fingerprint))\n self.assertEqual('030B22437D99B2DB2908B747B6962EAD13AB4038', desc.fingerprint)\n self.assertEqual(0, len(desc.exit_addresses))\n self.assertEqual('@type tordnsel 1.0', str(desc.type_annotation()))\n", "method_code": "def _parse_file(tordnsel_file, validate=False, **kwargs):\n \"\"\"\n Iterates over a tordnsel file.\n\n :returns: iterator for :class:`~stem.descriptor.tordnsel.TorDNSEL`\n instances in the file\n\n :raises:\n * **ValueError** if the contents is malformed and validate is **True**\n * **IOError** if the file can't be read\n \"\"\"\n _read_until_keywords('ExitNode', tordnsel_file, skip=True)\n while True:\n contents = _read_until_keywords('ExitAddress', tordnsel_file)\n contents += _read_until_keywords('ExitNode', tordnsel_file)\n if contents:\n yield TorDNSEL(bytes.join(b'', contents), validate, **kwargs)\n else:\n break", "context": "def _parse_file(tordnsel_file, validate=False, **kwargs): ...\ndef _parse_file(tordnsel_file, validate=False, **kwargs): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_parse_file", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001083.py"} {"focal_file": "stem/descriptor/server_descriptor.py", "focal_class": null, "focal_method": "digest", "tests": "import unittest\n\nclass Test_digest(unittest.TestCase):\n def test_digest(self):\n with open(get_resource('example_descriptor'), 'rb') as descriptor_file:\n desc = next(stem.descriptor.parse_file(descriptor_file, 'server-descriptor 1.0'))\n self.assertEqual('2C7B27BEAB04B4E2459D89CA6D5CD1CC5F95A689', desc.digest(DigestHash.SHA1, DigestEncoding.HEX))\n self.assertEqual('55F87C93AA5C16311308D09B94315DD1435174A95020E4FD47A70F82338BE9EA', desc.digest(DigestHash.SHA256, DigestEncoding.HEX))\n self.assertEqual('LHsnvqsEtOJFnYnKbVzRzF+Vpok', desc.digest(DigestHash.SHA1, DigestEncoding.BASE64))\n self.assertEqual('Vfh8k6pcFjETCNCblDFd0UNRdKlQIOT9R6cPgjOL6eo', desc.digest(DigestHash.SHA256, DigestEncoding.BASE64))\n digested_content = desc._content_range(start='router', end='\\nrouter-signature\\n')\n self.assertEqual(hashlib.sha1(digested_content).digest(), desc.digest(DigestHash.SHA1, DigestEncoding.RAW).digest())\n self.assertEqual(hashlib.sha256(digested_content).digest(), desc.digest(DigestHash.SHA256, DigestEncoding.RAW).digest())\n self.assertRaisesWith(NotImplementedError, 'Server descriptor digests are only available in sha1 and sha256, not bad-hash', desc.digest, 'bad-hash')\n self.assertRaisesWith(ValueError, 'Digest encodings should be among our DigestEncoding enumeration (RAW, HEX, BASE64), not BAD_ENCODING', desc.digest, DigestHash.SHA1, 'BAD_ENCODING')\n", "method_code": " def digest(self, hash_type=DigestHash.SHA1, encoding=DigestEncoding.HEX):\n \"\"\"\n Digest of this descriptor's content. These are referenced by...\n \n * **Consensus**\n \n * Referer: :class:`~stem.descriptor.router_status_entry.RouterStatusEntryV3` **digest** attribute\n * Format: **SHA1/BASE64**\n \n .. versionchanged:: 1.8.0\n Added the hash_type and encoding arguments.\n \n :param stem.descriptor.DigestHash hash_type: digest hashing algorithm\n :param stem.descriptor.DigestEncoding encoding: digest encoding\n \n :returns: **hashlib.HASH** or **str** based on our encoding argument\n \"\"\"\n raise NotImplementedError('Unsupported Operation: this should be implemented by the ServerDescriptor subclass')\n ", "context": "class ServerDescriptor(Descriptor):\n def digest(self, hash_type=DigestHash.SHA1, encoding=DigestEncoding.HEX): ...\n def __init__(self, raw_contents, validate=False, annotations=None): ...\n def get_annotations(self): ...\n def get_annotation_lines(self): ...\n def _check_constraints(self, entries): ...\n def _required_fields(self): ...\n def _single_fields(self): ...\n def _first_keyword(self): ...\n def _last_keyword(self): ...\n\n self._annotation_lines = annotations if annotations else []\n self.hidden_service_dir = ['2']\n\n ATTRIBUTES = {'nickname': (None, _parse_router_line), 'fingerprint': (None, _parse_fingerprint_line), 'contact': (None, _parse_contact_line), 'published': (None, _parse_published_line), 'exit_policy': (None, _parse_exit_policy), 'address': (None, _parse_router_line), 'or_port': (None, _parse_router_line), 'socks_port': (None, _parse_router_line), 'dir_port': (None, _parse_router_line), 'platform': (None, _parse_platform_line), 'tor_version': (None, _parse_platform_line), 'operating_system': (None, _parse_platform_line), 'uptime': (None, _parse_uptime_line), 'exit_policy_v6': (DEFAULT_IPV6_EXIT_POLICY, _parse_ipv6_policy_line), 'bridge_distribution': (DEFAULT_BRIDGE_DISTRIBUTION, _parse_bridge_distribution_request_line), 'family': (set(), _parse_family_line), 'average_bandwidth': (None, _parse_bandwidth_line), 'burst_bandwidth': (None, _parse_bandwidth_line), 'observed_bandwidth': (None, _parse_bandwidth_line), 'link_protocols': (None, _parse_protocols_line), 'circuit_protocols': (None, _parse_protocols_line), 'is_hidden_service_dir': (False, _parse_hidden_service_dir_line), 'hibernating': (False, _parse_hibernating_line), 'allow_single_hop_exits': (False, _parse_allow_single_hop_exits_line), 'allow_tunneled_dir_requests': (False, _parse_tunneled_dir_server_line), 'protocols': ({}, _parse_proto_line), 'extra_info_cache': (False, _parse_caches_extra_info_line), 'extra_info_digest': (None, _parse_extrainfo_digest_line), 'extra_info_sha256_digest': (None, _parse_extrainfo_digest_line), 'eventdns': (None, _parse_eventdns_line), 'ntor_onion_key': (None, _parse_ntor_onion_key_line), 'or_addresses': ([], _parse_or_address_line), 'read_history_end': (None, _parse_read_history_line), 'read_history_interval': (None, _parse_read_history_line), 'read_history_values': (None, _parse_read_history_line), 'write_history_end': (None, _parse_write_history_line), 'write_history_interval': (None, _parse_write_history_line), 'write_history_values': (None, _parse_write_history_line)}\n PARSER_FOR_LINE = {'router': _parse_router_line, 'bandwidth': _parse_bandwidth_line, 'platform': _parse_platform_line, 'published': _parse_published_line, 'fingerprint': _parse_fingerprint_line, 'contact': _parse_contact_line, 'hibernating': _parse_hibernating_line, 'extra-info-digest': _parse_extrainfo_digest_line, 'hidden-service-dir': _parse_hidden_service_dir_line, 'uptime': _parse_uptime_line, 'protocols': _parse_protocols_line, 'ntor-onion-key': _parse_ntor_onion_key_line, 'or-address': _parse_or_address_line, 'read-history': _parse_read_history_line, 'write-history': _parse_write_history_line, 'ipv6-policy': _parse_ipv6_policy_line, 'allow-single-hop-exits': _parse_allow_single_hop_exits_line, 'tunnelled-dir-server': _parse_tunneled_dir_server_line, 'proto': _parse_proto_line, 'caches-extra-info': _parse_caches_extra_info_line, 'bridge-distribution-request': _parse_bridge_distribution_request_line, 'family': _parse_family_line, 'eventdns': _parse_eventdns_line}\n", "repository": "illumineinteractive/stem", "test_name": "test_digest", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001084.py"} {"focal_file": "stem/descriptor/server_descriptor.py", "focal_class": null, "focal_method": "get_annotations", "tests": "import unittest\n\nclass Test_get_annotations(unittest.TestCase):\n @patch('stem.prereq.is_crypto_available', Mock(return_value=False))\n def test_annotations(self):\n \"\"\"\n Checks that content before a descriptor are parsed as annotations.\n \"\"\"\n desc_text = b'@pepperjack very tasty\\n@mushrooms not so much\\n'\n desc_text += RelayDescriptor.content()\n desc_text += b'\\ntrailing text that should be invalid, ho hum'\n desc_iter = stem.descriptor.server_descriptor._parse_file(io.BytesIO(desc_text), validate=True)\n self.assertRaises(ValueError, list, desc_iter)\n desc_text = b'@pepperjack very tasty\\n@mushrooms not so much\\n'\n desc_text += RelayDescriptor.content({'router': 'caerSidi 71.35.133.197 9001 0 0'})\n desc_iter = stem.descriptor.server_descriptor._parse_file(io.BytesIO(desc_text))\n desc_entries = list(desc_iter)\n self.assertEqual(1, len(desc_entries))\n desc = desc_entries[0]\n self.assertEqual('caerSidi', desc.nickname)\n self.assertEqual('@pepperjack very tasty', desc.get_annotation_lines()[0])\n self.assertEqual('@mushrooms not so much', desc.get_annotation_lines()[1])\n self.assertEqual({'@pepperjack': 'very tasty', '@mushrooms': 'not so much'}, desc.get_annotations())\n self.assertEqual([], desc.get_unrecognized_lines())\n", "method_code": " def get_annotations(self):\n \"\"\"\n Provides content that appeared prior to the descriptor. If this comes from\n the cached-descriptors file then this commonly contains content like...\n \n ::\n \n @downloaded-at 2012-03-18 21:18:29\n @source \"173.254.216.66\"\n \n .. deprecated:: 1.8.0\n Users very rarely read from cached descriptor files any longer. This\n method will be removed in Stem 2.x. If you have some need for us to keep\n this please `let me know\n `_.\n \n :returns: **dict** with the key/value pairs in our annotations\n \"\"\"\n annotation_dict = {}\n for line in self._annotation_lines:\n if ' ' in line:\n key, value = line.split(' ', 1)\n annotation_dict[key] = value\n else:\n annotation_dict[line] = None\n return annotation_dict\n ", "context": "class ServerDescriptor(Descriptor):\n @lru_cache()\n def get_annotations(self): ...\n def __init__(self, raw_contents, validate=False, annotations=None): ...\n def digest(self, hash_type=DigestHash.SHA1, encoding=DigestEncoding.HEX): ...\n def get_annotation_lines(self): ...\n def _check_constraints(self, entries): ...\n def _required_fields(self): ...\n def _single_fields(self): ...\n def _first_keyword(self): ...\n def _last_keyword(self): ...\n\n self._annotation_lines = annotations if annotations else []\n self.hidden_service_dir = ['2']\n\n ATTRIBUTES = {'nickname': (None, _parse_router_line), 'fingerprint': (None, _parse_fingerprint_line), 'contact': (None, _parse_contact_line), 'published': (None, _parse_published_line), 'exit_policy': (None, _parse_exit_policy), 'address': (None, _parse_router_line), 'or_port': (None, _parse_router_line), 'socks_port': (None, _parse_router_line), 'dir_port': (None, _parse_router_line), 'platform': (None, _parse_platform_line), 'tor_version': (None, _parse_platform_line), 'operating_system': (None, _parse_platform_line), 'uptime': (None, _parse_uptime_line), 'exit_policy_v6': (DEFAULT_IPV6_EXIT_POLICY, _parse_ipv6_policy_line), 'bridge_distribution': (DEFAULT_BRIDGE_DISTRIBUTION, _parse_bridge_distribution_request_line), 'family': (set(), _parse_family_line), 'average_bandwidth': (None, _parse_bandwidth_line), 'burst_bandwidth': (None, _parse_bandwidth_line), 'observed_bandwidth': (None, _parse_bandwidth_line), 'link_protocols': (None, _parse_protocols_line), 'circuit_protocols': (None, _parse_protocols_line), 'is_hidden_service_dir': (False, _parse_hidden_service_dir_line), 'hibernating': (False, _parse_hibernating_line), 'allow_single_hop_exits': (False, _parse_allow_single_hop_exits_line), 'allow_tunneled_dir_requests': (False, _parse_tunneled_dir_server_line), 'protocols': ({}, _parse_proto_line), 'extra_info_cache': (False, _parse_caches_extra_info_line), 'extra_info_digest': (None, _parse_extrainfo_digest_line), 'extra_info_sha256_digest': (None, _parse_extrainfo_digest_line), 'eventdns': (None, _parse_eventdns_line), 'ntor_onion_key': (None, _parse_ntor_onion_key_line), 'or_addresses': ([], _parse_or_address_line), 'read_history_end': (None, _parse_read_history_line), 'read_history_interval': (None, _parse_read_history_line), 'read_history_values': (None, _parse_read_history_line), 'write_history_end': (None, _parse_write_history_line), 'write_history_interval': (None, _parse_write_history_line), 'write_history_values': (None, _parse_write_history_line)}\n PARSER_FOR_LINE = {'router': _parse_router_line, 'bandwidth': _parse_bandwidth_line, 'platform': _parse_platform_line, 'published': _parse_published_line, 'fingerprint': _parse_fingerprint_line, 'contact': _parse_contact_line, 'hibernating': _parse_hibernating_line, 'extra-info-digest': _parse_extrainfo_digest_line, 'hidden-service-dir': _parse_hidden_service_dir_line, 'uptime': _parse_uptime_line, 'protocols': _parse_protocols_line, 'ntor-onion-key': _parse_ntor_onion_key_line, 'or-address': _parse_or_address_line, 'read-history': _parse_read_history_line, 'write-history': _parse_write_history_line, 'ipv6-policy': _parse_ipv6_policy_line, 'allow-single-hop-exits': _parse_allow_single_hop_exits_line, 'tunnelled-dir-server': _parse_tunneled_dir_server_line, 'proto': _parse_proto_line, 'caches-extra-info': _parse_caches_extra_info_line, 'bridge-distribution-request': _parse_bridge_distribution_request_line, 'family': _parse_family_line, 'eventdns': _parse_eventdns_line}\n", "repository": "illumineinteractive/stem", "test_name": "", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001085.py"} {"focal_file": "stem/descriptor/server_descriptor.py", "focal_class": "BridgeDescriptor", "focal_method": "digest", "tests": "import unittest\n\nclass Test_BridgeDescriptor_digest(unittest.TestCase):\n def test_router_digest(self):\n \"\"\"\n Constructs with a router-digest line with both valid and invalid contents.\n \"\"\"\n router_digest = '068A2E28D4C934D9490303B7A645BA068DCA0504'\n desc = BridgeDescriptor.create({'router-digest': router_digest})\n self.assertEqual(router_digest, desc.digest())\n desc_text = BridgeDescriptor.content(exclude=['router-digest'])\n self.assertRaises(ValueError, BridgeDescriptor, desc_text, True)\n desc = BridgeDescriptor(desc_text, validate=False)\n self.assertEqual(None, desc.digest())\n test_values = ('', '006FD96BA35E7785A6A3B8B75FE2E2435A13BDB44', '006FD96BA35E7785A6A3B8B75FE2E2435A13BDB', '006FD96BA35E7785A6A3B8B75FE2E2435A13BDBH')\n for value in test_values:\n desc_text = BridgeDescriptor.content({'router-digest': value})\n self.assertRaises(ValueError, BridgeDescriptor, desc_text, True)\n desc = BridgeDescriptor(desc_text, validate=False)\n self.assertEqual(None, desc.digest())\n", "method_code": " def digest(self, hash_type=DigestHash.SHA1, encoding=DigestEncoding.HEX):\n \"\"\"\n Digest of this descriptor's content. These are referenced by...\n \n * **Consensus**\n \n * Referer: :class:`~stem.descriptor.router_status_entry.RouterStatusEntryV3` **digest** attribute\n * Format: **SHA1/BASE64**\n \n .. versionchanged:: 1.8.0\n Added the hash_type and encoding arguments.\n \n :param stem.descriptor.DigestHash hash_type: digest hashing algorithm\n :param stem.descriptor.DigestEncoding encoding: digest encoding\n \n :returns: **hashlib.HASH** or **str** based on our encoding argument\n \"\"\"\n raise NotImplementedError('Unsupported Operation: this should be implemented by the ServerDescriptor subclass')\n ", "context": "class ServerDescriptor(Descriptor):\n def digest(self, hash_type=DigestHash.SHA1, encoding=DigestEncoding.HEX): ...\n def __init__(self, raw_contents, validate=False, annotations=None): ...\n def get_annotations(self): ...\n def get_annotation_lines(self): ...\n def _check_constraints(self, entries): ...\n def _required_fields(self): ...\n def _single_fields(self): ...\n def _first_keyword(self): ...\n def _last_keyword(self): ...\n\n self._annotation_lines = annotations if annotations else []\n self.hidden_service_dir = ['2']\n\n ATTRIBUTES = {'nickname': (None, _parse_router_line), 'fingerprint': (None, _parse_fingerprint_line), 'contact': (None, _parse_contact_line), 'published': (None, _parse_published_line), 'exit_policy': (None, _parse_exit_policy), 'address': (None, _parse_router_line), 'or_port': (None, _parse_router_line), 'socks_port': (None, _parse_router_line), 'dir_port': (None, _parse_router_line), 'platform': (None, _parse_platform_line), 'tor_version': (None, _parse_platform_line), 'operating_system': (None, _parse_platform_line), 'uptime': (None, _parse_uptime_line), 'exit_policy_v6': (DEFAULT_IPV6_EXIT_POLICY, _parse_ipv6_policy_line), 'bridge_distribution': (DEFAULT_BRIDGE_DISTRIBUTION, _parse_bridge_distribution_request_line), 'family': (set(), _parse_family_line), 'average_bandwidth': (None, _parse_bandwidth_line), 'burst_bandwidth': (None, _parse_bandwidth_line), 'observed_bandwidth': (None, _parse_bandwidth_line), 'link_protocols': (None, _parse_protocols_line), 'circuit_protocols': (None, _parse_protocols_line), 'is_hidden_service_dir': (False, _parse_hidden_service_dir_line), 'hibernating': (False, _parse_hibernating_line), 'allow_single_hop_exits': (False, _parse_allow_single_hop_exits_line), 'allow_tunneled_dir_requests': (False, _parse_tunneled_dir_server_line), 'protocols': ({}, _parse_proto_line), 'extra_info_cache': (False, _parse_caches_extra_info_line), 'extra_info_digest': (None, _parse_extrainfo_digest_line), 'extra_info_sha256_digest': (None, _parse_extrainfo_digest_line), 'eventdns': (None, _parse_eventdns_line), 'ntor_onion_key': (None, _parse_ntor_onion_key_line), 'or_addresses': ([], _parse_or_address_line), 'read_history_end': (None, _parse_read_history_line), 'read_history_interval': (None, _parse_read_history_line), 'read_history_values': (None, _parse_read_history_line), 'write_history_end': (None, _parse_write_history_line), 'write_history_interval': (None, _parse_write_history_line), 'write_history_values': (None, _parse_write_history_line)}\n PARSER_FOR_LINE = {'router': _parse_router_line, 'bandwidth': _parse_bandwidth_line, 'platform': _parse_platform_line, 'published': _parse_published_line, 'fingerprint': _parse_fingerprint_line, 'contact': _parse_contact_line, 'hibernating': _parse_hibernating_line, 'extra-info-digest': _parse_extrainfo_digest_line, 'hidden-service-dir': _parse_hidden_service_dir_line, 'uptime': _parse_uptime_line, 'protocols': _parse_protocols_line, 'ntor-onion-key': _parse_ntor_onion_key_line, 'or-address': _parse_or_address_line, 'read-history': _parse_read_history_line, 'write-history': _parse_write_history_line, 'ipv6-policy': _parse_ipv6_policy_line, 'allow-single-hop-exits': _parse_allow_single_hop_exits_line, 'tunnelled-dir-server': _parse_tunneled_dir_server_line, 'proto': _parse_proto_line, 'caches-extra-info': _parse_caches_extra_info_line, 'bridge-distribution-request': _parse_bridge_distribution_request_line, 'family': _parse_family_line, 'eventdns': _parse_eventdns_line}\n", "repository": "illumineinteractive/stem", "test_name": "test_router_digest", "smells": [1, 0, 0, 0, 1, 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": [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], "pynose_source_file": "test_001086.py"} {"focal_file": "stem/descriptor/networkstatus.py", "focal_class": null, "focal_method": "get_unrecognized_lines", "tests": "import unittest\n\nclass Test_get_unrecognized_lines(unittest.TestCase):\n def test_unrecognized_line(self):\n \"\"\"\n Includes unrecognized content in the descriptor.\n \"\"\"\n authority = DirectoryAuthority.create({'pepperjack': 'is oh so tasty!'})\n self.assertEqual(['pepperjack is oh so tasty!'], authority.get_unrecognized_lines())\n\n def test_unrecognized_line(self):\n \"\"\"\n Includes unrecognized content in the descriptor.\n \"\"\"\n sig = DetachedSignature.create({'pepperjack': 'is oh so tasty!'})\n self.assertEqual(['pepperjack is oh so tasty!'], sig.get_unrecognized_lines())\n", "method_code": " def get_unrecognized_lines(self):\n if self._lazy_loading:\n self._parse(self._header_entries, False, parser_for_line=self._HEADER_PARSER_FOR_LINE)\n self._parse(self._footer_entries, False, parser_for_line=self._FOOTER_PARSER_FOR_LINE)\n self._lazy_loading = False\n return super(NetworkStatusDocumentV3, self).get_unrecognized_lines()\n ", "context": "class NetworkStatusDocumentV3(NetworkStatusDocument):\n def get_unrecognized_lines(self): ...\n def content(cls, attr=None, exclude=(), sign=False, authorities=None, routers=None): ...\n def create(cls, attr=None, exclude=(), validate=True, sign=False, authorities=None, routers=None): ...\n def __init__(self, raw_content, validate=False, default_params=True): ...\n def type_annotation(self): ...\n def is_valid(self): ...\n def is_fresh(self): ...\n def validate_signatures(self, key_certs): ...\n def meets_consensus_method(self, method): ...\n def _header(self, document_file, validate): ...\n def _footer(self, document_file, validate): ...\n def _check_params_constraints(self): ...\n\n self.is_shared_randomness_participate = False\n self.shared_randomness_commitments = []\n self._default_params = default_params\n self.directory_authorities = tuple(stem.descriptor.router_status_entry._parse_file(document_file, validate, entry_class=DirectoryAuthority, entry_keyword=AUTH_START, section_end_keywords=(ROUTERS_START, FOOTER_START, V2_FOOTER_START), extra_args=(self.is_vote,)))\n self.routers = dict(((desc.fingerprint, desc) for desc in router_iter))\n\n ATTRIBUTES = {'version': (None, _parse_header_network_status_version_line), 'version_flavor': ('ns', _parse_header_network_status_version_line), 'is_consensus': (True, _parse_header_vote_status_line), 'is_vote': (False, _parse_header_vote_status_line), 'is_microdescriptor': (False, _parse_header_network_status_version_line), 'consensus_methods': ([], _parse_header_consensus_methods_line), 'published': (None, _parse_published_line), 'consensus_method': (None, _parse_header_consensus_method_line), 'valid_after': (None, _parse_header_valid_after_line), 'fresh_until': (None, _parse_header_fresh_until_line), 'valid_until': (None, _parse_header_valid_until_line), 'vote_delay': (None, _parse_header_voting_delay_line), 'dist_delay': (None, _parse_header_voting_delay_line), 'client_versions': ([], _parse_header_client_versions_line), 'server_versions': ([], _parse_header_server_versions_line), 'packages': ([], _parse_package_line), 'known_flags': ([], _parse_header_known_flags_line), 'flag_thresholds': ({}, _parse_header_flag_thresholds_line), 'recommended_client_protocols': ({}, _parse_recommended_client_protocols_line), 'recommended_relay_protocols': ({}, _parse_recommended_relay_protocols_line), 'required_client_protocols': ({}, _parse_required_client_protocols_line), 'required_relay_protocols': ({}, _parse_required_relay_protocols_line), 'params': ({}, _parse_header_parameters_line), 'shared_randomness_previous_reveal_count': (None, _parse_shared_rand_previous_value), 'shared_randomness_previous_value': (None, _parse_shared_rand_previous_value), 'shared_randomness_current_reveal_count': (None, _parse_shared_rand_current_value), 'shared_randomness_current_value': (None, _parse_shared_rand_current_value), 'bandwidth_file_headers': ({}, _parse_bandwidth_file_headers), 'bandwidth_file_digest': ({}, _parse_bandwidth_file_digest), 'signatures': ([], _parse_footer_directory_signature_line), 'bandwidth_weights': ({}, _parse_footer_bandwidth_weights_line)}\n _HEADER_PARSER_FOR_LINE = {'network-status-version': _parse_header_network_status_version_line, 'vote-status': _parse_header_vote_status_line, 'consensus-methods': _parse_header_consensus_methods_line, 'consensus-method': _parse_header_consensus_method_line, 'published': _parse_published_line, 'valid-after': _parse_header_valid_after_line, 'fresh-until': _parse_header_fresh_until_line, 'valid-until': _parse_header_valid_until_line, 'voting-delay': _parse_header_voting_delay_line, 'client-versions': _parse_header_client_versions_line, 'server-versions': _parse_header_server_versions_line, 'package': _parse_package_line, 'known-flags': _parse_header_known_flags_line, 'flag-thresholds': _parse_header_flag_thresholds_line, 'recommended-client-protocols': _parse_recommended_client_protocols_line, 'recommended-relay-protocols': _parse_recommended_relay_protocols_line, 'required-client-protocols': _parse_required_client_protocols_line, 'required-relay-protocols': _parse_required_relay_protocols_line, 'params': _parse_header_parameters_line, 'shared-rand-previous-value': _parse_shared_rand_previous_value, 'shared-rand-current-value': _parse_shared_rand_current_value, 'bandwidth-file-headers': _parse_bandwidth_file_headers, 'bandwidth-file-digest': _parse_bandwidth_file_digest}\n _FOOTER_PARSER_FOR_LINE = {'directory-footer': _parse_directory_footer_line, 'bandwidth-weights': _parse_footer_bandwidth_weights_line, 'directory-signature': _parse_footer_directory_signature_line}\n", "repository": "illumineinteractive/stem", "test_name": "test_unrecognized_line", "smells": [1, 0, 0, 0, 1, 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_001087.py"} {"focal_file": "stem/descriptor/networkstatus.py", "focal_class": "DocumentSignature", "focal_method": "_parse_file_detached_sigs", "tests": "import unittest\n\nclass Test_DocumentSignature_parse_file_detached_sigs(unittest.TestCase):\n def test_real_detached_signatures(self):\n \"\"\"\n Checks that actual detached signatures can be properly parsed.\n \"\"\"\n expected_additional_sigs = [DocumentSignature('sha256', '0232AF901C31A04EE9848595AF9BB7620D4C5B2E', 'CD1FD971855430880D3C31E0331C5C55800C2F79', BLOCK1, flavor='microdesc'), DocumentSignature('sha256', '14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4', '1F4D49989DA1503D5B20EAADB0673C948BA73B49', BLOCK2, flavor='microdesc'), DocumentSignature('sha256', '23D15D965BC35114467363C165C4F724B64B4F66', 'A2E5511319AD43DF88EABFB8BB1FFD767D005601', BLOCK3, flavor='microdesc')]\n expected_sigs = [DocumentSignature('sha1', '0232AF901C31A04EE9848595AF9BB7620D4C5B2E', 'CD1FD971855430880D3C31E0331C5C55800C2F79', BLOCK4), DocumentSignature('sha1', '14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4', '1F4D49989DA1503D5B20EAADB0673C948BA73B49', BLOCK5), DocumentSignature('sha1', '23D15D965BC35114467363C165C4F724B64B4F66', 'A2E5511319AD43DF88EABFB8BB1FFD767D005601', BLOCK6)]\n with open(get_resource('detached_signatures'), 'rb') as sig_file:\n sig = next(_parse_file_detached_sigs(sig_file, 'dir-key-certificate-3 1.0'))\n self.assertEqual('244E0760BB0B1E5418A4A014822F804AFE0CC3D6', sig.consensus_digest)\n self.assertEqual(datetime.datetime(2018, 11, 22, 20, 0), sig.valid_after)\n self.assertEqual(datetime.datetime(2018, 11, 22, 21, 0), sig.fresh_until)\n self.assertEqual(datetime.datetime(2018, 11, 22, 23, 0), sig.valid_until)\n self.assertEqual([DocumentDigest('microdesc', 'sha256', 'EC7F220E415F62394565259F9E44133800F749BFEFB358A3D7F622B8A1728A47')], sig.additional_digests)\n self.assertEqual(9, len(sig.additional_signatures))\n self.assertEqual(expected_additional_sigs, sig.additional_signatures[:3])\n self.assertEqual(9, len(sig.signatures))\n self.assertEqual(expected_sigs, sig.signatures[:3])\n self.assertEqual([], sig.get_unrecognized_lines())\n", "method_code": "def _parse_file_detached_sigs(detached_signature_file, validate=False):\n \"\"\"\n Parses a file containing one or more detached signatures.\n\n :param file detached_signature_file: file with detached signatures\n :param bool validate: checks the validity of the detached signature's\n contents if **True**, skips these checks otherwise\n\n :returns: iterator for :class:`stem.descriptor.networkstatus.DetachedSignature`\n instances in the file\n\n :raises:\n * **ValueError** if the detached signatures are invalid and validate is **True**\n * **IOError** if the file can't be read\n \"\"\"\n while True:\n detached_sig_content = _read_until_keywords('consensus-digest', detached_signature_file, ignore_first=True)\n if detached_sig_content:\n yield stem.descriptor.networkstatus.DetachedSignature(bytes.join(b'', detached_sig_content), validate=validate)\n else:\n break", "context": "def _parse_file_detached_sigs(detached_signature_file, validate=False): ...\ndef _parse_file(document_file, document_type=None, validate=False, is_microdescriptor=False, document_handler=DocumentHandler.ENTRIES, **kwargs): ...\ndef _parse_file_key_certs(certificate_file, validate=False): ...\ndef _parse_file_detached_sigs(detached_signature_file, validate=False): ...\ndef _parse_version_line(keyword, attribute, expected_version): ...\ndef _parse_dir_source_line(descriptor, entries): ...\ndef _parse_additional_digests(descriptor, entries): ...\ndef _parse_additional_signatures(descriptor, entries): ...\ndef _parse_header_network_status_version_line(descriptor, entries): ...\ndef _parse_header_vote_status_line(descriptor, entries): ...\ndef _parse_header_consensus_methods_line(descriptor, entries): ...\ndef _parse_header_consensus_method_line(descriptor, entries): ...\ndef _parse_header_voting_delay_line(descriptor, entries): ...\ndef _parse_versions_line(keyword, attribute): ...\ndef _parse_header_flag_thresholds_line(descriptor, entries): ...\ndef _parse_header_parameters_line(descriptor, entries): ...\ndef _parse_directory_footer_line(descriptor, entries): ...\ndef _parse_footer_directory_signature_line(descriptor, entries): ...\ndef _parse_package_line(descriptor, entries): ...\ndef _parsed_shared_rand_commit(descriptor, entries): ...\ndef _parse_shared_rand_previous_value(descriptor, entries): ...\ndef _parse_shared_rand_current_value(descriptor, entries): ...\ndef _parse_bandwidth_file_headers(descriptor, entries): ...\ndef _parse_bandwidth_file_digest(descriptor, entries): ...\ndef _check_for_missing_and_disallowed_fields(document, entries, fields): ...\ndef _parse_int_mappings(keyword, value, validate): ...\ndef _parse_dirauth_source_line(descriptor, entries): ...\ndef _parse_dir_address_line(descriptor, entries): ...\n", "repository": "illumineinteractive/stem", "test_name": "test_real_detached_signatures", "smells": [1, 0, 0, 0, 1, 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": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001088.py"} {"focal_file": "trie_search/trie.py", "focal_class": "TrieSearch", "focal_method": "search_all_patterns", "tests": "import unittest\n\nclass Test_TrieSearch_search_all_patterns(unittest.TestCase):\n def test_search_all_patterns(self):\n patterns = ['new york', 'york city', 'new york city']\n text = 'new york city'\n answers = {'new york': 0, 'york city': 4, 'new york city': 0}\n trie = TrieSearch(patterns=patterns)\n for ptn, idx in trie.search_all_patterns(text):\n self.assertIn(ptn, answers)\n self.assertEqual(idx, answers[ptn])\n\n def test_search_all_patterns_jp(self):\n patterns = ['ニューヨーク', 'ヨークシティ', 'ニューヨークシティ']\n text = 'ニューヨークシティ'\n answers = {'ニューヨーク': 0, 'ヨークシティ': 3, 'ニューヨークシティ': 0}\n trie = TrieSearch(patterns=patterns, splitter='')\n for ptn, idx in trie.search_all_patterns(text):\n self.assertIn(ptn, answers)\n self.assertEqual(idx, answers[ptn])\n", "method_code": " def search_all_patterns(self, text):\n text_idx = 0\n for line in re.split('[\\\\n\\\\r]', text):\n if self.splitter:\n words = re.split(self.splitter, line)\n else:\n words = line\n line_idx = 0\n for i, w in enumerate(words):\n for pattern in self.__search_prefix_patterns(w, words[i + 1:]):\n yield (pattern, text_idx + line_idx)\n line_idx += len(w) + len(self.splitter)\n text_idx += line_idx\n ", "context": "class TrieSearch(Trie):\n def search_all_patterns(self, text): ...\n def __init__(self, patterns=None, filepath=None, splitter=' '): ...\n def search_longest_patterns(self, text): ...\n def __search_prefix_patterns(self, query, remaining_words): ...\n\n self.splitter = splitter\n", "repository": "nkmrtty/trie-search", "test_name": "test_search_all_patterns", "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_001089.py"} {"focal_file": "trie_search/trie.py", "focal_class": "TrieSearch", "focal_method": "search_longest_patterns", "tests": "import unittest\n\nclass Test_TrieSearch_search_longest_patterns(unittest.TestCase):\n def test_search_longest_patterns(self):\n patterns = ['new york', 'york city', 'new york city']\n text = 'new york city'\n answers = {'new york city': 0}\n trie = TrieSearch(patterns=patterns)\n for ptn, idx in trie.search_longest_patterns(text):\n self.assertIn(ptn, answers)\n self.assertEqual(idx, answers[ptn])\n\n def test_search_longest_patterns_jp(self):\n patterns = ['ニューヨーク', 'ヨークシティ', 'ニューヨークシティ']\n text = 'ニューヨークシティ'\n answers = {'ニューヨークシティ': 0}\n trie = TrieSearch(patterns=patterns, splitter='')\n for ptn, idx in trie.search_longest_patterns(text):\n self.assertIn(ptn, answers)\n self.assertEqual(idx, answers[ptn])\n", "method_code": " def search_longest_patterns(self, text):\n all_patterns = self.search_all_patterns(text)\n check_field = [0] * len(text)\n for pattern, start_idx in sorted(all_patterns, key=lambda x: len(x[0]), reverse=True):\n target_field = check_field[start_idx:start_idx + len(pattern)]\n check_sum = sum(target_field)\n if check_sum == 0:\n for i in range(len(pattern)):\n check_field[start_idx + i] = 1\n yield (pattern, start_idx)\n ", "context": "class TrieSearch(Trie):\n def search_longest_patterns(self, text): ...\n def __init__(self, patterns=None, filepath=None, splitter=' '): ...\n def search_all_patterns(self, text): ...\n def __search_prefix_patterns(self, query, remaining_words): ...\n\n self.splitter = splitter\n", "repository": "nkmrtty/trie-search", "test_name": "test_search_longest_patterns", "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_001090.py"} {"focal_file": "downloader.py", "focal_class": null, "focal_method": "download_image", "tests": "import unittest\n\nclass Test_download_image(unittest.TestCase):\n def test_download(self):\n download_image(APP_STORE_US_GOOGLE, print_only=False, save_path='./')\n contain_google = list(filter(lambda x: 'google' in x.lower(), os.listdir()))\n self.assertTrue(len(contain_google) > 0)\n self.assertIsNotNone(re.match('Google_[0-9.]+_[0-9]+x0w.(jpg|png)', contain_google[0]))\n os.remove(contain_google[0])\n", "method_code": "def download_image(app_url: str, print_only: bool=False, args_name: str=None, save_path: str=None):\n if not save_path:\n save_path = os.path.join(os.path.expanduser('~'), 'Downloads')\n try:\n app_name, app_url_cleaned, app_version, img_ext, image_url_orig = get_orig_img_url(app_url)\n except urllib.error.HTTPError and ValueError:\n print('Error 404: Page Not Found', file=stderr)\n print('Nothing is downloaded!', file=stderr)\n return\n image_url_10240x0w, img_bin, img_size_tup = get_img_maxsize(image_url_orig)\n if os.environ.get('TERM_PROGRAM') == 'iTerm.app':\n image_url_128 = change_img_url_size(image_url_10240x0w, 128)\n with request.urlopen(image_url_128) as resp:\n image_bin_128 = resp.read()\n show_image_in_terminal(app_name, image_bin_128, Image.open(BytesIO(image_bin_128)).size)\n if print_only:\n print('app name:', app_name)\n print('version:', app_version if app_version else '[N/A]')\n print('store url:', app_url_cleaned)\n print('image url:', change_img_url_size(image_url_10240x0w, img_size_tup[0]))\n else:\n if args_name:\n app_name = args_name\n output_file_name = app_name + ('_' + app_version if app_version else '') + '_' + str(img_size_tup[0]) + ('x0w' if img_size_tup[0] == img_size_tup[1] else f'x{str(img_size_tup[1])}') + '.' + img_ext\n print('saving image to file \"' + output_file_name + '\"')\n with open(os.path.join(save_path, output_file_name), 'wb') as file:\n file.write(img_bin)\n print('success!')", "context": "def download_image(app_url: str, print_only: bool=False, args_name: str=None, save_path: str=None): ...\ndef download_image(app_url: str, print_only: bool=False, args_name: str=None, save_path: str=None): ...\n", "repository": "eric1932/AppStoreIconDownloader", "test_name": "test_download", "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_001091.py"} {"focal_file": "tests/unit_tests/test_export.py", "focal_class": null, "focal_method": "_train_and_export", "tests": "import unittest\n\nclass Test_train_and_export(unittest.TestCase):\n def test_export(self):\n self._train_and_export()\n model_name = 'test'\n model_path = '.'\n signature = 'signature.json'\n synset = 'synset.txt'\n export_path = '.'\n cmd = 'python ../../export_model.py --model %s=%s --signature %s --synset %s --export-path %s' % (model_name, model_path, signature, synset, export_path)\n os.system(cmd)\n assert os.path.isfile('test.zip'), 'No zip file is found. Export failed!'\n mx_vision_service('test.zip')\n", "method_code": " def _train_and_export(self):\n num_class = 10\n data1 = mx.sym.Variable('data1')\n data2 = mx.sym.Variable('data2')\n conv1 = mx.sym.Convolution(data=data1, kernel=(2, 2), num_filter=2, stride=(2, 2))\n conv2 = mx.sym.Convolution(data=data2, kernel=(3, 3), num_filter=3, stride=(1, 1))\n pooling1 = mx.sym.Pooling(data=conv1, kernel=(2, 2), stride=(1, 1), pool_type='avg')\n pooling2 = mx.sym.Pooling(data=conv2, kernel=(2, 2), stride=(1, 1), pool_type='max')\n flatten1 = mx.sym.flatten(data=pooling1)\n flatten2 = mx.sym.flatten(data=pooling2)\n sum = mx.sym.sum(data=flatten1, axis=1) + mx.sym.sum(data=flatten2, axis=1)\n fc = mx.sym.FullyConnected(data=sum, num_hidden=num_class)\n sym = mx.sym.SoftmaxOutput(data=fc, name='softmax')\n dshape1 = (10, 3, 64, 64)\n dshape2 = (10, 3, 32, 32)\n lshape = (10,)\n mod = mx.mod.Module(symbol=sym, data_names=('data1', 'data2'), label_names=('softmax_label',))\n mod.bind(data_shapes=[('data1', dshape1), ('data2', dshape2)], label_shapes=[('softmax_label', lshape)])\n mod.init_params()\n mod.init_optimizer(optimizer_params={'learning_rate': 0.01})\n data_batch = mx.io.DataBatch(data=[mx.nd.random.uniform(0, 9, dshape1), mx.nd.random.uniform(5, 15, dshape2)], label=[mx.nd.ones(lshape)])\n mod.forward(data_batch)\n mod.backward()\n mod.update()\n with open('synset.txt', 'w') as synset:\n for i in range(10):\n synset.write('test label %d\\n' % i)\n with open('signature.json', 'w') as sig:\n signature = {'input_type': 'image/jpeg', 'inputs': [{'data_name': 'data1', 'data_shape': [1, 3, 64, 64]}, {'data_name': 'data2', 'data_shape': [1, 3, 32, 32]}], 'output_type': 'application/json', 'outputs': [{'data_name': 'softmax', 'data_shape': [1, 10]}]}\n json.dump(signature, sig)\n mod.save_checkpoint('test', 0)\n ", "context": "class TestExport(unittest.TestCase):\n def _train_and_export(self): ...\n def test_export(self): ...\n def runTest(self): ...\n", "repository": "yuruofeifei/mms", "test_name": "test_export", "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_001092.py"} {"focal_file": "utils.py", "focal_class": null, "focal_method": "are_overlapping", "tests": "import unittest\n\nclass Test_are_overlapping(unittest.TestCase):\n def test_are_overlapping(self):\n self.assertTrue(are_overlapping([2, 1, 7, 6], [5, 4, 11, 8]))\n self.assertFalse(are_overlapping([2, 1, 7, 6], [8, 6, 13, 9]))\n", "method_code": "def are_overlapping(bbox1, bbox2):\n ymin1, xmin1, ymax1, xmax1 = bbox1\n ymin2, xmin2, ymax2, xmax2 = bbox2\n vertexes = [(xmin1, ymin1), (xmin1, ymax1), (xmax1, ymin1), (xmax1, ymax1)]\n for x, y in vertexes:\n if xmin2 < x < xmax2 and ymin2 < y < ymax2:\n return True\n return False", "context": "def are_overlapping(bbox1, bbox2): ...\ndef are_overlapping(bbox1, bbox2): ...\ndef generate_background_bbox(image_shape, bbox_shape, existing_bboxes, n_attempts=10): ...\n", "repository": "IshitaTakeshi/RoadDamageDetector", "test_name": "test_are_overlapping", "smells": [1, 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": [1, 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": "utils.py", "focal_class": null, "focal_method": "generate_background_bbox", "tests": "import unittest\n\nclass Test_generate_background_bbox(unittest.TestCase):\n def test_generate_background(self):\n existing_bboxes = [[3, 4, 8, 9], [13, 1, 16, 5]]\n bbox_shape = (5, 5)\n image_shape = (23, 10)\n\n def test():\n try:\n bbox = generate_background_bbox(image_shape, bbox_shape, existing_bboxes)\n except RuntimeError:\n return\n for existing_bbox in existing_bboxes:\n self.assertFalse(are_overlapping(bbox, existing_bbox))\n for i in range(10):\n test()\n", "method_code": "def generate_background_bbox(image_shape, bbox_shape, existing_bboxes, n_attempts=10):\n \"\"\"\n Generate a bounding box that does not overlap with any `existing_bboxes`.\n The function tries generating a bounding box at most `n_attempts` times.\n Raises `RuntimeError` if a bounding box that doesn't overlap with any\n existing bounding boxes cannot be generated.\n\n Args:\n image_shape (tuple): The shape of the original image in the format of\n (height, width). Bounding boxes are generated to fit within\n `image_shape`.\n bbox_shape (tuple): The shape of a bounding box to be generated.\n existing_bboxes (list of tuples): Existing bounding boxes. The\n generated bounding box should not overlap with any\n `existing_bboxes`.\n n_attempts (int): The number of attempts to generate a bounding box\n \"\"\"\n\n def generate_candidate():\n xmin = randint(0, image_shape[0] - bbox_shape[0] + 1)\n ymin = randint(0, image_shape[1] - bbox_shape[1] + 1)\n xmax = xmin + bbox_shape[0]\n ymax = ymin + bbox_shape[1]\n return (ymin, xmin, ymax, xmax)\n\n def at_least_one_overlapping(candidate, bboxes):\n \"\"\"\n Whether there is at least one bbox that overlaps with the candidate\n \"\"\"\n for bbox in bboxes:\n if are_overlapping(candidate, bbox):\n return True\n return False\n for i in range(n_attempts):\n candidate = generate_candidate()\n if at_least_one_overlapping(candidate, existing_bboxes):\n continue\n return candidate\n raise RuntimeError('Background could not be generated')", "context": "def generate_background_bbox(image_shape, bbox_shape, existing_bboxes, n_attempts=10): ...\ndef are_overlapping(bbox1, bbox2): ...\ndef generate_background_bbox(image_shape, bbox_shape, existing_bboxes, n_attempts=10): ...\n", "repository": "IshitaTakeshi/RoadDamageDetector", "test_name": "test_generate_background", "smells": [1, 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, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "pynose_source_file": "test_001094.py"} {"focal_file": "A3/test_a3.py", "focal_class": null, "focal_method": "_test_optimalZeropad", "tests": "import unittest\n\nclass Test_test_optimalZeropad(unittest.TestCase):\n def test_optimalZeropad_1(self):\n self._test_optimalZeropad(16, 3, 1000, 100, 25)\n\n def test_optimalZeropad_2(self):\n self._test_optimalZeropad(121, 6, 10000, 250, 210)\n", "method_code": " def _test_optimalZeropad(self, length, maxbin_index, fs, f, M):\n x = self._generate_sine(fs, f)[:M]\n mX = A3Part2.optimalZeropad(x, fs, f)\n self.assertEquals(length, len(mX))\n maxbin = mX[maxbin_index]\n self.assertGreater(maxbin, mX[maxbin_index - 1])\n self.assertGreater(maxbin, mX[maxbin_index + 1])\n ", "context": "class Assignment3TestCase(unittest.TestCase):\n def _test_optimalZeropad(self, length, maxbin_index, fs, f, M): ...\n def _assert_zero_except(self, array, *non_zeros): ...\n def _generate_sine(self, fs, f): ...\n def _generate_two_sine_signal(self, fs, f1, f2): ...\n def test_minimizeEnergySpreadDFT_has_expected_bins_1(self): ...\n def test_minimizeEnergySpreadDFT_has_expected_bins_2(self): ...\n def test_optimalZeropad_1(self): ...\n def test_optimalZeropad_2(self): ...\n def test_testRealEven_1(self): ...\n def test_testRealEven_2(self): ...\n", "repository": "tlantz/course-audio-sig-proc", "test_name": "test_optimalZeropad_1", "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_001095.py"}