Best Python code snippet using molecule_python
lofi.py
Source:lofi.py  
1# Copyright 2017 The Chromium Authors. All rights reserved.2# Use of this source code is governed by a BSD-style license that can be3# found in the LICENSE file.4import common5from common import TestDriver6from common import IntegrationTest7from decorators import ChromeVersionBeforeM8from decorators import ChromeVersionEqualOrAfterM9class LoFi(IntegrationTest):10  #  Checks that the compressed image is below a certain threshold.11  #  The test page is uncacheable otherwise a cached page may be served that12  #  doesn't have the correct via headers.13  @ChromeVersionBeforeM(65)14  def testLoFiOldFlags(self):15    with TestDriver() as test_driver:16      test_driver.AddChromeArg('--enable-spdy-proxy-auth')17      test_driver.AddChromeArg('--enable-features='18                               'Previews,DataReductionProxyDecidesTransform')19      test_driver.AddChromeArg('--data-reduction-proxy-lo-fi=always-on')20      # Disable server experiments such as tamper detection.21      test_driver.AddChromeArg('--data-reduction-proxy-server-experiments-'22                               'disabled')23      test_driver.LoadURL('http://check.googlezip.net/static/index.html')24      lofi_responses = 025      for response in test_driver.GetHTTPResponses():26        if not response.url.endswith('png'):27          continue28        if not response.request_headers:29          continue30        if (self.checkLoFiResponse(response, True)):31          lofi_responses = lofi_responses + 132      # Verify that Lo-Fi responses were seen.33      self.assertNotEqual(0, lofi_responses)34      # Verify Lo-Fi previews info bar recorded35      histogram = test_driver.GetHistogram('Previews.InfoBarAction.LoFi', 5)36      self.assertEqual(1, histogram['count'])37  # Checks that LoFi images are served when LoFi slow connections are used and38  # the network quality estimator returns Slow2G.39  @ChromeVersionBeforeM(65)40  def testLoFiSlowConnectionOldFlags(self):41    with TestDriver() as test_driver:42      test_driver.AddChromeArg('--enable-spdy-proxy-auth')43      test_driver.AddChromeArg('--enable-features='44                               'Previews,DataReductionProxyDecidesTransform')45      test_driver.AddChromeArg('--data-reduction-proxy-lo-fi=slow-connections-'46                               'only')47      # Disable server experiments such as tamper detection.48      test_driver.AddChromeArg('--data-reduction-proxy-server-experiments-'49                               'disabled')50      test_driver.AddChromeArg('--force-fieldtrial-params='51                               'NetworkQualityEstimator.Enabled:'52                               'force_effective_connection_type/Slow2G')53      test_driver.AddChromeArg('--force-fieldtrials=NetworkQualityEstimator/'54                               'Enabled')55      test_driver.LoadURL('http://check.googlezip.net/static/index.html')56      lofi_responses = 057      for response in test_driver.GetHTTPResponses():58        if not response.url.endswith('png'):59          continue60        if not response.request_headers:61          continue62        if (self.checkLoFiResponse(response, True)):63          lofi_responses = lofi_responses + 164      # Verify that Lo-Fi responses were seen.65      self.assertNotEqual(0, lofi_responses)66      # Verify Lo-Fi previews info bar recorded67      histogram = test_driver.GetHistogram('Previews.InfoBarAction.LoFi', 5)68      self.assertEqual(1, histogram['count'])69  # Checks that LoFi images are served when LoFi slow connections are used and70  # the network quality estimator returns Slow2G.71  @ChromeVersionEqualOrAfterM(65)72  def testLoFiOnSlowConnection(self):73    with TestDriver() as test_driver:74      test_driver.AddChromeArg('--enable-spdy-proxy-auth')75      test_driver.AddChromeArg('--enable-features='76                               'Previews,DataReductionProxyDecidesTransform')77      # Disable server experiments such as tamper detection.78      test_driver.AddChromeArg('--data-reduction-proxy-server-experiments-'79                               'disabled')80      test_driver.AddChromeArg('--force-fieldtrial-params='81                               'NetworkQualityEstimator.Enabled:'82                               'force_effective_connection_type/Slow2G')83      test_driver.AddChromeArg('--force-fieldtrials=NetworkQualityEstimator/'84                               'Enabled')85      test_driver.LoadURL('http://check.googlezip.net/static/index.html')86      lofi_responses = 087      for response in test_driver.GetHTTPResponses():88        if not response.url.endswith('png'):89          continue90        if not response.request_headers:91          continue92        if (self.checkLoFiResponse(response, True)):93          lofi_responses = lofi_responses + 194      # Verify that Lo-Fi responses were seen.95      self.assertNotEqual(0, lofi_responses)96      # Verify Lo-Fi previews info bar recorded97      histogram = test_driver.GetHistogram('Previews.InfoBarAction.LoFi', 5)98      self.assertEqual(1, histogram['count'])99  # Checks that LoFi images are NOT served when the network quality estimator100  # returns fast connection type.101  @ChromeVersionBeforeM(65)102  def testLoFiFastConnectionOldFlags(self):103    with TestDriver() as test_driver:104      test_driver.AddChromeArg('--enable-spdy-proxy-auth')105      test_driver.AddChromeArg('--enable-features='106                               'Previews,DataReductionProxyDecidesTransform')107      test_driver.AddChromeArg('--data-reduction-proxy-lo-fi=slow-connections-'108                               'only')109      # Disable server experiments such as tamper detection.110      test_driver.AddChromeArg('--data-reduction-proxy-server-experiments-'111                               'disabled')112      test_driver.AddChromeArg('--force-fieldtrial-params='113                               'NetworkQualityEstimator.Enabled:'114                               'force_effective_connection_type/4G')115      test_driver.AddChromeArg('--force-fieldtrials=NetworkQualityEstimator/'116                               'Enabled')117      test_driver.LoadURL('http://check.googlezip.net/static/index.html')118      lofi_responses = 0119      for response in test_driver.GetHTTPResponses():120        if response.url.endswith('html'):121          # Main resource should accept transforms but not be transformed.122          self.assertEqual('lite-page',123            response.request_headers['chrome-proxy-accept-transform'])124          self.assertNotIn('chrome-proxy-content-transform',125            response.response_headers)126          if 'chrome-proxy' in response.response_headers:127            self.assertNotIn('page-policies',128                             response.response_headers['chrome-proxy'])129        else:130          # No subresources should accept transforms.131          self.assertNotIn('chrome-proxy-accept-transform',132            response.request_headers)133      # Verify no Lo-Fi previews info bar recorded134      histogram = test_driver.GetHistogram('Previews.InfoBarAction.LoFi', 5)135      self.assertEqual(histogram, {})136  # Checks that LoFi images are NOT served when the network quality estimator137  # returns fast connection.138  @ChromeVersionEqualOrAfterM(65)139  def testLoFiFastConnection(self):140    with TestDriver() as test_driver:141      test_driver.AddChromeArg('--enable-spdy-proxy-auth')142      test_driver.AddChromeArg('--enable-features='143                               'Previews,DataReductionProxyDecidesTransform')144      # Disable server experiments such as tamper detection.145      test_driver.AddChromeArg('--data-reduction-proxy-server-experiments-'146                               'disabled')147      test_driver.AddChromeArg('--force-fieldtrial-params='148                               'NetworkQualityEstimator.Enabled:'149                               'force_effective_connection_type/4G')150      test_driver.AddChromeArg('--force-fieldtrials=NetworkQualityEstimator/'151                               'Enabled')152      test_driver.LoadURL('http://check.googlezip.net/static/index.html')153      lofi_responses = 0154      for response in test_driver.GetHTTPResponses():155        if response.url.endswith('html'):156          # Main resource should accept transforms but not be transformed.157          self.assertEqual('lite-page',158            response.request_headers['chrome-proxy-accept-transform'])159          self.assertNotIn('chrome-proxy-content-transform',160            response.response_headers)161          if 'chrome-proxy' in response.response_headers:162            self.assertNotIn('page-policies',163                             response.response_headers['chrome-proxy'])164        else:165          # No subresources should accept transforms.166          self.assertNotIn('chrome-proxy-accept-transform',167            response.request_headers)168      # Verify no Lo-Fi previews info bar recorded169      histogram = test_driver.GetHistogram('Previews.InfoBarAction.LoFi', 5)170      self.assertEqual(histogram, {})171  # Checks that LoFi images are not served, but the if-heavy CPAT header is172  # added when LoFi slow connections are used and the network quality estimator173  # returns 4G.174  # If-heavy stopped being added in M61.175  @ChromeVersionBeforeM(61)176  def testLoFiIfHeavyFastConnection(self):177    with TestDriver() as test_driver:178      test_driver.AddChromeArg('--enable-spdy-proxy-auth')179      test_driver.AddChromeArg('--data-reduction-proxy-lo-fi=slow-connections-'180                               'only')181      # Disable server experiments.182      test_driver.AddChromeArg('--data-reduction-proxy-server-experiments-'183                               'disabled')184      test_driver.AddChromeArg('--force-fieldtrial-params='185                               'NetworkQualityEstimator.Enabled:'186                               'force_effective_connection_type/4G')187      test_driver.AddChromeArg('--force-fieldtrials=NetworkQualityEstimator/'188                               'Enabled')189      test_driver.LoadURL('http://check.googlezip.net/static/index.html')190      non_lofi_responses = 0191      for response in test_driver.GetHTTPResponses():192        if not response.url.endswith('png'):193          continue194        if not response.request_headers:195          continue196        self.assertIn('chrome-proxy-accept-transform', response.request_headers)197        actual_cpat_headers = \198          response.request_headers['chrome-proxy-accept-transform'].split(';')199        self.assertIn('empty-image', actual_cpat_headers)200        self.assertIn('if-heavy', actual_cpat_headers)201        if (not self.checkLoFiResponse(response, False)):202          non_lofi_responses = non_lofi_responses + 1203      # Verify that non Lo-Fi image responses were seen.204      self.assertNotEqual(0, non_lofi_responses)205  # Checks that Lo-Fi placeholder images are not loaded from cache on page206  # reloads when Lo-Fi mode is disabled or data reduction proxy is disabled.207  # First a test page is opened with Lo-Fi and chrome proxy enabled. This allows208  # Chrome to cache the Lo-Fi placeholder image. The browser is restarted with209  # chrome proxy disabled and the same test page is loaded. This second page210  # load should not pick the Lo-Fi placeholder from cache and original image211  # should be loaded. Finally, the browser is restarted with chrome proxy212  # enabled and Lo-Fi disabled and the same test page is loaded. This third page213  # load should not pick the Lo-Fi placeholder from cache and original image214  # should be loaded.215  @ChromeVersionBeforeM(65)216  def testLoFiCacheBypassOldFlags(self):217    # If it was attempted to run with another experiment, skip this test.218    if common.ParseFlags().browser_args and ('--data-reduction-proxy-experiment'219        in common.ParseFlags().browser_args):220      self.skipTest('This test cannot be run with other experiments.')221    with TestDriver() as test_driver:222      # First page load, enable Lo-Fi and chrome proxy. Disable server223      # experiments such as tamper detection. This test should be run with224      # --profile-type=default command line for the same user profile and cache225      # to be used across the two page loads.226      test_driver.AddChromeArg('--enable-spdy-proxy-auth')227      test_driver.AddChromeArg('--enable-features='228                               'Previews,DataReductionProxyDecidesTransform')229      test_driver.AddChromeArg('--data-reduction-proxy-lo-fi=always-on')230      test_driver.AddChromeArg('--profile-type=default')231      test_driver.AddChromeArg('--data-reduction-proxy-server-experiments-'232                               'disabled')233      test_driver.LoadURL('http://check.googlezip.net/cacheable/test.html')234      lofi_responses = 0235      for response in test_driver.GetHTTPResponses():236        if not response.url.endswith('png'):237          continue238        if not response.request_headers:239          continue240        if (self.checkLoFiResponse(response, True)):241          lofi_responses = lofi_responses + 1242      # Verify that Lo-Fi responses were seen.243      self.assertNotEqual(0, lofi_responses)244      # Second page load with the chrome proxy off.245      test_driver._StopDriver()246      test_driver.RemoveChromeArg('--enable-spdy-proxy-auth')247      test_driver.LoadURL('http://check.googlezip.net/cacheable/test.html')248      responses = 0249      for response in test_driver.GetHTTPResponses():250        if not response.url.endswith('png'):251          continue252        if not response.request_headers:253          continue254        responses = responses + 1255        self.assertNotHasChromeProxyViaHeader(response)256        self.checkLoFiResponse(response, False)257      # Verify that responses were seen.258      self.assertNotEqual(0, responses)259      # Third page load with the chrome proxy on and Lo-Fi off.260      test_driver._StopDriver()261      test_driver.AddChromeArg('--enable-spdy-proxy-auth')262      test_driver.RemoveChromeArg('--data-reduction-proxy-lo-fi=always-on')263      test_driver.AddChromeArg('--data-reduction-proxy-lo-fi=disabled')264      test_driver.LoadURL('http://check.googlezip.net/cacheable/test.html')265      responses = 0266      for response in test_driver.GetHTTPResponses():267        if not response.url.endswith('png'):268          continue269        if not response.request_headers:270          continue271        responses = responses + 1272        self.assertHasChromeProxyViaHeader(response)273        self.checkLoFiResponse(response, False)274      # Verify that responses were seen.275      self.assertNotEqual(0, responses)276  # Checks that Lo-Fi placeholder images are not loaded from cache on page277  # reloads when Lo-Fi mode is disabled or data reduction proxy is disabled.278  # First a test page is opened with Lo-Fi and chrome proxy enabled. This allows279  # Chrome to cache the Lo-Fi placeholder image. The browser is restarted with280  # chrome proxy disabled and the same test page is loaded. This second page281  # load should not pick the Lo-Fi placeholder from cache and original image282  # should be loaded. Finally, the browser is restarted with chrome proxy283  # enabled and Lo-Fi disabled and the same test page is loaded. This third page284  # load should not pick the Lo-Fi placeholder from cache and original image285  # should be loaded.286  @ChromeVersionEqualOrAfterM(65)287  def testLoFiCacheBypass(self):288    # If it was attempted to run with another experiment, skip this test.289    if common.ParseFlags().browser_args and ('--data-reduction-proxy-experiment'290        in common.ParseFlags().browser_args):291      self.skipTest('This test cannot be run with other experiments.')292    with TestDriver() as test_driver:293      # First page load, enable Lo-Fi and chrome proxy. Disable server294      # experiments such as tamper detection. This test should be run with295      # --profile-type=default command line for the same user profile and cache296      # to be used across the two page loads.297      test_driver.AddChromeArg('--enable-spdy-proxy-auth')298      test_driver.AddChromeArg('--enable-features='299                               'Previews,DataReductionProxyDecidesTransform')300      test_driver.AddChromeArg('--profile-type=default')301      test_driver.AddChromeArg('--data-reduction-proxy-server-experiments-'302                               'disabled')303      test_driver.AddChromeArg('--force-fieldtrial-params='304                               'NetworkQualityEstimator.Enabled:'305                               'force_effective_connection_type/Slow2G')306      test_driver.AddChromeArg('--force-fieldtrials=NetworkQualityEstimator/'307                               'Enabled')308      test_driver.LoadURL('http://check.googlezip.net/cacheable/test.html')309      lofi_responses = 0310      for response in test_driver.GetHTTPResponses():311        if not response.url.endswith('png'):312          continue313        if not response.request_headers:314          continue315        if (self.checkLoFiResponse(response, True)):316          lofi_responses = lofi_responses + 1317      # Verify that Lo-Fi responses were seen.318      self.assertNotEqual(0, lofi_responses)319      # Second page load with the chrome proxy off.320      test_driver._StopDriver()321      test_driver.RemoveChromeArg('--enable-spdy-proxy-auth')322      test_driver.LoadURL('http://check.googlezip.net/cacheable/test.html')323      responses = 0324      for response in test_driver.GetHTTPResponses():325        if not response.url.endswith('png'):326          continue327        if not response.request_headers:328          continue329        responses = responses + 1330        self.assertNotHasChromeProxyViaHeader(response)331        self.checkLoFiResponse(response, False)332      # Verify that responses were seen.333      self.assertNotEqual(0, responses)334      # Third page load with the chrome proxy on and Lo-Fi off.335      test_driver._StopDriver()336      test_driver.AddChromeArg('--enable-spdy-proxy-auth')337      test_driver.RemoveChromeArg('--enable-features='338                                  'DataReductionProxyDecidesTransform')339      test_driver.AddChromeArg('--disable-features='340                               'DataReductionProxyDecidesTransform')341      test_driver.LoadURL('http://check.googlezip.net/cacheable/test.html')342      responses = 0343      for response in test_driver.GetHTTPResponses():344        if not response.url.endswith('png'):345          continue346        if not response.request_headers:347          continue348        responses = responses + 1349        self.assertHasChromeProxyViaHeader(response)350        self.checkLoFiResponse(response, False)351      # Verify that responses were seen.352      self.assertNotEqual(0, responses)353  # Checks that LoFi images are served and the force empty image experiment354  # directive is provided when LoFi is always-on without Lite Pages enabled.355  @ChromeVersionEqualOrAfterM(61)356  @ChromeVersionBeforeM(65)357  def testLoFiForcedExperimentOldFlags(self):358    # If it was attempted to run with another experiment, skip this test.359    if common.ParseFlags().browser_args and ('--data-reduction-proxy-experiment'360        in common.ParseFlags().browser_args):361      self.skipTest('This test cannot be run with other experiments.')362    with TestDriver() as test_driver:363      test_driver.AddChromeArg('--enable-spdy-proxy-auth')364      test_driver.AddChromeArg('--enable-features='365                               'Previews,DataReductionProxyDecidesTransform')366      test_driver.AddChromeArg('--data-reduction-proxy-lo-fi=always-on')367      # Ensure fast network (4G) to ensure force flag ignores ECT.368      test_driver.AddChromeArg('--force-fieldtrial-params='369                               'NetworkQualityEstimator.Enabled:'370                               'force_effective_connection_type/4G')371      test_driver.AddChromeArg('--force-fieldtrials=NetworkQualityEstimator/'372                               'Enabled')373      test_driver.LoadURL('http://check.googlezip.net/static/index.html')374      lofi_responses = 0375      for response in test_driver.GetHTTPResponses():376        self.assertIn('exp=force_page_policies_empty_image',377          response.request_headers['chrome-proxy'])378        if response.url.endswith('html'):379          # Verify that the server provides the fallback directive380          self.assertIn('chrome-proxy', response.response_headers)381          self.assertIn('page-policies=empty-image',382                        response.response_headers['chrome-proxy'])383          continue384        if response.url.endswith('png'):385          self.checkLoFiResponse(response, True)386          lofi_responses = lofi_responses + 1387      # Verify that Lo-Fi responses were seen.388      self.assertNotEqual(0, lofi_responses)389  # Checks that Client LoFi resource requests have the Intervention header.390  @ChromeVersionEqualOrAfterM(61)391  def testClientLoFiInterventionHeader(self):392    with TestDriver() as test_driver:393      test_driver.AddChromeArg('--enable-spdy-proxy-auth')394      test_driver.AddChromeArg('--enable-features='395                               'Previews,DataReductionProxyDecidesTransform')396      test_driver.AddChromeArg(397          '--force-fieldtrial-params=NetworkQualityEstimator.Enabled:'398          'force_effective_connection_type/2G,'399          'PreviewsClientLoFi.Enabled:'400          'max_allowed_effective_connection_type/4G')401      test_driver.AddChromeArg(402          '--force-fieldtrials=NetworkQualityEstimator/Enabled/'403          'PreviewsClientLoFi/Enabled')404      test_driver.LoadURL('https://check.googlezip.net/static/index.html')405      intervention_headers = 0406      for response in test_driver.GetHTTPResponses():407        if not response.url.endswith('html'):408          self.assertIn('intervention', response.request_headers)409          intervention_headers = intervention_headers + 1410      self.assertNotEqual(0, intervention_headers)411if __name__ == '__main__':...application_driver_test.py
Source:application_driver_test.py  
1# -*- coding: utf-8 -*-2from __future__ import absolute_import, print_function3import os4import numpy as np5import tensorflow as tf6from niftynet.engine.application_driver import ApplicationDriver7from niftynet.io.misc_io import set_logger8from niftynet.utilities.util_common import ParserNamespace9from niftynet.application.base_application import TRAIN, INFER10# def _run_test_application():11#    test_driver = get_initialised_driver()12#    test_driver.run_application()13#    return14def get_initialised_driver(starting_iter=0):15    system_param = {16        'SYSTEM': ParserNamespace(17            action='train',18            num_threads=2,19            num_gpus=4,20            cuda_devices='6',21            model_dir=os.path.join('.', 'testing_data'),22            dataset_split_file=os.path.join(23                '.', 'testing_data', 'testtoyapp.csv')),24        'NETWORK': ParserNamespace(25            batch_size=20,26            name='tests.toy_application.TinyNet'),27        'TRAINING': ParserNamespace(28            starting_iter=starting_iter,29            max_iter=500,30            save_every_n=20,31            tensorboard_every_n=1,32            max_checkpoints=20,33            optimiser='niftynet.engine.application_optimiser.Adagrad',34            validation_every_n=-1,35            exclude_fraction_for_validation=0.1,36            exclude_fraction_for_inference=0.1,37            lr=0.01),38        'CUSTOM': ParserNamespace(39            vector_size=100,40            mean=10.0,41            stddev=2.0,42            name='tests.toy_application.ToyApplication')43    }44    app_driver = ApplicationDriver()45    app_driver.initialise_application(system_param, {})46    # set parameters without __init__47    app_driver.app.action_param = system_param['TRAINING']48    app_driver.app.net_param = system_param['NETWORK']49    app_driver.app.action = TRAIN50    return app_driver51class ApplicationDriverTest(tf.test.TestCase):52    def test_wrong_init(self):53        app_driver = ApplicationDriver()54        with self.assertRaisesRegexp(AttributeError, ''):55            app_driver.initialise_application([], [])56    def test_create_app(self):57        test_driver = get_initialised_driver(starting_iter=499)58        with self.assertRaisesRegexp(ValueError, 'Could not import'):59            test_driver._create_app('test.test')60        with self.assertRaisesRegexp(ValueError, 'Could not import'):61            test_driver._create_app('testtest')62        with self.assertRaisesRegexp(ValueError, 'Could not import'):63            test_driver._create_app(1)64        test_driver._create_app('tests.toy_application.ToyApplication')65    def test_stop_app(self):66        test_driver = get_initialised_driver()67        test_driver.graph = test_driver._create_graph(test_driver.graph)68        with self.test_session(graph=test_driver.graph) as sess:69            sess.run(test_driver._init_op)70            coord = tf.train.Coordinator()71            for samplers in test_driver.app.get_sampler():72                for sampler in samplers:73                    sampler.run_threads(sess, coord, test_driver.num_threads)74            train_op = test_driver.app.gradient_op75            test_driver.app.stop()76            try:77                while True:78                    sess.run(train_op)79            except tf.errors.OutOfRangeError:80                for thread in test_driver.app.sampler[0][0]._threads:81                    self.assertFalse(thread.isAlive(), "threads not closed")82    def test_training_update(self):83        test_driver = get_initialised_driver()84        test_driver.graph = test_driver._create_graph(test_driver.graph)85        with self.test_session(graph=test_driver.graph) as sess:86            sess.run(test_driver._init_op)87            coord = tf.train.Coordinator()88            for samplers in test_driver.app.get_sampler():89                for sampler in samplers:90                    sampler.run_threads(sess, coord, test_driver.num_threads)91            train_op = test_driver.app.gradient_op92            test_tensor = test_driver.graph.get_tensor_by_name(93                'G/conv_bn_selu/conv_/w:0')94            var_0 = sess.run(test_tensor)95            sess.run(train_op)96            var_1 = sess.run(test_tensor)97            square_diff = np.sum(np.abs(var_0 - var_1))98            self.assertGreater(99                square_diff, 0.0, 'train_op does not change model')100            test_driver.app.stop()101    def test_multi_device_inputs(self):102        test_driver = get_initialised_driver()103        test_driver.graph = test_driver._create_graph(test_driver.graph)104        with self.test_session(graph=test_driver.graph) as sess:105            sess.run(test_driver._init_op)106            coord = tf.train.Coordinator()107            for samplers in test_driver.app.get_sampler():108                for sampler in samplers:109                    sampler.run_threads(sess, coord, test_driver.num_threads)110            for i in range(2):111                sess.run(test_driver.app.gradient_op)112                s_0, s_1, s_2, s_3 = sess.run([113                    test_driver.graph.get_tensor_by_name(114                        'worker_0/feature_input:0'),115                    test_driver.graph.get_tensor_by_name(116                        'worker_1/feature_input:0'),117                    test_driver.graph.get_tensor_by_name(118                        'worker_2/feature_input:0'),119                    test_driver.graph.get_tensor_by_name(120                        'worker_3/feature_input:0')121                ])122                msg = 'same input data for different devices'123                self.assertGreater(np.sum(np.abs(s_0 - s_1)), 0.0, msg)124                self.assertGreater(np.sum(np.abs(s_0 - s_2)), 0.0, msg)125                self.assertGreater(np.sum(np.abs(s_0 - s_3)), 0.0, msg)126                self.assertGreater(np.sum(np.abs(s_1 - s_2)), 0.0, msg)127                self.assertGreater(np.sum(np.abs(s_1 - s_3)), 0.0, msg)128                self.assertGreater(np.sum(np.abs(s_2 - s_3)), 0.0, msg)129        test_driver.app.stop()130    def test_multi_device_gradients(self):131        test_driver = get_initialised_driver()132        test_driver.graph = test_driver._create_graph(test_driver.graph)133        with self.test_session(graph=test_driver.graph) as sess:134            sess.run(test_driver._init_op)135            coord = tf.train.Coordinator()136            for samplers in test_driver.app.get_sampler():137                for sampler in samplers:138                    sampler.run_threads(sess, coord, test_driver.num_threads)139            for i in range(2):140                sess.run(test_driver.app.gradient_op)141                g_0, g_1, g_2, g_3, g_ave = sess.run([142                    test_driver.graph.get_tensor_by_name(143                        'worker_0/ComputeGradients/gradients/AddN_5:0'),144                    test_driver.graph.get_tensor_by_name(145                        'worker_1/ComputeGradients/gradients/AddN_5:0'),146                    test_driver.graph.get_tensor_by_name(147                        'worker_2/ComputeGradients/gradients/AddN_5:0'),148                    test_driver.graph.get_tensor_by_name(149                        'worker_3/ComputeGradients/gradients/AddN_5:0'),150                    test_driver.graph.get_tensor_by_name(151                        'ApplyGradients/Mean:0')152                ])153                msg = 'same gradients for different devices'154                self.assertGreater(np.sum(np.abs(g_0 - g_1)), 0.0, msg)155                self.assertGreater(np.sum(np.abs(g_0 - g_2)), 0.0, msg)156                self.assertGreater(np.sum(np.abs(g_0 - g_3)), 0.0, msg)157                self.assertGreater(np.sum(np.abs(g_1 - g_2)), 0.0, msg)158                self.assertGreater(np.sum(np.abs(g_1 - g_3)), 0.0, msg)159                self.assertGreater(np.sum(np.abs(g_2 - g_3)), 0.0, msg)160                g_array = np.concatenate([g_0.reshape((1, -1)),161                                          g_1.reshape((1, -1)),162                                          g_2.reshape((1, -1)),163                                          g_3.reshape((1, -1))], axis=0)164                g_ave = g_ave.reshape(-1)165                g_np_ave = np.mean(g_array, axis=0)166                self.assertAllClose(g_np_ave, g_ave)167        test_driver.app.stop()168    def test_rand_initialisation(self):169        test_driver = get_initialised_driver(starting_iter=0)170        test_driver.graph = test_driver._create_graph(test_driver.graph)171        with self.test_session(graph=test_driver.graph) as sess:172            test_tensor = test_driver.graph.get_tensor_by_name(173                "G/conv_bn_selu/conv_/w:0")174            with self.assertRaisesRegexp(175                    tf.errors.FailedPreconditionError,176                    'uninitialized value'):177                sess.run(test_tensor)178            test_driver._rand_init_or_restore_vars(sess)179            sess.run(test_tensor)180            _ = sess.run(tf.global_variables())181    def test_from_latest_file_initialisation(self):182        test_driver = get_initialised_driver(starting_iter=-1)183        test_driver.graph = test_driver._create_graph(test_driver.graph)184        expected_init = np.array(185            [[-0.03544217, 0.0228963, -0.04585603, 0.16923568, -0.51635778,186              0.60694504, 0.01968583, -0.6252712, 0.28622296, -0.29527491,187              0.61191976, 0.27878678, -0.07661559, -0.41357407, 0.70488983,188              -0.10836645, 0.06488426, 0.0746650, -0.188567, -0.64652514]],189            dtype=np.float32)190        with self.test_session(graph=test_driver.graph) as sess:191            test_tensor = test_driver.graph.get_tensor_by_name(192                "G/conv_bn_selu/conv_/w:0")193            with self.assertRaisesRegexp(194                    tf.errors.FailedPreconditionError,195                    'uninitialized value'):196                _ = sess.run(test_tensor)197            test_driver._rand_init_or_restore_vars(sess)198            after_init = sess.run(test_tensor)199            self.assertAllClose(after_init[0], expected_init)200            _ = sess.run(tf.global_variables())201    def test_not_found_file_initialisation(self):202        test_driver = get_initialised_driver(starting_iter=42)203        test_driver.graph = test_driver._create_graph(test_driver.graph)204        with self.test_session(graph=test_driver.graph) as sess:205            with self.assertRaisesRegexp(206                    tf.errors.NotFoundError, 'Failed to find'):207                test_driver._rand_init_or_restore_vars(sess)208    def test_from_file_initialisation(self):209        test_driver = get_initialised_driver(starting_iter=40)210        test_driver.graph = test_driver._create_graph(test_driver.graph)211        expected_init = np.array(212            [[-0.23192197, 0.60880029, -0.24921742, -0.00186354, -0.3345384,213              0.16067748, -0.2210995, -0.19460233, -0.3035436, -0.42839912,214              -0.0489039, -0.90753943, -0.12664583, -0.23129687, 0.01584663,215              -0.43854219, 0.40412974, 0.0396539, -0.1590578, -0.53759819]],216            dtype=np.float32)217        with self.test_session(graph=test_driver.graph) as sess:218            test_tensor = test_driver.graph.get_tensor_by_name(219                "G/conv_bn_selu/conv_/w:0")220            with self.assertRaisesRegexp(221                    tf.errors.FailedPreconditionError,222                    'uninitialized value'):223                _ = sess.run(test_tensor)224            test_driver._rand_init_or_restore_vars(sess)225            after_init = sess.run(test_tensor)226            self.assertAllClose(after_init[0], expected_init)227            _ = sess.run(tf.global_variables())228if __name__ == "__main__":229    set_logger()230    # _run_test_application()...run_main.py
Source:run_main.py  
1'''2@Description: python3@Version: 1.04@Autor: liuhua5@QQ: 434375025@qq.com6@Link: https://github.com/choly19857@Date: 2019-10-29 15:28:018@LastEditors: liuhua9'''10from base_node.read_init import read_ini11import sys12sys.path.append(13    r'F:\Src\LearningPython\AutoTest_Web_meke\base_node\auto_test_web.py')14if __name__ == '__main__':15    # test_driver = AutoTestBase('firefox')16    # test_driver.get_url('http://www.baidu.com')17    # test_driver.sleep()18    # test_driver.get_url('http://www.sina.com')19    # # test_driver.handle_windows(800, 800)20    # test_driver.sleep(1)21    # test_driver.handle_windows('back')22    # test_driver.sleep(1)23    # test_driver.handle_windows('go')24    # test_driver.sleep(1)25    # test_driver.handle_windows('back')26    # test_driver.sleep(1)27    # if test_driver.asser_title('ç¾åº¦ä¸ä¸ï¼ä½ å°±ç¥é'):28    #     print('æå¼urlæ£ç¡®')29    # # if test_driver.open_url_is_true('http://www.baidu.com', 'ç¾åº¦ä¸ä¸ï¼ä½ å°±ç¥é'):30    # #     print('æå¼urlæ£ç¡®')31    # # test_driver.save_png()32    # test_driver.quit_browser()33    pass34    arr_num = ['{}'.format(i) for i in range(1, 201)]...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!!
