def test_print_entry_listing_does_nothing_with_an_empty_aggregate(): """Ensure that nothing is printed with an empty aggregate""" empty_aggregate_feed = AggregateFeed() override(sys, 'stdout') replay() FeedWriter().print_entry_listings(empty_aggregate_feed) verify()
def test_get_and_remove_conn(self): ''' Each requested connection must be closed by calling 'remove_connection' when the server doesn't support persistent HTTP Connections ''' kah = self.kahdler host = self.host conn = self.conn req = self.req ## Start recording ## method(req, 'get_host').expects().returns(host) method(req, 'get_full_url').expects().returns('test_full_url') # Override KeepAliveHandler._start_transaction override(kah, '_start_transaction').expects(conn, req).returns(None) conn_factory = kah._get_connection # Mock conn's getresponse() resp = HTTPResponse(socket.socket()) resp.will_close = True override(conn, 'getresponse').expects().returns(resp) # The connection mgr conn_mgr_mock = self.mock() method(conn_mgr_mock, 'get_available_connection').expects(host, conn_factory).returns(conn) method(conn_mgr_mock, 'remove_connection').expects(conn, host).returns(None) ## Stop Recording.Time to Play! ## self.replay() # Replace with mocked out ConnMgr. kah._cm = conn_mgr_mock kah.do_open(req) ## Verify ## self.verify()
def test_filter_files(self): from pysvn import wc_notify_action as wcna from pysvn import Revision os = get_autoupdate_os_module() client = self.client override(os.path, "isdir").expects(dontcare()).returns(False) set_count(exactly=2) ## Stop recording. Play! self.replay() # Call client's callback function several times f1 = "/path/to/file/foo.py" ev = { "action": wcna.update_delete, "error": None, "mime_type": None, "path": f1, "revision": Revision(pysvn.opt_revision_kind.number, 11), } client._register(ev) f2 = "/path/to/file/foo2.py" ev2 = { "action": wcna.update_update, "error": None, "mime_type": None, "path": f2, "revision": Revision(pysvn.opt_revision_kind.number, 11), } client._register(ev2) expected_res = SVNFilesList([(f1, FILE_DEL), (f2, FILE_UPD)]) self.assertEquals(expected_res, client._filter_files(filterbyactions=w3afSVNClient.UPD_ACTIONS)) ## Verify ## self.verify()
def test_timeout(self): """ Ensure that kah raises 'URLTimeoutError' when timeouts occur and raises 'w3afMustStopException' when the timeout limit is reached. """ kah = self.kahdler host = self.host conn = self.conn req = self.req ## Start recording ## method(req, 'get_host').expects().returns(host) method(req, 'get_host').expects().returns(host) # Override KeepAliveHandler._start_transaction - raises timeout override(kah, '_start_transaction').expects(conn, req).raises(socket.timeout) conn_factory = kah._get_connection; # The connection mgr conn_mgr = self.mock() method(conn_mgr, 'get_available_connection').expects(host, conn_factory).returns(conn) method(conn_mgr, 'remove_connection').expects(conn, host).returns(None) ## Stop Recording.Time to Play! ## self.replay() # Replace with mocked out ConnMgr. kah._cm = conn_mgr self.assertRaises(URLTimeoutError, kah.do_open, req) self.assertRaises(w3afMustStopException, kah.do_open, req) ## Verify ## self.verify()
def test_filter_files(self): from pysvn import wc_notify_action as wcna from pysvn import Revision from core.controllers.auto_update.auto_update import os client = self.client override(os.path, 'isdir').expects(dontcare()).returns(False) set_count(exactly=2) ## Stop recording. Play! self.replay() # Call client's callback function several times f1 = '/path/to/file/foo.py' ev = {'action': wcna.update_delete, 'error': None, 'mime_type': None, 'path': f1, 'revision': Revision(pysvn.opt_revision_kind.number, 11)} client._register(ev) f2 = '/path/to/file/foo2.py' ev2 = {'action': wcna.update_update, 'error': None, 'mime_type': None, 'path': f2, 'revision': Revision(pysvn.opt_revision_kind.number, 11)} client._register(ev2) expected_res = SVNFilesList([(f1, FILE_DEL), (f2, FILE_UPD)]) self.assertEquals(expected_res, client._filter_files(filterbyactions=w3afSVNClient.UPD_ACTIONS)) ## Verify ## self.verify()
def test_non_svn_install(self): """ Ensure that SVNError is raised when `get_svnversion` is called in a non svn copy. """ os = get_autoupdate_os_module() override(os, "walk").expects(dontcare()).returns(()) self.replay() self.assertRaises(SVNError, get_svnversion, (W3AF_LOCAL_PATH,))
def _sqlite_connect(): f = '/x' uri = 'sqlite:///x' connection = dummy() override(sqlobject, 'connectionForURI').expects(uri).\ returns(connection) replay() sqlite_connect(f) assert sqlobject.sqlhub.processConnection is connection verify()
def test_create_entry(): """Should create an entry and add it to the collection""" subject = AggregateFeed() (feed, entry) = (dummy(), dummy()) new_entry = dummy() override(rsreader.application, 'FeedEntry')\ .expects(feed, entry)\ .returns(new_entry) override(subject, 'add').expects(new_entry) replay() subject.create_entry(feed, entry) verify()
def test_add_single_feed(): """Should create a new entry for each entry in the feed""" subject = AggregateFeed() entries = [dummy(), dummy()] feed = mock() feed.entries returns(entries) override(subject, 'create_entry').expects(feed, entries[0]) override(subject, 'create_entry').expects(feed, entries[1]) replay() subject.add_single_feed(feed) verify()
def test_upd(self): client = self.client override(pysvn, "Revision", self.mock()) pysvnhead = pysvn.Revision(pysvn.opt_revision_kind.head) method(client._svnclient, "update").expects(LOCAL_PATH, revision=pysvnhead, depth=INF).returns([self.rev]) override(client, "_filter_files").expects(client.UPD_ACTIONS).returns(self.upd_files) ## Stop recording. Play! self.replay() self.assertEquals(self.upd_files, client.update(rev=None)) ## Verify ## self.verify()
def test_print_agg_feed_listing_is_printed(): """Should print listing of feed entries""" unsorted_entries = [ FeedEntry(xkcd_feed, xkcd_items[1]), FeedEntry(xkcd_feed, xkcd_items[0]) ] aggregate_feed = AggregateFeed() aggregate_feed.entries = unsorted_entries override(sys, 'stdout') method(sys.stdout, 'write').expects(xkcd_output + os.linesep) replay() FeedWriter().print_entry_listings(aggregate_feed) verify()
def test_upd_fail(self): override(pysvn, "Revision", self.mock()) pysvnhead = pysvn.Revision(pysvn.opt_revision_kind.head) client = self.client method(client._svnclient, "update").expects(LOCAL_PATH, revision=pysvnhead, depth=INF).raises( pysvn.ClientError("file locked") ) ## Stop recording. Play! self.replay() self.assertRaises(SVNUpdateError, client.update) ## Verify ## self.verify()
def test_upd_fail(self): override(pysvn, 'Revision', self.mock()) pysvnhead = pysvn.Revision(pysvn.opt_revision_kind.head) from core.controllers.auto_update.auto_update import SVNUpdateError client = self.client method(client._svnclient, 'update').expects(LOCAL_PATH, revision=pysvnhead) self.raises(pysvn.ClientError('file locked')) ## Stop recording. Play! self.replay() self.assertRaises(SVNUpdateError, client.update) ## Verify ## self.verify()
def test_working_copy(self): cli = self.mock() override(pysvn, 'Client').expects().returns(cli) # NOT A WORKING COPY method(cli, 'status').expects(LOCAL_PATH, recurse=False).raises(Exception()) self.replay() self.assertFalse(w3afSVNClient.is_working_copy(LOCAL_PATH)) # IS A WORKING COPY self.reset() cli = self.mock() override(pysvn, 'Client').expects().returns(cli) method(cli, 'status').expects(LOCAL_PATH, recurse=False).returns(1) self.replay() self.assertTrue(w3afSVNClient.is_working_copy(LOCAL_PATH))
def test_get_svnversion_with_non_svn_path(self): os = get_autoupdate_os_module() override(os, "walk").expects(dontcare()).generates(*([("x", "y", "z")] * 3)) cli = self.cli Rev = TestSVNVersion.Rev method(cli, "info").expects(dontcare()).returns({"revision": Rev(22)}) method(cli, "info").expects(dontcare()).returns({"revision": Rev(23)}) # If at least a 2-level depth non svn subdirectory is # found the pysvn client raises an exception method(cli, "info").expects(dontcare()).raises(pysvn.ClientError) ## Stop recording - Replay ## self.replay() self.assertEquals("22:23", get_svnversion(W3AF_LOCAL_PATH)) ## Verify ## self.verify()
def test_free_connection(self): """ Ensure that conns are returned back to the pool when requests are closed. """ override = self.override kah = self.kahdler conn = self.conn ## Start recording ## # The connection mgr conn_mgr = self.mock() override(conn_mgr, 'free_connection').expects(conn) ## Stop Recording.Time to Play! ## self.replay() kah._cm = conn_mgr kah._request_closed(conn) ## Verify ## self.verify()
def test_case_sensitivity(self): """ Ensure handler methods are *always* called with lowered-cased tag and attribute names """ def islower(s): il = False if isinstance(s, basestring): il = s.islower() elif isinstance(s, dict): il = all(k.islower() for k in s) assert il, "'%s' is not lowered-case" % s return il from itertools import combinations from random import choice tags = (A_LINK_ABSOLUTE, INPUT_CHECKBOX_WITH_NAME, SELECT_WITH_NAME, TEXTAREA_WITH_ID_AND_DATA, INPUT_HIDDEN) ops = "lower", "upper", "title" for indexes in combinations(range(len(tags)), 2): body_elems = [] for index, tag in enumerate(tags): ele = tag if index in indexes: ele = getattr(tag, choice(ops))() body_elems.append(ele) body = HTML_DOC % {"head": "", "body": "".join(body_elems)} resp = _build_http_response(URL, body) p = _SGMLParser(resp) args = (IfTrue(islower), IfTrue(islower)) override(p, "start").expects(*args).returns(None).at_least(10) # Replay self.replay() p._parse(resp) # Verify and reset self.verify() self.reset()
def test_discover_eq_routes(self): # Start recording plugininst = self.plugininst override(plugininst, '_has_permission').expects().returns(True) method(self.fuzz_req, 'getURL').expects().returns(self.test_url) # HTTPS try self._call_traceroute('host.tld', 443, self.tracedict) # HTTP try self._call_traceroute('host.tld', 80, self.tracedict) # Output Manager. It must not be called! ommock = self.mock(hvshsdist.om) ommock.out set_count(exactly=0) ## Stop Recording.Time to Play! ## self.replay() res = plugininst.discover(self.fuzz_req) self.assertEquals(res, []) ## Verify ## self.verify()
def test_discover_override_port(self): plugininst = self.plugininst override(plugininst, '_has_permission').expects().returns(True) method(self.fuzz_req, 'getURL').expects().returns('https://host.tld:4444') # HTTPS try self._call_traceroute('host.tld', 4444, self.tracedict) # HTTP try tracedict = copy.deepcopy(self.tracedict) tracedict['localhost'][3] = ('200.200.0.0', False) # Set diff hop self._call_traceroute('host.tld', 80, tracedict) # Mock output manager. Ensure that is called with the proper desc. override(hvshsdist.om.out, 'information').expects(expr(lambda x: x.find('host.tld:4444') != -1)) set_count(exactly=1) ## Stop Recording.Time to Play! ## self.replay() res = plugininst.discover(self.fuzz_req) self.assertEquals(res, []) ## Verify ## self.verify()
def test_from_urls(): """Should retrieve feeds and add them to the aggregate""" urls = [dummy(), dummy()] feeds = [dummy(), dummy()] subject = AggregateFeed() # override(feedparser, 'parse').expects(urls[0]).returns(feeds[0]) override(subject, 'add_single_feed').expects(feeds[0]) # override(feedparser, 'parse').expects(urls[1]).returns(feeds[1]) override(subject, 'add_single_feed').expects(feeds[1]) # replay() subject.from_urls(urls) verify()
def test_not_root_user(self): from core.controllers.w3afException import w3afException override(self.plugininst, '_has_permission').expects().returns(False) self.assertRaises(w3afException, self.plugininst.discover, self.fuzz_req)
def _call_traceroute(self, dest, dport, trace_resp): # Mocks scapy 'traceroute' function https_tracerout_obj = self.mock() method(https_tracerout_obj, 'get_trace').expects().returns(trace_resp) resp_tuple = (https_tracerout_obj, None) override(hvshsdist, 'traceroute').expects(dest, dport=dport).returns(resp_tuple)
def setUp(self): PyMockTestCase.setUp(self) from ..auto_update import pysvn self.cli = self.mock() override(pysvn, "Client").expects().returns(self.cli)