Best JavaScript code snippet using navalia
emma_coverage_stats_test.py
Source:emma_coverage_stats_test.py
1#!/usr/bin/python2# Copyright 2015 The Chromium Authors. All rights reserved.3# Use of this source code is governed by a BSD-style license that can be4# found in the LICENSE file.5# pylint: disable=protected-access6import unittest7from xml.etree import ElementTree8import emma_coverage_stats9from pylib.constants import host_paths10with host_paths.SysPath(host_paths.PYMOCK_PATH):11 import mock # pylint: disable=import-error12EMPTY_COVERAGE_STATS_DICT = {13 'files': {},14 'patch': {15 'incremental': {16 'covered': 0, 'total': 017 }18 }19}20class _EmmaHtmlParserTest(unittest.TestCase):21 """Tests for _EmmaHtmlParser.22 Uses modified EMMA report HTML that contains only the subset of tags needed23 for test verification.24 """25 def setUp(self):26 self.emma_dir = 'fake/dir/'27 self.parser = emma_coverage_stats._EmmaHtmlParser(self.emma_dir)28 self.simple_html = '<TR><TD CLASS="p">Test HTML</TD></TR>'29 self.index_html = (30 '<HTML>'31 '<BODY>'32 '<TABLE CLASS="hdft" CELLSPACING="0" WIDTH="100%">'33 '</TABLE>'34 '<TABLE CELLSPACING="0" WIDTH="100%">'35 '</TABLE>'36 '<TABLE CLASS="it" CELLSPACING="0">'37 '</TABLE>'38 '<TABLE CELLSPACING="0" WIDTH="100%">'39 '<TR>'40 '<TH CLASS="f">name</TH>'41 '<TH>class, %</TH>'42 '<TH>method, %</TH>'43 '<TH>block, %</TH>'44 '<TH>line, %</TH>'45 '</TR>'46 '<TR CLASS="o">'47 '<TD><A HREF="_files/0.html"'48 '>org.chromium.chrome.browser</A></TD>'49 '<TD CLASS="h">0% (0/3)</TD>'50 '</TR>'51 '<TR>'52 '<TD><A HREF="_files/1.html"'53 '>org.chromium.chrome.browser.tabmodel</A></TD>'54 '<TD CLASS="h">0% (0/8)</TD>'55 '</TR>'56 '</TABLE>'57 '<TABLE CLASS="hdft" CELLSPACING="0" WIDTH="100%">'58 '</TABLE>'59 '</BODY>'60 '</HTML>'61 )62 self.package_1_class_list_html = (63 '<HTML>'64 '<BODY>'65 '<TABLE CLASS="hdft" CELLSPACING="0" WIDTH="100%">'66 '</TABLE>'67 '<TABLE CELLSPACING="0" WIDTH="100%">'68 '</TABLE>'69 '<TABLE CELLSPACING="0" WIDTH="100%">'70 '<TR>'71 '<TH CLASS="f">name</TH>'72 '<TH>class, %</TH>'73 '<TH>method, %</TH>'74 '<TH>block, %</TH>'75 '<TH>line, %</TH>'76 '</TR>'77 '<TR CLASS="o">'78 '<TD><A HREF="1e.html">IntentHelper.java</A></TD>'79 '<TD CLASS="h">0% (0/3)</TD>'80 '<TD CLASS="h">0% (0/9)</TD>'81 '<TD CLASS="h">0% (0/97)</TD>'82 '<TD CLASS="h">0% (0/26)</TD>'83 '</TR>'84 '</TABLE>'85 '<TABLE CLASS="hdft" CELLSPACING="0" WIDTH="100%">'86 '</TABLE>'87 '</BODY>'88 '</HTML>'89 )90 self.package_2_class_list_html = (91 '<HTML>'92 '<BODY>'93 '<TABLE CLASS="hdft" CELLSPACING="0" WIDTH="100%">'94 '</TABLE>'95 '<TABLE CELLSPACING="0" WIDTH="100%">'96 '</TABLE>'97 '<TABLE CELLSPACING="0" WIDTH="100%">'98 '<TR>'99 '<TH CLASS="f">name</TH>'100 '<TH>class, %</TH>'101 '<TH>method, %</TH>'102 '<TH>block, %</TH>'103 '<TH>line, %</TH>'104 '</TR>'105 '<TR CLASS="o">'106 '<TD><A HREF="1f.html">ContentSetting.java</A></TD>'107 '<TD CLASS="h">0% (0/1)</TD>'108 '</TR>'109 '<TR>'110 '<TD><A HREF="20.html">DevToolsServer.java</A></TD>'111 '</TR>'112 '<TR CLASS="o">'113 '<TD><A HREF="21.html">FileProviderHelper.java</A></TD>'114 '</TR>'115 '<TR>'116 '<TD><A HREF="22.html">ContextualMenuBar.java</A></TD>'117 '</TR>'118 '<TR CLASS="o">'119 '<TD><A HREF="23.html">AccessibilityUtil.java</A></TD>'120 '</TR>'121 '<TR>'122 '<TD><A HREF="24.html">NavigationPopup.java</A></TD>'123 '</TR>'124 '</TABLE>'125 '<TABLE CLASS="hdft" CELLSPACING="0" WIDTH="100%">'126 '</TABLE>'127 '</BODY>'128 '</HTML>'129 )130 self.partially_covered_tr_html = (131 '<TR CLASS="p">'132 '<TD CLASS="l" TITLE="78% line coverage (7 out of 9)">108</TD>'133 '<TD TITLE="78% line coverage (7 out of 9 instructions)">'134 'if (index < 0 || index = mSelectors.size()) index = 0;</TD>'135 '</TR>'136 )137 self.covered_tr_html = (138 '<TR CLASS="c">'139 '<TD CLASS="l">110</TD>'140 '<TD> if (mSelectors.get(index) != null) {</TD>'141 '</TR>'142 )143 self.not_executable_tr_html = (144 '<TR>'145 '<TD CLASS="l">109</TD>'146 '<TD> </TD>'147 '</TR>'148 )149 self.tr_with_extra_a_tag = (150 '<TR CLASS="z">'151 '<TD CLASS="l">'152 '<A name="1f">54</A>'153 '</TD>'154 '<TD> }</TD>'155 '</TR>'156 )157 def testInit(self):158 emma_dir = self.emma_dir159 parser = emma_coverage_stats._EmmaHtmlParser(emma_dir)160 self.assertEqual(parser._base_dir, emma_dir)161 self.assertEqual(parser._emma_files_path, 'fake/dir/_files')162 self.assertEqual(parser._index_path, 'fake/dir/index.html')163 def testFindElements_basic(self):164 read_values = [self.simple_html]165 found, _ = MockOpenForFunction(self.parser._FindElements, read_values,166 file_path='fake', xpath_selector='.//TD')167 self.assertIs(type(found), list)168 self.assertIs(type(found[0]), ElementTree.Element)169 self.assertEqual(found[0].text, 'Test HTML')170 def testFindElements_multipleElements(self):171 multiple_trs = self.not_executable_tr_html + self.covered_tr_html172 read_values = ['<div>' + multiple_trs + '</div>']173 found, _ = MockOpenForFunction(self.parser._FindElements, read_values,174 file_path='fake', xpath_selector='.//TR')175 self.assertEquals(2, len(found))176 def testFindElements_noMatch(self):177 read_values = [self.simple_html]178 found, _ = MockOpenForFunction(self.parser._FindElements, read_values,179 file_path='fake', xpath_selector='.//TR')180 self.assertEqual(found, [])181 def testFindElements_badFilePath(self):182 with self.assertRaises(IOError):183 with mock.patch('os.path.exists', return_value=False):184 self.parser._FindElements('fake', xpath_selector='//tr')185 def testGetPackageNameToEmmaFileDict_basic(self):186 expected_dict = {187 'org.chromium.chrome.browser.AccessibilityUtil.java':188 'fake/dir/_files/23.html',189 'org.chromium.chrome.browser.ContextualMenuBar.java':190 'fake/dir/_files/22.html',191 'org.chromium.chrome.browser.tabmodel.IntentHelper.java':192 'fake/dir/_files/1e.html',193 'org.chromium.chrome.browser.ContentSetting.java':194 'fake/dir/_files/1f.html',195 'org.chromium.chrome.browser.DevToolsServer.java':196 'fake/dir/_files/20.html',197 'org.chromium.chrome.browser.NavigationPopup.java':198 'fake/dir/_files/24.html',199 'org.chromium.chrome.browser.FileProviderHelper.java':200 'fake/dir/_files/21.html'}201 read_values = [self.index_html, self.package_1_class_list_html,202 self.package_2_class_list_html]203 return_dict, mock_open = MockOpenForFunction(204 self.parser.GetPackageNameToEmmaFileDict, read_values)205 self.assertDictEqual(return_dict, expected_dict)206 self.assertEqual(mock_open.call_count, 3)207 calls = [mock.call('fake/dir/index.html'),208 mock.call('fake/dir/_files/1.html'),209 mock.call('fake/dir/_files/0.html')]210 mock_open.assert_has_calls(calls)211 def testGetPackageNameToEmmaFileDict_noPackageElements(self):212 self.parser._FindElements = mock.Mock(return_value=[])213 return_dict = self.parser.GetPackageNameToEmmaFileDict()214 self.assertDictEqual({}, return_dict)215 def testGetLineCoverage_status_basic(self):216 line_coverage = self.GetLineCoverageWithFakeElements([self.covered_tr_html])217 self.assertEqual(line_coverage[0].covered_status,218 emma_coverage_stats.COVERED)219 def testGetLineCoverage_status_statusMissing(self):220 line_coverage = self.GetLineCoverageWithFakeElements(221 [self.not_executable_tr_html])222 self.assertEqual(line_coverage[0].covered_status,223 emma_coverage_stats.NOT_EXECUTABLE)224 def testGetLineCoverage_fractionalCoverage_basic(self):225 line_coverage = self.GetLineCoverageWithFakeElements([self.covered_tr_html])226 self.assertEqual(line_coverage[0].fractional_line_coverage, 1.0)227 def testGetLineCoverage_fractionalCoverage_partial(self):228 line_coverage = self.GetLineCoverageWithFakeElements(229 [self.partially_covered_tr_html])230 self.assertEqual(line_coverage[0].fractional_line_coverage, 0.78)231 def testGetLineCoverage_lineno_basic(self):232 line_coverage = self.GetLineCoverageWithFakeElements([self.covered_tr_html])233 self.assertEqual(line_coverage[0].lineno, 110)234 def testGetLineCoverage_lineno_withAlternativeHtml(self):235 line_coverage = self.GetLineCoverageWithFakeElements(236 [self.tr_with_extra_a_tag])237 self.assertEqual(line_coverage[0].lineno, 54)238 def testGetLineCoverage_source(self):239 self.parser._FindElements = mock.Mock(240 return_value=[ElementTree.fromstring(self.covered_tr_html)])241 line_coverage = self.parser.GetLineCoverage('fake_path')242 self.assertEqual(line_coverage[0].source,243 ' if (mSelectors.get(index) != null) {')244 def testGetLineCoverage_multipleElements(self):245 line_coverage = self.GetLineCoverageWithFakeElements(246 [self.covered_tr_html, self.partially_covered_tr_html,247 self.tr_with_extra_a_tag])248 self.assertEqual(len(line_coverage), 3)249 def GetLineCoverageWithFakeElements(self, html_elements):250 """Wraps GetLineCoverage so mock HTML can easily be used.251 Args:252 html_elements: List of strings each representing an HTML element.253 Returns:254 A list of LineCoverage objects.255 """256 elements = [ElementTree.fromstring(string) for string in html_elements]257 with mock.patch('emma_coverage_stats._EmmaHtmlParser._FindElements',258 return_value=elements):259 return self.parser.GetLineCoverage('fake_path')260class _EmmaCoverageStatsTest(unittest.TestCase):261 """Tests for _EmmaCoverageStats."""262 def setUp(self):263 self.good_source_to_emma = {264 '/path/to/1/File1.java': '/emma/1.html',265 '/path/2/File2.java': '/emma/2.html',266 '/path/2/File3.java': '/emma/3.html'267 }268 self.line_coverage = [269 emma_coverage_stats.LineCoverage(270 1, '', emma_coverage_stats.COVERED, 1.0),271 emma_coverage_stats.LineCoverage(272 2, '', emma_coverage_stats.COVERED, 1.0),273 emma_coverage_stats.LineCoverage(274 3, '', emma_coverage_stats.NOT_EXECUTABLE, 1.0),275 emma_coverage_stats.LineCoverage(276 4, '', emma_coverage_stats.NOT_COVERED, 1.0),277 emma_coverage_stats.LineCoverage(278 5, '', emma_coverage_stats.PARTIALLY_COVERED, 0.85),279 emma_coverage_stats.LineCoverage(280 6, '', emma_coverage_stats.PARTIALLY_COVERED, 0.20)281 ]282 self.lines_for_coverage = [1, 3, 5, 6]283 with mock.patch('emma_coverage_stats._EmmaHtmlParser._FindElements',284 return_value=[]):285 self.simple_coverage = emma_coverage_stats._EmmaCoverageStats(286 'fake_dir', {})287 def testInit(self):288 coverage_stats = self.simple_coverage289 self.assertIsInstance(coverage_stats._emma_parser,290 emma_coverage_stats._EmmaHtmlParser)291 self.assertIsInstance(coverage_stats._source_to_emma, dict)292 def testNeedsCoverage_withExistingJavaFile(self):293 test_file = '/path/to/file/File.java'294 with mock.patch('os.path.exists', return_value=True):295 self.assertTrue(296 emma_coverage_stats._EmmaCoverageStats.NeedsCoverage(test_file))297 def testNeedsCoverage_withNonJavaFile(self):298 test_file = '/path/to/file/File.c'299 with mock.patch('os.path.exists', return_value=True):300 self.assertFalse(301 emma_coverage_stats._EmmaCoverageStats.NeedsCoverage(test_file))302 def testNeedsCoverage_fileDoesNotExist(self):303 test_file = '/path/to/file/File.java'304 with mock.patch('os.path.exists', return_value=False):305 self.assertFalse(306 emma_coverage_stats._EmmaCoverageStats.NeedsCoverage(test_file))307 def testGetPackageNameFromFile_basic(self):308 test_file_text = """// Test Copyright309 package org.chromium.chrome.browser;310 import android.graphics.RectF;"""311 result_package, _ = MockOpenForFunction(312 emma_coverage_stats._EmmaCoverageStats.GetPackageNameFromFile,313 [test_file_text], file_path='/path/to/file/File.java')314 self.assertEqual(result_package, 'org.chromium.chrome.browser.File.java')315 def testGetPackageNameFromFile_noPackageStatement(self):316 result_package, _ = MockOpenForFunction(317 emma_coverage_stats._EmmaCoverageStats.GetPackageNameFromFile,318 ['not a package statement'], file_path='/path/to/file/File.java')319 self.assertIsNone(result_package)320 def testGetSummaryStatsForLines_basic(self):321 covered, total = self.simple_coverage.GetSummaryStatsForLines(322 self.line_coverage)323 self.assertEqual(covered, 3.05)324 self.assertEqual(total, 5)325 def testGetSourceFileToEmmaFileDict(self):326 package_names = {327 '/path/to/1/File1.java': 'org.fake.one.File1.java',328 '/path/2/File2.java': 'org.fake.File2.java',329 '/path/2/File3.java': 'org.fake.File3.java'330 }331 package_to_emma = {332 'org.fake.one.File1.java': '/emma/1.html',333 'org.fake.File2.java': '/emma/2.html',334 'org.fake.File3.java': '/emma/3.html'335 }336 with mock.patch('os.path.exists', return_value=True):337 coverage_stats = self.simple_coverage338 coverage_stats._emma_parser.GetPackageNameToEmmaFileDict = mock.MagicMock(339 return_value=package_to_emma)340 coverage_stats.GetPackageNameFromFile = lambda x: package_names[x]341 result_dict = coverage_stats._GetSourceFileToEmmaFileDict(342 package_names.keys())343 self.assertDictEqual(result_dict, self.good_source_to_emma)344 def testGetCoverageDictForFile(self):345 line_coverage = self.line_coverage346 self.simple_coverage._emma_parser.GetLineCoverage = lambda x: line_coverage347 self.simple_coverage._source_to_emma = {'/fake/src': 'fake/emma'}348 lines = self.lines_for_coverage349 expected_dict = {350 'absolute': {351 'covered': 3.05,352 'total': 5353 },354 'incremental': {355 'covered': 2.05,356 'total': 3357 },358 'source': [359 {360 'line': line_coverage[0].source,361 'coverage': line_coverage[0].covered_status,362 'changed': True,363 'fractional_coverage': line_coverage[0].fractional_line_coverage,364 },365 {366 'line': line_coverage[1].source,367 'coverage': line_coverage[1].covered_status,368 'changed': False,369 'fractional_coverage': line_coverage[1].fractional_line_coverage,370 },371 {372 'line': line_coverage[2].source,373 'coverage': line_coverage[2].covered_status,374 'changed': True,375 'fractional_coverage': line_coverage[2].fractional_line_coverage,376 },377 {378 'line': line_coverage[3].source,379 'coverage': line_coverage[3].covered_status,380 'changed': False,381 'fractional_coverage': line_coverage[3].fractional_line_coverage,382 },383 {384 'line': line_coverage[4].source,385 'coverage': line_coverage[4].covered_status,386 'changed': True,387 'fractional_coverage': line_coverage[4].fractional_line_coverage,388 },389 {390 'line': line_coverage[5].source,391 'coverage': line_coverage[5].covered_status,392 'changed': True,393 'fractional_coverage': line_coverage[5].fractional_line_coverage,394 }395 ]396 }397 result_dict = self.simple_coverage.GetCoverageDictForFile(398 '/fake/src', lines)399 self.assertDictEqual(result_dict, expected_dict)400 def testGetCoverageDictForFile_emptyCoverage(self):401 expected_dict = {402 'absolute': {'covered': 0, 'total': 0},403 'incremental': {'covered': 0, 'total': 0},404 'source': []405 }406 self.simple_coverage._emma_parser.GetLineCoverage = lambda x: []407 self.simple_coverage._source_to_emma = {'fake_dir': 'fake/emma'}408 result_dict = self.simple_coverage.GetCoverageDictForFile('fake_dir', {})409 self.assertDictEqual(result_dict, expected_dict)410 def testGetCoverageDictForFile_missingCoverage(self):411 self.simple_coverage._source_to_emma = {}412 result_dict = self.simple_coverage.GetCoverageDictForFile('fake_file', {})413 self.assertIsNone(result_dict)414 def testGetCoverageDict_basic(self):415 files_for_coverage = {416 '/path/to/1/File1.java': [1, 3, 4],417 '/path/2/File2.java': [1, 2]418 }419 self.simple_coverage._source_to_emma = {420 '/path/to/1/File1.java': 'emma_1',421 '/path/2/File2.java': 'emma_2'422 }423 coverage_info = {424 'emma_1': [425 emma_coverage_stats.LineCoverage(426 1, '', emma_coverage_stats.COVERED, 1.0),427 emma_coverage_stats.LineCoverage(428 2, '', emma_coverage_stats.PARTIALLY_COVERED, 0.5),429 emma_coverage_stats.LineCoverage(430 3, '', emma_coverage_stats.NOT_EXECUTABLE, 1.0),431 emma_coverage_stats.LineCoverage(432 4, '', emma_coverage_stats.COVERED, 1.0)433 ],434 'emma_2': [435 emma_coverage_stats.LineCoverage(436 1, '', emma_coverage_stats.NOT_COVERED, 1.0),437 emma_coverage_stats.LineCoverage(438 2, '', emma_coverage_stats.COVERED, 1.0)439 ]440 }441 expected_dict = {442 'files': {443 '/path/2/File2.java': {444 'absolute': {'covered': 1, 'total': 2},445 'incremental': {'covered': 1, 'total': 2},446 'source': [{'changed': True, 'coverage': 0,447 'line': '', 'fractional_coverage': 1.0},448 {'changed': True, 'coverage': 1,449 'line': '', 'fractional_coverage': 1.0}]450 },451 '/path/to/1/File1.java': {452 'absolute': {'covered': 2.5, 'total': 3},453 'incremental': {'covered': 2, 'total': 2},454 'source': [{'changed': True, 'coverage': 1,455 'line': '', 'fractional_coverage': 1.0},456 {'changed': False, 'coverage': 2,457 'line': '', 'fractional_coverage': 0.5},458 {'changed': True, 'coverage': -1,459 'line': '', 'fractional_coverage': 1.0},460 {'changed': True, 'coverage': 1,461 'line': '', 'fractional_coverage': 1.0}]462 }463 },464 'patch': {'incremental': {'covered': 3, 'total': 4}}465 }466 # Return the relevant coverage info for each file.467 self.simple_coverage._emma_parser.GetLineCoverage = (468 lambda x: coverage_info[x])469 result_dict = self.simple_coverage.GetCoverageDict(files_for_coverage)470 self.assertDictEqual(result_dict, expected_dict)471 def testGetCoverageDict_noCoverage(self):472 result_dict = self.simple_coverage.GetCoverageDict({})473 self.assertDictEqual(result_dict, EMPTY_COVERAGE_STATS_DICT)474class EmmaCoverageStatsGenerateCoverageReport(unittest.TestCase):475 """Tests for GenerateCoverageReport."""476 def testGenerateCoverageReport_missingJsonFile(self):477 with self.assertRaises(IOError):478 with mock.patch('os.path.exists', return_value=False):479 emma_coverage_stats.GenerateCoverageReport('', '', '')480 def testGenerateCoverageReport_invalidJsonFile(self):481 with self.assertRaises(ValueError):482 with mock.patch('os.path.exists', return_value=True):483 MockOpenForFunction(emma_coverage_stats.GenerateCoverageReport, [''],484 line_coverage_file='', out_file_path='',485 coverage_dir='')486def MockOpenForFunction(func, side_effects, **kwargs):487 """Allows easy mock open and read for callables that open multiple files.488 Will mock the python open function in a way such that each time read() is489 called on an open file, the next element in |side_effects| is returned. This490 makes it easier to test functions that call open() multiple times.491 Args:492 func: The callable to invoke once mock files are setup.493 side_effects: A list of return values for each file to return once read.494 Length of list should be equal to the number calls to open in |func|.495 **kwargs: Keyword arguments to be passed to |func|.496 Returns:497 A tuple containing the return value of |func| and the MagicMock object used498 to mock all calls to open respectively.499 """500 mock_open = mock.mock_open()501 mock_open.side_effect = [mock.mock_open(read_data=side_effect).return_value502 for side_effect in side_effects]503 with mock.patch('__builtin__.open', mock_open):504 return func(**kwargs), mock_open505if __name__ == '__main__':506 # Suppress logging messages....
annotation_profiler_for_interval.py
Source:annotation_profiler_for_interval.py
...67 j = k68 else:69 i = k + 170 return i71 def get_coverage( self, start, end ):72 return self.get_coverage_regions_overlap( start, end )[0]73 def get_coverage_regions_overlap( self, start, end ):74 return self.get_coverage_regions_index_overlap( start, end )[0:2]75 def get_coverage_regions_index_overlap( self, start, end ):76 if len( self._coverage ) < 1 or start > self._coverage[-1][1] or end < self._coverage[0][0]:77 return 0, 0, 078 if self._total_coverage and start <= self._coverage[0][0] and end >= self._coverage[-1][1]:79 return self._total_coverage, len( self._coverage ), 080 coverage = 081 region_count = 082 start_index = self.get_start_index( start )83 for i in xrange( start_index, len( self._coverage ) ):84 c_start, c_end = self._coverage[i]85 if c_start > end:86 break87 if c_start <= end and c_end >= start:88 coverage += min( end, c_end ) - max( start, c_start )89 region_count += 190 return coverage, region_count, start_index9192class CachedCoverageReader:93 def __init__( self, base_file_path, buffer = 10, table_names = None, profiler_info = None ):94 self._base_file_path = base_file_path95 self._buffer = buffer #number of chromosomes to keep in memory at a time96 self._coverage = {}97 if table_names is None: table_names = [ table_dir for table_dir in os.listdir( self._base_file_path ) if os.path.isdir( os.path.join( self._base_file_path, table_dir ) ) ]98 for tablename in table_names: self._coverage[tablename] = {}99 if profiler_info is None: profiler_info = {}100 self._profiler_info = profiler_info101 def iter_table_coverage_by_region( self, chrom, start, end ):102 for tablename, coverage, regions in self.iter_table_coverage_regions_by_region( chrom, start, end ):103 yield tablename, coverage104 def iter_table_coverage_regions_by_region( self, chrom, start, end ):105 for tablename, coverage, regions, index in self.iter_table_coverage_regions_index_by_region( chrom, start, end ):106 yield tablename, coverage, regions107 def iter_table_coverage_regions_index_by_region( self, chrom, start, end ):108 for tablename, chromosomes in self._coverage.iteritems():109 if chrom not in chromosomes:110 if len( chromosomes ) >= self._buffer:111 #randomly remove one chromosome from this table112 del chromosomes[ chromosomes.keys().pop( random.randint( 0, self._buffer - 1 ) ) ]113 chromosomes[chrom] = RegionCoverage( os.path.join ( self._base_file_path, tablename, chrom ), self._profiler_info )114 coverage, regions, index = chromosomes[chrom].get_coverage_regions_index_overlap( start, end )115 yield tablename, coverage, regions, index116117class TableCoverageSummary:118 def __init__( self, coverage_reader, chrom_lengths ):119 self.coverage_reader = coverage_reader120 self.chrom_lengths = chrom_lengths121 self.chromosome_coverage = {} #dict of bitset by chromosome holding user's collapsed input intervals122 self.total_interval_size = 0 #total size of user's input intervals123 self.total_interval_count = 0 #total number of user's input intervals124 self.table_coverage = {} #dict of total coverage by user's input intervals by table125 self.table_chromosome_size = {} #dict of dict of table:chrom containing total coverage of table for a chrom126 self.table_chromosome_count = {} #dict of dict of table:chrom containing total number of coverage ranges of table for a chrom127 self.table_regions_overlaped_count = {} #total number of table regions overlaping user's input intervals (non unique)128 self.interval_table_overlap_count = {} #total number of user input intervals which overlap table129 self.region_size_errors = {} #dictionary of lists of invalid ranges by chromosome130 def add_region( self, chrom, start, end ):131 chrom_length = self.chrom_lengths.get( chrom )132 region_start = min( start, chrom_length )133 region_end = min( end, chrom_length )134 region_length = region_end - region_start135 136 if region_length < 1 or region_start != start or region_end != end:137 if chrom not in self.region_size_errors:138 self.region_size_errors[chrom] = []139 self.region_size_errors[chrom].append( ( start, end ) )140 if region_length < 1: return141 142 self.total_interval_size += region_length143 self.total_interval_count += 1144 if chrom not in self.chromosome_coverage:145 self.chromosome_coverage[chrom] = bx.bitset.BitSet( chrom_length )146 147 self.chromosome_coverage[chrom].set_range( region_start, region_length )148 for table_name, coverage, regions in self.coverage_reader.iter_table_coverage_regions_by_region( chrom, region_start, region_end ):149 if table_name not in self.table_coverage:150 self.table_coverage[table_name] = 0151 self.table_chromosome_size[table_name] = {}152 self.table_regions_overlaped_count[table_name] = 0153 self.interval_table_overlap_count[table_name] = 0154 self.table_chromosome_count[table_name] = {}155 if chrom not in self.table_chromosome_size[table_name]:156 self.table_chromosome_size[table_name][chrom] = self.coverage_reader._coverage[table_name][chrom]._total_coverage157 self.table_chromosome_count[table_name][chrom] = len( self.coverage_reader._coverage[table_name][chrom]._coverage )158 self.table_coverage[table_name] += coverage159 if coverage:160 self.interval_table_overlap_count[table_name] += 1161 self.table_regions_overlaped_count[table_name] += regions162 def iter_table_coverage( self ):163 def get_nr_coverage():164 #returns non-redundant coverage, where user's input intervals have been collapse to resolve overlaps165 table_coverage = {} #dictionary of tables containing number of table bases overlaped by nr intervals166 interval_table_overlap_count = {} #dictionary of tables containing number of nr intervals overlaping table167 table_regions_overlap_count = {} #dictionary of tables containing number of regions overlaped (unique)168 interval_count = 0 #total number of nr intervals169 interval_size = 0 #holds total size of nr intervals170 region_start_end = {} #holds absolute start,end for each user input chromosome171 for chrom, chromosome_bitset in self.chromosome_coverage.iteritems():172 #loop through user's collapsed input intervals173 end = 0174 last_end_index = {}175 interval_size += chromosome_bitset.count_range()176 while True:177 if end >= chromosome_bitset.size: break178 start = chromosome_bitset.next_set( end )179 if start >= chromosome_bitset.size: break180 end = chromosome_bitset.next_clear( start )181 interval_count += 1182 if chrom not in region_start_end:183 region_start_end[chrom] = [start, end]184 else:185 region_start_end[chrom][1] = end186 for table_name, coverage, region_count, start_index in self.coverage_reader.iter_table_coverage_regions_index_by_region( chrom, start, end ):187 if table_name not in table_coverage:188 table_coverage[table_name] = 0189 interval_table_overlap_count[table_name] = 0190 table_regions_overlap_count[table_name] = 0191 table_coverage[table_name] += coverage192 if coverage:193 interval_table_overlap_count[table_name] += 1194 table_regions_overlap_count[table_name] += region_count195 if table_name in last_end_index and last_end_index[table_name] == start_index:196 table_regions_overlap_count[table_name] -= 1197 last_end_index[table_name] = start_index + region_count - 1198 table_region_coverage = {} #total coverage for tables by bounding nr interval region199 table_region_count = {} #total number for tables by bounding nr interval region200 for chrom, start_end in region_start_end.items():201 for table_name, coverage, region_count in self.coverage_reader.iter_table_coverage_regions_by_region( chrom, start_end[0], start_end[1] ):202 if table_name not in table_region_coverage:203 table_region_coverage[table_name] = 0204 table_region_count[table_name] = 0205 table_region_coverage[table_name] += coverage206 table_region_count[table_name] += region_count207 return table_region_coverage, table_region_count, interval_count, interval_size, table_coverage, table_regions_overlap_count, interval_table_overlap_count208 table_region_coverage, table_region_count, nr_interval_count, nr_interval_size, nr_table_coverage, nr_table_regions_overlap_count, nr_interval_table_overlap_count = get_nr_coverage()209 for table_name in self.table_coverage:210 #TODO: determine a type of statistic, then calculate and report here211 yield table_name, sum( self.table_chromosome_size.get( table_name, {} ).values() ), sum( self.table_chromosome_count.get( table_name, {} ).values() ), table_region_coverage.get( table_name, 0 ), table_region_count.get( table_name, 0 ), self.total_interval_count, self.total_interval_size, self.table_coverage[table_name], self.table_regions_overlaped_count.get( table_name, 0), self.interval_table_overlap_count.get( table_name, 0 ), nr_interval_count, nr_interval_size, nr_table_coverage[table_name], nr_table_regions_overlap_count.get( table_name, 0 ), nr_interval_table_overlap_count.get( table_name, 0 )212213def profile_per_interval( interval_filename, chrom_col, start_col, end_col, out_filename, keep_empty, coverage_reader ):214 out = open( out_filename, 'wb' )215 for region in bx.intervals.io.NiceReaderWrapper( open( interval_filename, 'rb' ), chrom_col = chrom_col, start_col = start_col, end_col = end_col, fix_strand = True, return_header = False, return_comments = False ):216 for table_name, coverage, region_count in coverage_reader.iter_table_coverage_regions_by_region( region.chrom, region.start, region.end ):217 if keep_empty or coverage:218 #only output regions that have atleast 1 base covered unless empty are requested219 out.write( "%s\t%s\t%s\t%s\n" % ( "\t".join( region.fields ), table_name, coverage, region_count ) )220 out.close()221222def profile_summary( interval_filename, chrom_col, start_col, end_col, out_filename, keep_empty, coverage_reader, chrom_lengths ):223 out = open( out_filename, 'wb' )224 table_coverage_summary = TableCoverageSummary( coverage_reader, chrom_lengths )225 for region in bx.intervals.io.NiceReaderWrapper( open( interval_filename, 'rb' ), chrom_col = chrom_col, start_col = start_col, end_col = end_col, fix_strand = True, return_header = False, return_comments = False ):226 table_coverage_summary.add_region( region.chrom, region.start, region.end )227 228 out.write( "#tableName\ttableChromosomeCoverage\ttableChromosomeCount\ttableRegionCoverage\ttableRegionCount\tallIntervalCount\tallIntervalSize\tallCoverage\tallTableRegionsOverlaped\tallIntervalsOverlapingTable\tnrIntervalCount\tnrIntervalSize\tnrCoverage\tnrTableRegionsOverlaped\tnrIntervalsOverlapingTable\n" )229 for table_name, table_chromosome_size, table_chromosome_count, table_region_coverage, table_region_count, total_interval_count, total_interval_size, total_coverage, table_regions_overlaped_count, interval_region_overlap_count, nr_interval_count, nr_interval_size, nr_coverage, nr_table_regions_overlaped_count, nr_interval_table_overlap_count in table_coverage_summary.iter_table_coverage():230 if keep_empty or total_coverage:231 #only output tables that have atleast 1 base covered unless empty are requested232 out.write( "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" % ( table_name, table_chromosome_size, table_chromosome_count, table_region_coverage, table_region_count, total_interval_count, total_interval_size, total_coverage, table_regions_overlaped_count, interval_region_overlap_count, nr_interval_count, nr_interval_size, nr_coverage, nr_table_regions_overlaped_count, nr_interval_table_overlap_count ) )233 out.close()234 235 #report chrom size errors as needed:236 if table_coverage_summary.region_size_errors:237 print "Regions provided extended beyond known chromosome lengths, and have been truncated as necessary, for the following intervals:"238 for chrom, regions in table_coverage_summary.region_size_errors.items():239 if len( regions ) > 3:240 extra_region_info = ", ... "241 else:242 extra_region_info = ""243 print "%s has max length of %s, exceeded by %s%s." % ( chrom, chrom_lengths.get( chrom ), ", ".join( map( str, regions[:3] ) ), extra_region_info )
...
emma_coverage_stats.py
Source:emma_coverage_stats.py
1#!/usr/bin/python2# Copyright 2015 The Chromium Authors. All rights reserved.3# Use of this source code is governed by a BSD-style license that can be4# found in the LICENSE file.5"""Generates incremental code coverage reports for Java code in Chromium.6Usage:7 build/android/emma_coverage_stats.py -v --out <output file path> --emma-dir8 <EMMA file directory> --lines-for-coverage-file9 <path to file containing lines for coverage>10 Creates a JSON representation of the overall and file coverage stats and saves11 this information to the specified output file.12"""13import argparse14import collections15import json16import logging17import os18import re19import sys20from xml.etree import ElementTree21from devil.utils import run_tests_helper22NOT_EXECUTABLE = -123NOT_COVERED = 024COVERED = 125PARTIALLY_COVERED = 226# Coverage information about a single line of code.27LineCoverage = collections.namedtuple(28 'LineCoverage',29 ['lineno', 'source', 'covered_status', 'fractional_line_coverage'])30class _EmmaHtmlParser(object):31 """Encapsulates HTML file parsing operations.32 This class contains all operations related to parsing HTML files that were33 produced using the EMMA code coverage tool.34 Example HTML:35 Package links:36 <a href="_files/1.html">org.chromium.chrome</a>37 This is returned by the selector |XPATH_SELECT_PACKAGE_ELEMENTS|.38 Class links:39 <a href="1e.html">DoActivity.java</a>40 This is returned by the selector |XPATH_SELECT_CLASS_ELEMENTS|.41 Line coverage data:42 <tr class="p">43 <td class="l" title="78% line coverage (7 out of 9)">108</td>44 <td title="78% line coverage (7 out of 9 instructions)">45 if (index < 0 || index = mSelectors.size()) index = 0;</td>46 </tr>47 <tr>48 <td class="l">109</td>49 <td> </td>50 </tr>51 <tr class="c">52 <td class="l">110</td>53 <td> if (mSelectors.get(index) != null) {</td>54 </tr>55 <tr class="z">56 <td class="l">111</td>57 <td> for (int i = 0; i < mSelectors.size(); i++) {</td>58 </tr>59 Each <tr> element is returned by the selector |XPATH_SELECT_LOC|.60 We can parse this to get:61 1. Line number62 2. Line of source code63 3. Coverage status (c, z, or p)64 4. Fractional coverage value (% out of 100 if PARTIALLY_COVERED)65 """66 # Selector to match all <a> elements within the rows that are in the table67 # that displays all of the different packages.68 _XPATH_SELECT_PACKAGE_ELEMENTS = './/BODY/TABLE[4]/TR/TD/A'69 # Selector to match all <a> elements within the rows that are in the table70 # that displays all of the different classes within a package.71 _XPATH_SELECT_CLASS_ELEMENTS = './/BODY/TABLE[3]/TR/TD/A'72 # Selector to match all <tr> elements within the table containing Java source73 # code in an EMMA HTML file.74 _XPATH_SELECT_LOC = './/BODY/TABLE[4]/TR'75 # Children of HTML elements are represented as a list in ElementTree. These76 # constants represent list indices corresponding to relevant child elements.77 # Child 1 contains percentage covered for a line.78 _ELEMENT_PERCENT_COVERED = 179 # Child 1 contains the original line of source code.80 _ELEMENT_CONTAINING_SOURCE_CODE = 181 # Child 0 contains the line number.82 _ELEMENT_CONTAINING_LINENO = 083 # Maps CSS class names to corresponding coverage constants.84 _CSS_TO_STATUS = {'c': COVERED, 'p': PARTIALLY_COVERED, 'z': NOT_COVERED}85 # UTF-8 no break space.86 _NO_BREAK_SPACE = '\xc2\xa0'87 def __init__(self, emma_file_base_dir):88 """Initializes _EmmaHtmlParser.89 Args:90 emma_file_base_dir: Path to the location where EMMA report files are91 stored. Should be where index.html is stored.92 """93 self._base_dir = emma_file_base_dir94 self._emma_files_path = os.path.join(self._base_dir, '_files')95 self._index_path = os.path.join(self._base_dir, 'index.html')96 def GetLineCoverage(self, emma_file_path):97 """Returns a list of LineCoverage objects for the given EMMA HTML file.98 Args:99 emma_file_path: String representing the path to the EMMA HTML file.100 Returns:101 A list of LineCoverage objects.102 """103 line_tr_elements = self._FindElements(104 emma_file_path, self._XPATH_SELECT_LOC)105 line_coverage = []106 for tr in line_tr_elements:107 # Get the coverage status.108 coverage_status = self._CSS_TO_STATUS.get(tr.get('CLASS'), NOT_EXECUTABLE)109 # Get the fractional coverage value.110 if coverage_status == PARTIALLY_COVERED:111 title_attribute = (tr[self._ELEMENT_PERCENT_COVERED].get('TITLE'))112 # Parse string that contains percent covered: "83% line coverage ...".113 percent_covered = title_attribute.split('%')[0]114 fractional_coverage = int(percent_covered) / 100.0115 else:116 fractional_coverage = 1.0117 # Get the line number.118 lineno_element = tr[self._ELEMENT_CONTAINING_LINENO]119 # Handles oddly formatted HTML (where there is an extra <a> tag).120 lineno = int(lineno_element.text or121 lineno_element[self._ELEMENT_CONTAINING_LINENO].text)122 # Get the original line of Java source code.123 raw_source = tr[self._ELEMENT_CONTAINING_SOURCE_CODE].text124 utf8_source = raw_source.encode('UTF-8')125 source = utf8_source.replace(self._NO_BREAK_SPACE, ' ')126 line = LineCoverage(lineno, source, coverage_status, fractional_coverage)127 line_coverage.append(line)128 return line_coverage129 def GetPackageNameToEmmaFileDict(self):130 """Returns a dict mapping Java packages to EMMA HTML coverage files.131 Parses the EMMA index.html file to get a list of packages, then parses each132 package HTML file to get a list of classes for that package, and creates133 a dict with this info.134 Returns:135 A dict mapping string representation of Java packages (with class136 names appended) to the corresponding file paths of EMMA HTML files.137 """138 # These <a> elements contain each package name and the path of the file139 # where all classes within said package are listed.140 package_link_elements = self._FindElements(141 self._index_path, self._XPATH_SELECT_PACKAGE_ELEMENTS)142 # Maps file path of package directory (EMMA generated) to package name.143 # Example: emma_dir/f.html: org.chromium.chrome.144 package_links = {145 os.path.join(self._base_dir, link.attrib['HREF']): link.text146 for link in package_link_elements if 'HREF' in link.attrib147 }148 package_to_emma = {}149 for package_emma_file_path, package_name in package_links.iteritems():150 # These <a> elements contain each class name in the current package and151 # the path of the file where the coverage info is stored for each class.152 coverage_file_link_elements = self._FindElements(153 package_emma_file_path, self._XPATH_SELECT_CLASS_ELEMENTS)154 for class_name_element in coverage_file_link_elements:155 emma_coverage_file_path = os.path.join(156 self._emma_files_path, class_name_element.attrib['HREF'])157 full_package_name = '%s.%s' % (package_name, class_name_element.text)158 package_to_emma[full_package_name] = emma_coverage_file_path159 return package_to_emma160 # pylint: disable=no-self-use161 def _FindElements(self, file_path, xpath_selector):162 """Reads a HTML file and performs an XPath match.163 Args:164 file_path: String representing the path to the HTML file.165 xpath_selector: String representing xpath search pattern.166 Returns:167 A list of ElementTree.Elements matching the given XPath selector.168 Returns an empty list if there is no match.169 """170 with open(file_path) as f:171 file_contents = f.read().decode('ISO-8859-1').encode('UTF-8')172 root = ElementTree.fromstring(file_contents)173 return root.findall(xpath_selector)174class _EmmaCoverageStats(object):175 """Computes code coverage stats for Java code using the coverage tool EMMA.176 This class provides an API that allows users to capture absolute code coverage177 and code coverage on a subset of lines for each Java source file. Coverage178 reports are generated in JSON format.179 """180 # Regular expression to get package name from Java package statement.181 RE_PACKAGE_MATCH_GROUP = 'package'182 RE_PACKAGE = re.compile(r'package (?P<%s>[\w.]*);' % RE_PACKAGE_MATCH_GROUP)183 def __init__(self, emma_file_base_dir, files_for_coverage):184 """Initialize _EmmaCoverageStats.185 Args:186 emma_file_base_dir: String representing the path to the base directory187 where EMMA HTML coverage files are stored, i.e. parent of index.html.188 files_for_coverage: A list of Java source code file paths to get EMMA189 coverage for.190 """191 self._emma_parser = _EmmaHtmlParser(emma_file_base_dir)192 self._source_to_emma = self._GetSourceFileToEmmaFileDict(files_for_coverage)193 def GetCoverageDict(self, lines_for_coverage):194 """Returns a dict containing detailed coverage information.195 Gets detailed coverage stats for each file specified in the196 |lines_for_coverage| dict and the total incremental number of lines covered197 and executable for all files in |lines_for_coverage|.198 Args:199 lines_for_coverage: A dict mapping Java source file paths to lists of line200 numbers.201 Returns:202 A dict containing coverage stats for the given dict of files and lines.203 Contains absolute coverage stats for each file, coverage stats for each204 file's lines specified in |lines_for_coverage|, line by line coverage205 for each file, and overall coverage stats for the lines specified in206 |lines_for_coverage|.207 """208 file_coverage = {}209 for file_path, line_numbers in lines_for_coverage.iteritems():210 file_coverage_dict = self.GetCoverageDictForFile(file_path, line_numbers)211 if file_coverage_dict:212 file_coverage[file_path] = file_coverage_dict213 else:214 logging.warning(215 'No code coverage data for %s, skipping.', file_path)216 covered_statuses = [s['incremental'] for s in file_coverage.itervalues()]217 num_covered_lines = sum(s['covered'] for s in covered_statuses)218 num_total_lines = sum(s['total'] for s in covered_statuses)219 return {220 'files': file_coverage,221 'patch': {222 'incremental': {223 'covered': num_covered_lines,224 'total': num_total_lines225 }226 }227 }228 def GetCoverageDictForFile(self, file_path, line_numbers):229 """Returns a dict containing detailed coverage info for the given file.230 Args:231 file_path: The path to the Java source file that we want to create the232 coverage dict for.233 line_numbers: A list of integer line numbers to retrieve additional stats234 for.235 Returns:236 A dict containing absolute, incremental, and line by line coverage for237 a file.238 """239 if file_path not in self._source_to_emma:240 return None241 emma_file = self._source_to_emma[file_path]242 total_line_coverage = self._emma_parser.GetLineCoverage(emma_file)243 incremental_line_coverage = [line for line in total_line_coverage244 if line.lineno in line_numbers]245 line_by_line_coverage = [246 {247 'line': line.source,248 'coverage': line.covered_status,249 'changed': line.lineno in line_numbers,250 'fractional_coverage': line.fractional_line_coverage,251 }252 for line in total_line_coverage253 ]254 total_covered_lines, total_lines = (255 self.GetSummaryStatsForLines(total_line_coverage))256 incremental_covered_lines, incremental_total_lines = (257 self.GetSummaryStatsForLines(incremental_line_coverage))258 file_coverage_stats = {259 'absolute': {260 'covered': total_covered_lines,261 'total': total_lines262 },263 'incremental': {264 'covered': incremental_covered_lines,265 'total': incremental_total_lines266 },267 'source': line_by_line_coverage,268 }269 return file_coverage_stats270 # pylint: disable=no-self-use271 def GetSummaryStatsForLines(self, line_coverage):272 """Gets summary stats for a given list of LineCoverage objects.273 Args:274 line_coverage: A list of LineCoverage objects.275 Returns:276 A tuple containing the number of lines that are covered and the total277 number of lines that are executable, respectively278 """279 partially_covered_sum = 0280 covered_status_totals = {COVERED: 0, NOT_COVERED: 0, PARTIALLY_COVERED: 0}281 for line in line_coverage:282 status = line.covered_status283 if status == NOT_EXECUTABLE:284 continue285 covered_status_totals[status] += 1286 if status == PARTIALLY_COVERED:287 partially_covered_sum += line.fractional_line_coverage288 total_covered = covered_status_totals[COVERED] + partially_covered_sum289 total_lines = sum(covered_status_totals.values())290 return total_covered, total_lines291 def _GetSourceFileToEmmaFileDict(self, files):292 """Gets a dict used to correlate Java source files with EMMA HTML files.293 This method gathers the information needed to correlate EMMA HTML294 files with Java source files. EMMA XML and plain text reports do not provide295 line by line coverage data, so HTML reports must be used instead.296 Unfortunately, the HTML files that are created are given garbage names297 (i.e 1.html) so we need to manually correlate EMMA HTML files298 with the original Java source files.299 Args:300 files: A list of file names for which coverage information is desired.301 Returns:302 A dict mapping Java source file paths to EMMA HTML file paths.303 """304 # Maps Java source file paths to package names.305 # Example: /usr/code/file.java -> org.chromium.file.java.306 source_to_package = {}307 for file_path in files:308 package = self.GetPackageNameFromFile(file_path)309 if package:310 source_to_package[file_path] = package311 else:312 logging.warning("Skipping %s because it doesn\'t have a package "313 "statement.", file_path)314 # Maps package names to EMMA report HTML files.315 # Example: org.chromium.file.java -> out/coverage/1a.html.316 package_to_emma = self._emma_parser.GetPackageNameToEmmaFileDict()317 # Finally, we have a dict mapping Java file paths to EMMA report files.318 # Example: /usr/code/file.java -> out/coverage/1a.html.319 source_to_emma = {source: package_to_emma[package]320 for source, package in source_to_package.iteritems()321 if package in package_to_emma}322 return source_to_emma323 @staticmethod324 def NeedsCoverage(file_path):325 """Checks to see if the file needs to be analyzed for code coverage.326 Args:327 file_path: A string representing path to the file.328 Returns:329 True for Java files that exist, False for all others.330 """331 if os.path.splitext(file_path)[1] == '.java' and os.path.exists(file_path):332 return True333 else:334 logging.info('Skipping file %s, cannot compute code coverage.', file_path)335 return False336 @staticmethod337 def GetPackageNameFromFile(file_path):338 """Gets the full package name including the file name for a given file path.339 Args:340 file_path: String representing the path to the Java source file.341 Returns:342 A string representing the full package name with file name appended or343 None if there is no package statement in the file.344 """345 with open(file_path) as f:346 file_content = f.read()347 package_match = re.search(_EmmaCoverageStats.RE_PACKAGE, file_content)348 if package_match:349 package = package_match.group(_EmmaCoverageStats.RE_PACKAGE_MATCH_GROUP)350 file_name = os.path.basename(file_path)351 return '%s.%s' % (package, file_name)352 else:353 return None354def GenerateCoverageReport(line_coverage_file, out_file_path, coverage_dir):355 """Generates a coverage report for a given set of lines.356 Writes the results of the coverage analysis to the file specified by357 |out_file_path|.358 Args:359 line_coverage_file: The path to a file which contains a dict mapping file360 names to lists of line numbers. Example: {file1: [1, 2, 3], ...} means361 that we should compute coverage information on lines 1 - 3 for file1.362 out_file_path: A string representing the location to write the JSON report.363 coverage_dir: A string representing the file path where the EMMA364 HTML coverage files are located (i.e. folder where index.html is located).365 """366 with open(line_coverage_file) as f:367 potential_files_for_coverage = json.load(f)368 files_for_coverage = {f: lines369 for f, lines in potential_files_for_coverage.iteritems()370 if _EmmaCoverageStats.NeedsCoverage(f)}371 coverage_results = {}372 if files_for_coverage:373 code_coverage = _EmmaCoverageStats(coverage_dir, files_for_coverage.keys())374 coverage_results = code_coverage.GetCoverageDict(files_for_coverage)375 else:376 logging.info('No Java files requiring coverage were included in %s.',377 line_coverage_file)378 with open(out_file_path, 'w+') as out_status_file:379 json.dump(coverage_results, out_status_file)380def main():381 argparser = argparse.ArgumentParser()382 argparser.add_argument('--out', required=True, type=str,383 help='Report output file path.')384 argparser.add_argument('--emma-dir', required=True, type=str,385 help='EMMA HTML report directory.')386 argparser.add_argument('--lines-for-coverage-file', required=True, type=str,387 help='File containing a JSON object. Should contain a '388 'dict mapping file names to lists of line numbers of '389 'code for which coverage information is desired.')390 argparser.add_argument('-v', '--verbose', action='count',391 help='Print verbose log information.')392 args = argparser.parse_args()393 run_tests_helper.SetLogLevel(args.verbose)394 GenerateCoverageReport(args.lines_for_coverage_file, args.out, args.emma_dir)395if __name__ == '__main__':...
coverages.py
Source:coverages.py
1from django.http import JsonResponse, HttpResponseNotFound, HttpResponseBadRequest2from rest_framework.views import APIView3from django.utils import timezone4from django.db.models import Q5from common.models.base_party import BaseParty6from common.models import RelatedParty, CreditApplication7from common.models.arrangement import Coverage, CoverageArchived, Facility, FacilityArchived, Collateral, CollateralArchived8from common.serializers.arrangement.coverage import CoveragesSerializer, CoverageCollateralSerializer, CoverageFacilitySerializer9from common.configs.views.arrangement.coverage_list import generate_config as generate_config_coverage_list10from common.configs.views.arrangement.coverage_collateral import generate_config as generate_config_coverage_collateral11from common.configs.views.arrangement.coverage_facility import generate_config as generate_config_coverage_facility12class CoveragesAPIView(APIView):13 # permission_classes = (IsAuthenticated,)14 def get(self, request, **kwargs):15 if 'id' in kwargs.keys():16 base_party = BaseParty.objects.filter(BasePartyId=kwargs['id']).first()17 else:18 base_party = None19 base_party_id = base_party.BasePartyId if base_party is not None else None20 data_view = request.GET.get('data_view', None)21 credit_application_id = request.GET.get('credit_application', None)22 if (data_view is None or credit_application_id is None) or (data_view is not None and credit_application_id is not None and data_view == 1):23 if 'id' in kwargs.keys():24 base_party_ids = [kwargs['id']]25 related_parties = RelatedParty.objects.filter((Q(BaseParty1Id=base_party) | Q(BaseParty2Id=base_party)), (Q(EndDate=None) | Q(EndDate__gte=timezone.now())))26 for party in related_parties:27 if party.BaseParty1Id not in base_party_ids:28 base_party_ids.append(party.BaseParty1Id)29 if party.BaseParty2Id not in base_party_ids:30 base_party_ids.append(party.BaseParty2Id)31 main_coverage = Coverage.objects.filter(Q(FacilityId__in=Facility.objects.filter(BasePartyId_id=kwargs['id'])) | Q(CollateralId__in=Collateral.objects.filter(BasePartyId_id=kwargs['id'])))32 related_coverages = Coverage.objects.filter(Q(FacilityId__in=Facility.objects.filter(BasePartyId_id__in=base_party_ids)) | Q(CollateralId__in=Collateral.objects.filter(BasePartyId_id__in=base_party_ids))).exclude(Q(FacilityId__in=Facility.objects.filter(BasePartyId_id=kwargs['id'])) | Q(CollateralId__in=Collateral.objects.filter(BasePartyId_id=kwargs['id'])))33 response_data = CoveragesSerializer(main_coverage, many=True, model=Coverage).data + CoveragesSerializer(related_coverages, many=True, model=Coverage).data34 else:35 response_data = CoveragesSerializer(Coverage.objects.all(), many=True, model=Coverage).data36 base_party_id = base_party.BasePartyId if base_party is not None else None37 elif data_view is not None and credit_application_id is not None and data_view != 1:38 if data_view == 2 or data_view == 3:39 global coverage_model40 credit_application_query_set = CreditApplication.objects.filter(CreditApplicationId=credit_application_id)41 if not credit_application_query_set.exists():42 return HttpResponseNotFound('Credit Application doesn\'t exist')43 credit_application = credit_application_query_set.first()44 if credit_application.DecisionType is None:45 coverage_model = Coverage46 elif credit_application.DecisionType is not None:47 coverage_model = CoverageArchived48 response_data = CoveragesSerializer(coverage_model.objects.filter(CreditApplicationId=credit_application_id), many=True, model=coverage_model).data49 else:50 response_data = []51 else:52 response_data = []53 response = {54 'data': response_data,55 'config': generate_config_coverage_list(False, base_party_id)56 }57 return JsonResponse(response)58class CoverageAPIView(APIView):59 # permission_classes = (IsAuthenticated,)60 def get(self, request, **kwargs):61 global facility_model62 global collateral_model63 global coverage_model64 bind = kwargs.get('bind')65 model = kwargs.get('model')66 coverage_id = kwargs.get('id')67 if model == 'Coverage':68 facility_model = Facility69 collateral_model = Collateral70 coverage_model = Coverage71 else:72 facility_model = FacilityArchived73 collateral_model = CollateralArchived74 coverage_model = CoverageArchived75 coverage_query_set = coverage_model.objects.filter(CoverageId=coverage_id)76 if not coverage_query_set.exists():77 return JsonResponse({'error': 'Coverage doesn\'t exist'}, status=400)78 coverage = coverage_query_set.first()79 if bind == 'Collateral':80 base_party_id = coverage.CollateralId.BasePartyId_id81 response = {82 'data': CoverageCollateralSerializer(coverage, model=coverage_model).data,83 'config': generate_config_coverage_collateral(False, base_party_id, coverage.CollateralId_id, coverage.CollateralId_id)84 }85 return JsonResponse(response)86 elif bind == 'Facility':87 base_party_id = coverage.FacilityId.BasePartyId_id88 response = {89 'data': CoverageFacilitySerializer(coverage, model=coverage_model).data,90 'config': generate_config_coverage_facility(False, base_party_id, coverage.FacilityId_id, coverage.FacilityId_id)91 }92 return JsonResponse(response)93 def post(self, request, **kwargs):94 global coverage_model95 bind = kwargs.get('bind')96 model = kwargs.get('model')97 coverage_data = request.data.get('coverage', {})98 if model == 'Coverage':99 coverage_model = Coverage100 else:101 coverage_model = CoverageArchived102 coverage = coverage_model()103 coverage.FacilityId_id = coverage_data.get('facilityId', None) if coverage_data.get('facilityId', None) is not None else request.data.get('facilityId')104 coverage.CollateralId_id = coverage_data.get('collateralId', None) if coverage_data.get('collateralId', None) is not None else request.data.get('collateralId')105 coverage.Assignment = coverage_data.get('assignment', None)106 coverage.LienOrder = coverage_data.get('lienOrder', None)107 coverage.BindWith = bind108 coverage.save()109 response = CoveragesSerializer(coverage, model=coverage_model).data110 return JsonResponse(response)111 def put(self, request, **kwargs):112 global coverage_model113 model = kwargs.get('model')114 coverage_id = request.data.get('coverageId', None)115 coverage_data = request.data.get('coverage', {})116 if model == 'Coverage':117 coverage_model = Coverage118 else:119 coverage_model = CoverageArchived120 coverage_query_set = coverage_model.objects.filter(CoverageId=coverage_id)121 if not coverage_query_set.exists():122 return JsonResponse({'error': 'Coverage doesn\'t exist'}, status=400)123 coverage = coverage_query_set.first()124 coverage.FacilityId_id = coverage_data.get('facilityId', None)125 coverage.CollateralId_id = coverage_data.get('collateralId', None)126 coverage.Assignment = coverage_data.get('assignment', None)127 coverage.LienOrder = coverage_data.get('lienOrder', None)128 coverage.save()129 response = CoveragesSerializer(coverage).data130 return JsonResponse(response)131class CoverageGetConfigAPIView(APIView):132 def get(self, request, **kwargs):133 global facility_model134 global collateral_model135 global coverage_model136 bind = kwargs.get('bind')137 model = kwargs.get('model')138 coverage_id = kwargs.get('id')139 if model == 'Coverage':140 facility_model = Facility141 collateral_model = Collateral142 coverage_model = Coverage143 else:144 facility_model = FacilityArchived145 collateral_model = CollateralArchived146 coverage_model = CoverageArchived147 coverage_query_set = coverage_model.objects.filter(CoverageId=coverage_id)148 if not coverage_query_set.exists():149 return JsonResponse({'error': 'Coverage doesn\'t exist'}, status=400)150 coverage = coverage_query_set.first()151 if bind == 'Collateral':152 base_party_id = coverage.CollateralId.BasePartyId_id153 response = {154 'config': generate_config_coverage_collateral(False, base_party_id, coverage.CollateralId_id, coverage.CollateralId_id)155 }156 return JsonResponse(response)157 elif bind == 'Facility':158 base_party_id = coverage.FacilityId.BasePartyId_id159 response = {160 'config': generate_config_coverage_facility(False, base_party_id, coverage.FacilityId_id, coverage.FacilityId_id)161 }162 return JsonResponse(response)163class CoverageArchiveAPIView(APIView):164 def get(self, request, **kwargs):165 global coverage_model166 print('archive')167 model = kwargs.get('model')168 coverage_id = kwargs.get('id')169 if model == 'Coverage':170 coverage_model = Coverage171 else:172 coverage_model = CoverageArchived173 coverage_query_set = coverage_model.objects.filter(CoverageId=coverage_id)174 if not coverage_query_set.exists():175 return JsonResponse({'error': 'Coverage doesn\'t exist'}, status=400)176 coverage = coverage_query_set.first()177 if coverage.CreditApplicationId is None:178 return JsonResponse({'error': 'Coverage hasn\'t credit application'}, status=400)179 coverage_archived = CoverageArchived()180 for field_name in coverage.__dict__:181 setattr(coverage_archived, field_name, getattr(coverage, field_name))182 coverage_archived.CoverageId = None183 coverage_archived.ArchiveStatus = coverage.CreditApplicationId.ApplicationStatus184 if model == 'Coverage':185 coverage_archived.ArchiveVersion = CoverageArchived.objects.filter(ActiveVersion_id=coverage.CoverageId).count() + 1186 coverage_archived.ActiveVersion = coverage187 else:188 coverage_archived.ArchiveVersion = CoverageArchived.objects.filter(ActiveVersion_id=coverage.ActiveVersion.CoverageId).count() + 1189 coverage_archived.ActiveVersion = coverage.ActiveVersion190 coverage_archived.save()...
test_coverage_ext.py
Source:test_coverage_ext.py
...21from nova import test22from nova.tests.api.openstack import fakes23def fake_telnet(self, data):24 return25def fake_check_coverage(self):26 return False27class FakeCoverage(object):28 def __init__(self, data_file=None):29 self.started = False30 return super(FakeCoverage, self).__init__()31 def save(self):32 pass33 def start(self):34 self.started = True35 def stop(self):36 if not self.started:37 raise AssertionError38 self.started = False39 def report(self, file):...
cover.py
Source:cover.py
...38 if not coverage_options:39 return40 if coverage_options.get('data_suffix', False) is False:41 return42 coverage_object = coverage.coverage(**coverage_options)43 coverage_object.start()44 multiprocessing.util.Finalize(45 None,46 multiprocessing_stop,47 args=(coverage_object,),48 exitpriority=100049 )50 if COVERAGE_AVAILABLE:51 multiprocessing.util.register_after_fork(52 multiprocessing_start,53 multiprocessing_start54 )55except ImportError:56 pass57if COVERAGE_AVAILABLE:58 # Cover any processes if the environ variables are present59 coverage.process_startup()60class SaltCoverageTestingParser(SaltTestingParser):61 '''62 Code coverage aware testing option parser63 '''64 def __init__(self, *args, **kwargs):65 if kwargs.pop('html_output_from_env', None) is not None or \66 kwargs.pop('html_output_dir', None) is not None:67 warnings.warn(68 'The unit tests HTML support was removed from {0}. Please '69 'stop passing \'html_output_dir\' or \'html_output_from_env\' '70 'as arguments to {0}'.format(self.__class__.__name__),71 category=DeprecationWarning,72 stacklevel=273 )74 SaltTestingParser.__init__(self, *args, **kwargs)75 self.code_coverage = None76 # Add the coverage related options77 self.output_options_group.add_option(78 '--coverage',79 default=False,80 action='store_true',81 help='Run tests and report code coverage'82 )83 self.output_options_group.add_option(84 '--no-processes-coverage',85 default=False,86 action='store_true',87 help='Do not track subprocess and/or multiprocessing processes'88 )89 self.output_options_group.add_option(90 '--coverage-xml',91 default=None,92 help='If provided, the path to where a XML report of the code '93 'coverage will be written to'94 )95 self.output_options_group.add_option(96 '--coverage-html',97 default=None,98 help=('The directory where the generated HTML coverage report '99 'will be saved to. The directory, if existing, will be '100 'deleted before the report is generated.')101 )102 def _validate_options(self):103 if (self.options.coverage_xml or self.options.coverage_html) and \104 not self.options.coverage:105 self.options.coverage = True106 if self.options.coverage is True and COVERAGE_AVAILABLE is False:107 self.error(108 'Cannot run tests with coverage report. '109 'Please install coverage>=3.5.3'110 )111 if self.options.coverage is True:112 coverage_version = tuple([113 int(part) for part in re.search(114 r'([0-9.]+)', coverage.__version__).group(0).split('.')115 ])116 if coverage_version < (3, 5, 3):117 # Should we just print the error instead of exiting?118 self.error(119 'Versions lower than 3.5.3 of the coverage library are '120 'know to produce incorrect results. Please consider '121 'upgrading...'122 )123 SaltTestingParser._validate_options(self)124 def pre_execution_cleanup(self):125 if self.options.coverage_html is not None:126 if os.path.isdir(self.options.coverage_html):127 shutil.rmtree(self.options.coverage_html)128 if self.options.coverage_xml is not None:129 if os.path.isfile(self.options.coverage_xml):130 os.unlink(self.options.coverage_xml)131 SaltTestingParser.pre_execution_cleanup(self)132 def start_coverage(self, **coverage_options):133 '''134 Start code coverage.135 You can pass any coverage options as keyword arguments. For the136 available options please see:137 http://nedbatchelder.com/code/coverage/api.html138 '''139 if self.options.coverage is False:140 return141 if coverage_options.pop('track_processes', None) is not None:142 raise RuntimeWarning(143 'Please stop passing \'track_processes\' to '144 '\'start_coverage()\'. It\'s now the default and '145 '\'--no-processes-coverage\' was added to the parser to '146 'disable it.'147 )148 print(' * Starting Coverage')149 if self.options.no_processes_coverage is False:150 # Update environ so that any subprocess started on tests are also151 # included in the report152 coverage_options['data_suffix'] = True153 os.environ['COVERAGE_PROCESS_START'] = ''154 os.environ['COVERAGE_OPTIONS'] = json.dumps(coverage_options)155 # Setup coverage156 self.code_coverage = coverage.coverage(**coverage_options)157 self.code_coverage.start()158 def stop_coverage(self, save_coverage=True):159 '''160 Stop code coverage.161 '''162 if self.options.coverage is False:163 return164 # Clean up environment165 os.environ.pop('COVERAGE_OPTIONS', None)166 os.environ.pop('COVERAGE_PROCESS_START', None)167 print(' * Stopping coverage')168 self.code_coverage.stop()169 if save_coverage:170 print(' * Saving coverage info')171 self.code_coverage.save()172 if self.options.no_processes_coverage is False:173 # Combine any multiprocessing coverage data files174 sys.stdout.write(' * Combining multiple coverage info files ... ')175 sys.stdout.flush()176 self.code_coverage.combine()177 print('Done.')178 if self.options.coverage_xml is not None:179 sys.stdout.write(180 ' * Generating Coverage XML Report At {0!r} ... '.format(181 self.options.coverage_xml182 )183 )184 sys.stdout.flush()185 self.code_coverage.xml_report(186 outfile=self.options.coverage_xml187 )188 print('Done.')189 if self.options.coverage_html is not None:190 sys.stdout.write(191 ' * Generating Coverage HTML Report Under {0!r} ... '.format(192 self.options.coverage_html193 )194 )195 sys.stdout.flush()196 self.code_coverage.html_report(197 directory=self.options.coverage_html198 )199 print('Done.')200 def finalize(self, exit_code=0):201 if self.options.coverage is True:202 self.stop_coverage(save_coverage=True)...
test_coverage_plugin.py
Source:test_coverage_plugin.py
1"""Test the coverage plugin."""2import os3import sys4import unittest5import shutil6from nose.exc import SkipTest7from nose.plugins import PluginTester8from nose.plugins.cover import Coverage9support = os.path.join(os.path.dirname(__file__), 'support')10try:11 import coverage12 # Python 3.3 may accidentally pick up our support area when running the unit13 # tests. Look for the coverage attribute to make sure we've got the right14 # package.15 hasCoverage = hasattr(coverage, 'coverage')16except ImportError:17 hasCoverage = False18class TestCoveragePlugin(PluginTester, unittest.TestCase):19 activate = "--with-coverage"20 args = ['-v', '--cover-package=blah', '--cover-html', '--cover-min-percentage', '25']21 plugins = [Coverage()]22 suitepath = os.path.join(support, 'coverage')23 def setUp(self):24 if not hasCoverage:25 raise SkipTest('coverage not available; skipping')26 self.cover_file = os.path.join(os.getcwd(), '.coverage')27 self.cover_html_dir = os.path.join(os.getcwd(), 'cover')28 if os.path.exists(self.cover_file):29 os.unlink(self.cover_file)30 if os.path.exists(self.cover_html_dir):31 shutil.rmtree(self.cover_html_dir)32 super(TestCoveragePlugin, self).setUp()33 def runTest(self):34 self.assertTrue("blah 4 3 25% 1" in self.output)35 self.assertTrue("Ran 1 test in" in self.output)36 # Assert coverage html report exists37 self.assertTrue(os.path.exists(os.path.join(self.cover_html_dir,38 'index.html')))39 # Assert coverage data is saved40 self.assertTrue(os.path.exists(self.cover_file))41class TestCoverageMinPercentagePlugin(PluginTester, unittest.TestCase):42 activate = "--with-coverage"43 args = ['-v', '--cover-package=blah', '--cover-min-percentage', '100']44 plugins = [Coverage()]45 suitepath = os.path.join(support, 'coverage')46 def setUp(self):47 if not hasCoverage:48 raise SkipTest('coverage not available; skipping')49 self.cover_file = os.path.join(os.getcwd(), '.coverage')50 self.cover_html_dir = os.path.join(os.getcwd(), 'cover')51 if os.path.exists(self.cover_file):52 os.unlink(self.cover_file)53 if os.path.exists(self.cover_html_dir):54 shutil.rmtree(self.cover_html_dir)55 self.assertRaises(SystemExit,56 super(TestCoverageMinPercentagePlugin, self).setUp)57 def runTest(self):58 pass59class TestCoverageMinPercentageSinglePackagePlugin(60 PluginTester, unittest.TestCase):61 activate = "--with-coverage"62 args = ['-v', '--cover-package=blah', '--cover-html',63 '--cover-min-percentage', '100']64 plugins = [Coverage()]65 suitepath = os.path.join(support, 'coverage')66 def setUp(self):67 if not hasCoverage:68 raise SkipTest('coverage not available; skipping')69 self.cover_file = os.path.join(os.getcwd(), '.coverage')70 self.cover_html_dir = os.path.join(os.getcwd(), 'cover')71 if os.path.exists(self.cover_file):72 os.unlink(self.cover_file)73 if os.path.exists(self.cover_html_dir):74 shutil.rmtree(self.cover_html_dir)75 self.assertRaises(SystemExit,76 super(TestCoverageMinPercentageSinglePackagePlugin,77 self).setUp)78 def runTest(self):79 pass80class TestCoverageMinPercentageSinglePackageWithBranchesPlugin(81 PluginTester, unittest.TestCase):82 activate = "--with-coverage"83 args = ['-v', '--cover-package=blah', '--cover-branches',84 '--cover-html', '--cover-min-percentage', '100']85 plugins = [Coverage()]86 suitepath = os.path.join(support, 'coverage')87 def setUp(self):88 if not hasCoverage:89 raise SkipTest('coverage not available; skipping')90 self.cover_file = os.path.join(os.getcwd(), '.coverage')91 self.cover_html_dir = os.path.join(os.getcwd(), 'cover')92 if os.path.exists(self.cover_file):93 os.unlink(self.cover_file)94 if os.path.exists(self.cover_html_dir):95 shutil.rmtree(self.cover_html_dir)96 self.assertRaises(97 SystemExit,98 super(TestCoverageMinPercentageSinglePackageWithBranchesPlugin,99 self).setUp)100 def runTest(self):101 pass102class TestCoverageMinPercentageTOTALPlugin(PluginTester, unittest.TestCase):103 activate = "--with-coverage"104 args = ['-v', '--cover-package=blah', '--cover-package=moo',105 '--cover-min-percentage', '100']106 plugins = [Coverage()]107 suitepath = os.path.join(support, 'coverage2')108 def setUp(self):109 if not hasCoverage:110 raise SkipTest('coverage not available; skipping')111 self.cover_file = os.path.join(os.getcwd(), '.coverage')112 self.cover_html_dir = os.path.join(os.getcwd(), 'cover')113 if os.path.exists(self.cover_file):114 os.unlink(self.cover_file)115 if os.path.exists(self.cover_html_dir):116 shutil.rmtree(self.cover_html_dir)117 self.assertRaises(SystemExit,118 super(TestCoverageMinPercentageTOTALPlugin, self).setUp)119 def runTest(self):120 pass121class TestCoverageMinPercentageWithBranchesTOTALPlugin(122 PluginTester, unittest.TestCase):123 activate = "--with-coverage"124 args = ['-v', '--cover-package=blah', '--cover-package=moo',125 '--cover-branches', '--cover-min-percentage', '100']126 plugins = [Coverage()]127 suitepath = os.path.join(support, 'coverage2')128 def setUp(self):129 if not hasCoverage:130 raise SkipTest('coverage not available; skipping')131 self.cover_file = os.path.join(os.getcwd(), '.coverage')132 self.cover_html_dir = os.path.join(os.getcwd(), 'cover')133 if os.path.exists(self.cover_file):134 os.unlink(self.cover_file)135 if os.path.exists(self.cover_html_dir):136 shutil.rmtree(self.cover_html_dir)137 self.assertRaises(138 SystemExit,139 super(TestCoverageMinPercentageWithBranchesTOTALPlugin, self).setUp)140 def runTest(self):141 pass142if __name__ == '__main__':...
pydev_runfiles_coverage.py
Source:pydev_runfiles_coverage.py
...57 n += 1 #Add 1 more for the current process (which will do the initial import).58 coverage_files = get_coverage_files(coverage_output_dir, n)59 os.environ['COVERAGE_FILE'] = coverage_files.pop(0)60 61 coverage_instance = coverage.coverage(source=[coverage_include])62 coverage_instance.start()63 64 elif coverage_output_file:65 #Client of parallel run.66 os.environ['COVERAGE_FILE'] = coverage_output_file67 coverage_instance = coverage.coverage(source=[coverage_include])68 coverage_instance.start()69 ...
Using AI Code Generation
1const Navalia = require('navalia');2const navalia = new Navalia();3 .then(() => navalia.coverage.startJSCoverage())4 .then(() => navalia.coverage.stopJSCoverage())5 .then((coverage) => console.log(coverage))6 .then(() => navalia.close())7 .catch((err) => console.error(err));8{9 {10 {11 }12 },13 {14 {15 }16 }17}18const Navalia = require('navalia
Using AI Code Generation
1const Navalia = require('navalia');2const navalia = new Navalia();3 .use(require('navalia-plugin-istanbul'))4 .coverage()5 .then((coverage) => {6 console.log(coverage);7 });8### .coverage()9### .coverage(options)10MIT © [Sam Verschueren](
Using AI Code Generation
1var navalia = require('navalia');2var browser = new navalia();3var puppeteer = require('puppeteer');4var browser = await puppeteer.launch();5var chromeless = require('chromeless');6var browser = chromeless();7var Nightmare = require('nightmare');8var browser = Nightmare();9var phantomjs = require('phantomjs');10var browser = phantomjs();11var casperjs = require('casperjs');12var browser = casperjs();13var slimerjs = require('slimerjs');14var browser = slimerjs();15var poltergeist = require('poltergeist');16var browser = poltergeist();17var selenium = require('selenium');18var browser = selenium();19var webdriverio = require('webdriverio');20var browser = webdriverio();21var webkit = require('webkit');22var browser = webkit();23var jsdom = require('jsdom');24var browser = jsdom();25var zombie = require('zombie');26var browser = zombie();27var cheerio = require('cheerio');28var browser = cheerio();29var axios = require('axios');30var browser = axios();31var request = require('request');32var browser = request();33var superagent = require('superagent');34var browser = superagent();35var node-fetch = require('node-fetch');36var browser = node-fetch();37var xmlhttprequest = require('xmlhttprequest');38var browser = xmlhttprequest();39var xmlhttprequest2 = require('xmlhttprequest2');40var browser = xmlhttprequest2();
Using AI Code Generation
1const navalia = require('navalia');2const assert = require('assert');3const path = require('path');4const fs = require('fs');5const { JSDOM } = require('jsdom');6const test = async () => {7 const browser = await navalia('chrome');8 await browser.coverage.startCSSCoverage();9 await browser.coverage.startJSCoverage();10 await browser.coverage.startHTMLCoverage();11 await browser.coverage.startBlockCoverage();12 const cssCoverage = await browser.coverage.stopCSSCoverage();13 const jsCoverage = await browser.coverage.stopJSCoverage();14 const htmlCoverage = await browser.coverage.stopHTMLCoverage();15 const blockCoverage = await browser.coverage.stopBlockCoverage();16 console.log(cssCoverage);17 console.log(jsCoverage);18 console.log(htmlCoverage);19 console.log(blockCoverage);20 await browser.close();21};22test();23body {24 background-color: lightblue;25}26h1 {27 color: navy;28 margin-left: 20px;29}30function myFunction(p1, p2) {31}32function myFunction(p1, p2) {33}34function myFunction(p1, p2) {35}36function myFunction(p1, p2) {37}38function myFunction(p1, p2) {39}
Using AI Code Generation
1var Navalia = require('navalia');2var navalia = new Navalia();3 .type('input[name="q"]', 'navalia')4 .click('input[name="btnG"]')5 .wait('#resultStats')6 .screenshot('google.png')7 .run(function(err) {8 if (err) {9 throw err;10 }11 });12### Navalia([options])13Create a new instance of Navalia. Options are passed to [phantomjs-node](
Using AI Code Generation
1var navalia = require('navalia');2var browser = new navalia('phantomjs');3var assert = require('assert');4var fs = require('fs');5 fs.writeFileSync('coverage.json', JSON.stringify(coverage));6 })7 .then(function(){8 browser.close();9 });10### new navalia([browserName])11### browser.open([options])12### browser.close()13### browser.visit(url)14### browser.evaluate(fn)15### browser.inject(fn)16### browser.injectAndEvaluate(fn)17### browser.click(selector)18### browser.fill(selector, value)19### browser.select(selector, value)20### browser.upload(selector, filePath)21### browser.wait(ms)22### browser.waitFor(fn)23### browser.waitForSelector(selector)24### browser.waitForText(selector, text)25### browser.waitForUrl(url)26### browser.waitForNavigation()
Using AI Code Generation
1const Navalia = require('navalia');2const chrome = new Navalia('chrome');3const fs = require('fs');4const path = require('path');5chrome.on('error', console.error);6 .waitForNetworkIdle()7 .coverage()8 .then((coverage) => {9 fs.writeFileSync(path.join(__dirname, 'coverage.json'), JSON.stringify(coverage));10 console.log('coverage', coverage);11 })12 .then(() => chrome.close())13 .catch((err) => {14 console.error(err);15 chrome.close();16 });17### new Navalia(browser, [options])18### .close()19### .goto(url)20### .waitForNetworkIdle()21### .waitForSelector(selector)22### .evaluate(fn, ...args)23### .evaluateOnNewDocument(fn, ...args)
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!