Best JavaScript code snippet using synthetixio-synpress
NetworkManager.js
Source:NetworkManager.js  
1/*2 * Copyright (C) 2011 Google Inc. All rights reserved.3 *4 * Redistribution and use in source and binary forms, with or without5 * modification, are permitted provided that the following conditions are6 * met:7 *8 *     * Redistributions of source code must retain the above copyright9 * notice, this list of conditions and the following disclaimer.10 *     * Redistributions in binary form must reproduce the above11 * copyright notice, this list of conditions and the following disclaimer12 * in the documentation and/or other materials provided with the13 * distribution.14 *     * Neither the name of Google Inc. nor the names of its15 * contributors may be used to endorse or promote products derived from16 * this software without specific prior written permission.17 *18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.29 */30/**31 * @constructor32 * @extends {WebInspector.Object}33 */34WebInspector.NetworkManager = function()35{36    WebInspector.Object.call(this);37    this._dispatcher = new WebInspector.NetworkDispatcher(this);38    if (WebInspector.settings.cacheDisabled.get())39        NetworkAgent.setCacheDisabled(true);40    NetworkAgent.enable();41    WebInspector.settings.cacheDisabled.addChangeListener(this._cacheDisabledSettingChanged, this);42    if (WebInspector.settings.userAgent.get())43        this._userAgentSettingChanged();44    WebInspector.settings.userAgent.addChangeListener(this._userAgentSettingChanged, this);45}46WebInspector.NetworkManager.EventTypes = {47    ResourceTrackingEnabled: "ResourceTrackingEnabled",48    ResourceTrackingDisabled: "ResourceTrackingDisabled",49    RequestStarted: "RequestStarted",50    RequestUpdated: "RequestUpdated",51    RequestFinished: "RequestFinished",52    RequestUpdateDropped: "RequestUpdateDropped"53}54WebInspector.NetworkManager._MIMETypes = {55    "text/html":                   {"document": true},56    "text/xml":                    {"document": true},57    "text/plain":                  {"document": true},58    "application/xhtml+xml":       {"document": true},59    "text/css":                    {"stylesheet": true},60    "text/xsl":                    {"stylesheet": true},61    "image/jpeg":                  {"image": true},62    "image/png":                   {"image": true},63    "image/gif":                   {"image": true},64    "image/bmp":                   {"image": true},65    "image/svg+xml":               {"image": true},66    "image/vnd.microsoft.icon":    {"image": true},67    "image/webp":                  {"image": true},68    "image/x-icon":                {"image": true},69    "image/x-xbitmap":             {"image": true},70    "font/ttf":                    {"font": true},71    "font/opentype":               {"font": true},72    "font/woff":                   {"font": true},73    "application/x-font-type1":    {"font": true},74    "application/x-font-ttf":      {"font": true},75    "application/x-font-woff":     {"font": true},76    "application/x-truetype-font": {"font": true},77    "text/javascript":             {"script": true},78    "text/ecmascript":             {"script": true},79    "application/javascript":      {"script": true},80    "application/ecmascript":      {"script": true},81    "application/x-javascript":    {"script": true},82    "application/json":            {"script": true},83    "text/javascript1.1":          {"script": true},84    "text/javascript1.2":          {"script": true},85    "text/javascript1.3":          {"script": true},86    "text/jscript":                {"script": true},87    "text/livescript":             {"script": true},88}89WebInspector.NetworkManager.prototype = {90    enableResourceTracking: function()91    {92        function callback(error)93        {94            this.dispatchEventToListeners(WebInspector.NetworkManager.EventTypes.ResourceTrackingEnabled);95        }96        NetworkAgent.enable(callback.bind(this));97    },98    disableResourceTracking: function()99    {100        function callback(error)101        {102            this.dispatchEventToListeners(WebInspector.NetworkManager.EventTypes.ResourceTrackingDisabled);103        }104        NetworkAgent.disable(callback.bind(this));105    },106    /**107     * @param {string} url108     * @return {WebInspector.NetworkRequest}109     */110    inflightRequestForURL: function(url)111    {112        return this._dispatcher._inflightRequestsByURL[url];113    },114    /**115     * @param {WebInspector.Event} event116     */117    _cacheDisabledSettingChanged: function(event)118    {119        var enabled = /** @type {boolean} */ event.data;120        NetworkAgent.setCacheDisabled(enabled);121    },122    _userAgentSettingChanged: function()123    {124        NetworkAgent.setUserAgentOverride(WebInspector.settings.userAgent.get());125    }126}127WebInspector.NetworkManager.prototype.__proto__ = WebInspector.Object.prototype;128/**129 * @constructor130 * @implements {NetworkAgent.Dispatcher}131 */132WebInspector.NetworkDispatcher = function(manager)133{134    this._manager = manager;135    this._inflightRequestsById = {};136    this._inflightRequestsByURL = {};137    InspectorBackend.registerNetworkDispatcher(this);138}139WebInspector.NetworkDispatcher.prototype = {140    /**141     * @param {WebInspector.NetworkRequest} networkRequest142     * @param {NetworkAgent.Request} request143     */144    _updateNetworkRequestWithRequest: function(networkRequest, request)145    {146        networkRequest.requestMethod = request.method;147        networkRequest.requestHeaders = request.headers;148        networkRequest.requestFormData = request.postData;149    },150    /**151     * @param {WebInspector.NetworkRequest} networkRequest152     * @param {NetworkAgent.Response=} response153     */154    _updateNetworkRequestWithResponse: function(networkRequest, response)155    {156        if (!response)157            return;158        if (response.url && networkRequest.url !== response.url)159            networkRequest.url = response.url;160        networkRequest.mimeType = response.mimeType;161        networkRequest.statusCode = response.status;162        networkRequest.statusText = response.statusText;163        networkRequest.responseHeaders = response.headers;164        if (response.headersText)165            networkRequest.responseHeadersText = response.headersText;166        if (response.requestHeaders)167            networkRequest.requestHeaders = response.requestHeaders;168        if (response.requestHeadersText)169            networkRequest.requestHeadersText = response.requestHeadersText;170        networkRequest.connectionReused = response.connectionReused;171        networkRequest.connectionId = response.connectionId;172        if (response.fromDiskCache)173            networkRequest.cached = true;174        else175            networkRequest.timing = response.timing;176        if (!this._mimeTypeIsConsistentWithType(networkRequest)) {177            WebInspector.console.addMessage(WebInspector.ConsoleMessage.create(WebInspector.ConsoleMessage.MessageSource.Network,178                WebInspector.ConsoleMessage.MessageLevel.Warning,179                WebInspector.UIString("Resource interpreted as %s but transferred with MIME type %s: \"%s\".", networkRequest.type.title(), networkRequest.mimeType, networkRequest.url),180                WebInspector.ConsoleMessage.MessageType.Log,181                "",182                0,183                1,184                [],185                null,186                networkRequest));187        }188    },189    /**190     * @param {WebInspector.NetworkRequest} networkRequest191     * @return {boolean}192     */193    _mimeTypeIsConsistentWithType: function(networkRequest)194    {195        // If status is an error, content is likely to be of an inconsistent type,196        // as it's going to be an error message. We do not want to emit a warning197        // for this, though, as this will already be reported as resource loading failure.198        // Also, if a URL like http://localhost/wiki/load.php?debug=true&lang=en produces text/css and gets reloaded,199        // it is 304 Not Modified and its guessed mime-type is text/php, which is wrong.200        // Don't check for mime-types in 304-resources.201        if (networkRequest.hasErrorStatusCode() || networkRequest.statusCode === 304)202            return true;203        if (typeof networkRequest.type === "undefined"204            || networkRequest.type === WebInspector.resourceTypes.Other205            || networkRequest.type === WebInspector.resourceTypes.XHR206            || networkRequest.type === WebInspector.resourceTypes.WebSocket)207            return true;208        if (!networkRequest.mimeType)209            return true; // Might be not known for cached resources with null responses.210        if (networkRequest.mimeType in WebInspector.NetworkManager._MIMETypes)211            return networkRequest.type.name() in WebInspector.NetworkManager._MIMETypes[networkRequest.mimeType];212        return false;213    },214    /**215     * @param {WebInspector.NetworkRequest} networkRequest216     * @param {?NetworkAgent.CachedResource} cachedResource217     */218    _updateNetworkRequestWithCachedResource: function(networkRequest, cachedResource)219    {220        networkRequest.type = WebInspector.resourceTypes[cachedResource.type];221        networkRequest.resourceSize = cachedResource.bodySize;222        this._updateNetworkRequestWithResponse(networkRequest, cachedResource.response);223    },224    /**225     * @param {NetworkAgent.Response} response226     * @return {boolean}227     */228    _isNull: function(response)229    {230        if (!response)231            return true;232        return !response.status && !response.mimeType && (!response.headers || !Object.keys(response.headers).length);233    },234    /**235     * @param {NetworkAgent.RequestId} requestId236     * @param {NetworkAgent.FrameId} frameId237     * @param {NetworkAgent.LoaderId} loaderId238     * @param {string} documentURL239     * @param {NetworkAgent.Request} request240     * @param {NetworkAgent.Timestamp} time241     * @param {NetworkAgent.Initiator} initiator242     * @param {NetworkAgent.Response=} redirectResponse243     */244    requestWillBeSent: function(requestId, frameId, loaderId, documentURL, request, time, initiator, redirectResponse)245    {246        var networkRequest = this._inflightRequestsById[requestId];247        if (networkRequest) {248            // FIXME: move this check to the backend.249            if (!redirectResponse)250                return;251            this.responseReceived(requestId, frameId, loaderId, time, "Other", redirectResponse);252            networkRequest = this._appendRedirect(requestId, time, request.url);253        } else254            networkRequest = this._createNetworkRequest(requestId, frameId, loaderId, request.url, documentURL, initiator);255        networkRequest.hasNetworkData = true;256        this._updateNetworkRequestWithRequest(networkRequest, request);257        networkRequest.startTime = time;258        this._startNetworkRequest(networkRequest);259    },260    /**261     * @param {NetworkAgent.RequestId} requestId262     */263    requestServedFromCache: function(requestId)264    {265        var networkRequest = this._inflightRequestsById[requestId];266        if (!networkRequest)267            return;268        networkRequest.cached = true;269    },270    /**271     * @param {NetworkAgent.RequestId} requestId272     * @param {NetworkAgent.FrameId} frameId273     * @param {NetworkAgent.LoaderId} loaderId274     * @param {NetworkAgent.Timestamp} time275     * @param {PageAgent.ResourceType} resourceType276     * @param {NetworkAgent.Response} response277     */278    responseReceived: function(requestId, frameId, loaderId, time, resourceType, response)279    {280        // FIXME: move this check to the backend.281        if (this._isNull(response))282            return;283        var networkRequest = this._inflightRequestsById[requestId];284        if (!networkRequest) {285            // We missed the requestWillBeSent.286            var eventData = {};287            eventData.url = response.url;288            eventData.frameId = frameId;289            eventData.loaderId = loaderId;290            eventData.resourceType = resourceType;291            eventData.mimeType = response.mimeType;292            this._manager.dispatchEventToListeners(WebInspector.NetworkManager.EventTypes.RequestUpdateDropped, eventData);293            return;294        }295        networkRequest.responseReceivedTime = time;296        networkRequest.type = WebInspector.resourceTypes[resourceType];297        this._updateNetworkRequestWithResponse(networkRequest, response);298        this._updateNetworkRequest(networkRequest);299    },300    /**301     * @param {NetworkAgent.RequestId} requestId302     * @param {NetworkAgent.Timestamp} time303     * @param {number} dataLength304     * @param {number} encodedDataLength305     */306    dataReceived: function(requestId, time, dataLength, encodedDataLength)307    {308        var networkRequest = this._inflightRequestsById[requestId];309        if (!networkRequest)310            return;311        networkRequest.resourceSize += dataLength;312        if (encodedDataLength != -1)313            networkRequest.increaseTransferSize(encodedDataLength);314        networkRequest.endTime = time;315        this._updateNetworkRequest(networkRequest);316    },317    /**318     * @param {NetworkAgent.RequestId} requestId319     * @param {NetworkAgent.Timestamp} finishTime320     */321    loadingFinished: function(requestId, finishTime)322    {323        var networkRequest = this._inflightRequestsById[requestId];324        if (!networkRequest)325            return;326        this._finishNetworkRequest(networkRequest, finishTime);327    },328    /**329     * @param {NetworkAgent.RequestId} requestId330     * @param {NetworkAgent.Timestamp} time331     * @param {string} localizedDescription332     * @param {boolean=} canceled333     */334    loadingFailed: function(requestId, time, localizedDescription, canceled)335    {336        var networkRequest = this._inflightRequestsById[requestId];337        if (!networkRequest)338            return;339        networkRequest.failed = true;340        networkRequest.canceled = canceled;341        networkRequest.localizedFailDescription = localizedDescription;342        this._finishNetworkRequest(networkRequest, time);343    },344    /**345     * @param {NetworkAgent.RequestId} requestId346     * @param {NetworkAgent.FrameId} frameId347     * @param {NetworkAgent.LoaderId} loaderId348     * @param {string} documentURL349     * @param {NetworkAgent.Timestamp} time350     * @param {NetworkAgent.Initiator} initiator351     * @param {NetworkAgent.CachedResource} cachedResource352     */353    requestServedFromMemoryCache: function(requestId, frameId, loaderId, documentURL, time, initiator, cachedResource)354    {355        var networkRequest = this._createNetworkRequest(requestId, frameId, loaderId, cachedResource.url, documentURL, initiator);356        this._updateNetworkRequestWithCachedResource(networkRequest, cachedResource);357        networkRequest.cached = true;358        networkRequest.requestMethod = "GET";359        this._startNetworkRequest(networkRequest);360        networkRequest.startTime = networkRequest.responseReceivedTime = time;361        this._finishNetworkRequest(networkRequest, time);362    },363    /**364     * @param {NetworkAgent.RequestId} requestId365     * @param {string} requestURL366     */367    webSocketCreated: function(requestId, requestURL)368    {369        var networkRequest = new WebInspector.NetworkRequest(requestId, requestURL, "", "", "");370        networkRequest.type = WebInspector.resourceTypes.WebSocket;371        this._startNetworkRequest(networkRequest);372    },373    /**374     * @param {NetworkAgent.RequestId} requestId375     * @param {NetworkAgent.Timestamp} time376     * @param {NetworkAgent.WebSocketRequest} request377     */378    webSocketWillSendHandshakeRequest: function(requestId, time, request)379    {380        var networkRequest = this._inflightRequestsById[requestId];381        if (!networkRequest)382            return;383        networkRequest.requestMethod = "GET";384        networkRequest.requestHeaders = request.headers;385        networkRequest.webSocketRequestKey3 = request.requestKey3;386        networkRequest.startTime = time;387        this._updateNetworkRequest(networkRequest);388    },389    /**390     * @param {NetworkAgent.RequestId} requestId391     * @param {NetworkAgent.Timestamp} time392     * @param {NetworkAgent.WebSocketResponse} response393     */394    webSocketHandshakeResponseReceived: function(requestId, time, response)395    {396        var networkRequest = this._inflightRequestsById[requestId];397        if (!networkRequest)398            return;399        networkRequest.statusCode = response.status;400        networkRequest.statusText = response.statusText;401        networkRequest.responseHeaders = response.headers;402        networkRequest.webSocketChallengeResponse = response.challengeResponse;403        networkRequest.responseReceivedTime = time;404        this._updateNetworkRequest(networkRequest);405    },406    /**407     * @param {NetworkAgent.RequestId} requestId408     * @param {NetworkAgent.Timestamp} time409     * @param {NetworkAgent.WebSocketFrame} response410     */411    webSocketFrameReceived: function(requestId, time, response)412    {413        var networkRequest = this._inflightRequestsById[requestId];414        if (!networkRequest)415            return;416        networkRequest.addFrame(response, time);417        networkRequest.responseReceivedTime = time;418        this._updateNetworkRequest(networkRequest);419    },420    /**421     * @param {NetworkAgent.RequestId} requestId422     * @param {NetworkAgent.Timestamp} time423     * @param {NetworkAgent.WebSocketFrame} response424     */425    webSocketFrameSent: function(requestId, time, response)426    {427        var networkRequest = this._inflightRequestsById[requestId];428        if (!networkRequest)429            return;430        networkRequest.addFrame(response, time, true);431        networkRequest.responseReceivedTime = time;432        this._updateNetworkRequest(networkRequest);433    },434    /**435     * @param {NetworkAgent.RequestId} requestId436     * @param {NetworkAgent.Timestamp} time437     * @param {string} errorMessage438     */439    webSocketFrameError: function(requestId, time, errorMessage)440    {441        var networkRequest = this._inflightRequestsById[requestId];442        if (!networkRequest)443            return;444        networkRequest.addFrameError(errorMessage, time);445        networkRequest.responseReceivedTime = time;446        this._updateNetworkRequest(networkRequest);447    },448    /**449     * @param {NetworkAgent.RequestId} requestId450     * @param {NetworkAgent.Timestamp} time451     */452    webSocketClosed: function(requestId, time)453    {454        var networkRequest = this._inflightRequestsById[requestId];455        if (!networkRequest)456            return;457        this._finishNetworkRequest(networkRequest, time);458    },459    /**460     * @param {NetworkAgent.RequestId} requestId461     * @param {NetworkAgent.Timestamp} time462     * @param {string} redirectURL463     * @return {WebInspector.NetworkRequest}464     */465    _appendRedirect: function(requestId, time, redirectURL)466    {467        var originalNetworkRequest = this._inflightRequestsById[requestId];468        var previousRedirects = originalNetworkRequest.redirects || [];469        originalNetworkRequest.requestId = "redirected:" + requestId + "." + previousRedirects.length;470        delete originalNetworkRequest.redirects;471        if (previousRedirects.length > 0)472            originalNetworkRequest.redirectSource = previousRedirects[previousRedirects.length - 1];473        this._finishNetworkRequest(originalNetworkRequest, time);474        var newNetworkRequest = this._createNetworkRequest(requestId, originalNetworkRequest.frameId, originalNetworkRequest.loaderId,475             redirectURL, originalNetworkRequest.documentURL, originalNetworkRequest.initiator);476        newNetworkRequest.redirects = previousRedirects.concat(originalNetworkRequest);477        return newNetworkRequest;478    },479    /**480     * @param {WebInspector.NetworkRequest} networkRequest481     */482    _startNetworkRequest: function(networkRequest)483    {484        this._inflightRequestsById[networkRequest.requestId] = networkRequest;485        this._inflightRequestsByURL[networkRequest.url] = networkRequest;486        this._dispatchEventToListeners(WebInspector.NetworkManager.EventTypes.RequestStarted, networkRequest);487    },488    /**489     * @param {WebInspector.NetworkRequest} networkRequest490     */491    _updateNetworkRequest: function(networkRequest)492    {493        this._dispatchEventToListeners(WebInspector.NetworkManager.EventTypes.RequestUpdated, networkRequest);494    },495    /**496     * @param {WebInspector.NetworkRequest} networkRequest497     * @param {NetworkAgent.Timestamp} finishTime498     */499    _finishNetworkRequest: function(networkRequest, finishTime)500    {501        networkRequest.endTime = finishTime;502        networkRequest.finished = true;503        this._dispatchEventToListeners(WebInspector.NetworkManager.EventTypes.RequestFinished, networkRequest);504        delete this._inflightRequestsById[networkRequest.requestId];505        delete this._inflightRequestsByURL[networkRequest.url];506    },507    /**508     * @param {string} eventType509     * @param {WebInspector.NetworkRequest} networkRequest510     */511    _dispatchEventToListeners: function(eventType, networkRequest)512    {513        this._manager.dispatchEventToListeners(eventType, networkRequest);514    },515    /**516     * @param {NetworkAgent.RequestId} requestId517     * @param {string} frameId518     * @param {NetworkAgent.LoaderId} loaderId519     * @param {string} url520     * @param {string} documentURL521     * @param {NetworkAgent.Initiator} initiator522     * @param {ConsoleAgent.StackTrace=} stackTrace523     */524    _createNetworkRequest: function(requestId, frameId, loaderId, url, documentURL, initiator, stackTrace)525    {526        var networkRequest = new WebInspector.NetworkRequest(requestId, url, documentURL, frameId, loaderId);527        networkRequest.initiator = initiator;528        return networkRequest;529    }530}531/**532 * @type {?WebInspector.NetworkManager}533 */...test-network.py
Source:test-network.py  
1#!/usr/bin/python32# ----------------------------------------------------------------------3#    Copyright (C) 2015 Christian Boltz <apparmor@cboltz.de>4#5#    This program is free software; you can redistribute it and/or6#    modify it under the terms of version 2 of the GNU General Public7#    License as published by the Free Software Foundation.8#9#    This program is distributed in the hope that it will be useful,10#    but WITHOUT ANY WARRANTY; without even the implied warranty of11#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12#    GNU General Public License for more details.13#14# ----------------------------------------------------------------------15import unittest16from collections import namedtuple17from common_test import AATest, setup_all_loops18from apparmor.rule.network import NetworkRule, NetworkRuleset, network_domain_keywords19from apparmor.rule import BaseRule20from apparmor.common import AppArmorException, AppArmorBug, cmd21from apparmor.logparser import ReadLog22from apparmor.translations import init_translation23_ = init_translation()24exp = namedtuple('exp', ['audit', 'allow_keyword', 'deny', 'comment',25        'domain', 'all_domains', 'type_or_protocol', 'all_type_or_protocols'])26# --- check if the keyword list is up to date --- #27class NetworkKeywordsTest(AATest):28    def test_network_keyword_list(self):29        rc, output = cmd('../../common/list_af_names.sh')30        self.assertEqual(rc, 0)31        af_names = []32        af_pairs = output.replace('AF_', '').strip().lower().split(",")33        for af_pair in af_pairs:34            af_name = af_pair.lstrip().split(" ")[0]35            # skip max af name definition36            if len(af_name) > 0 and af_name != "max":37                af_names.append(af_name)38        missing_af_names = []39        for keyword in af_names:40            if keyword not in network_domain_keywords:41                # keywords missing in the system are ok (= older kernel), but network_domain_keywords needs to have the full list42                missing_af_names.append(keyword)43        self.assertEqual(missing_af_names, [], 'Missing af_names in NetworkRule network_domain_keywords. This test is likely running '44                'on an newer kernel and will require updating the list of network domain keywords in utils/apparmor/rule/network.py')45# --- tests for single NetworkRule --- #46class NetworkTest(AATest):47    def _compare_obj(self, obj, expected):48        self.assertEqual(expected.allow_keyword, obj.allow_keyword)49        self.assertEqual(expected.audit, obj.audit)50        self.assertEqual(expected.domain, obj.domain)51        self.assertEqual(expected.type_or_protocol, obj.type_or_protocol)52        self.assertEqual(expected.all_domains, obj.all_domains)53        self.assertEqual(expected.all_type_or_protocols, obj.all_type_or_protocols)54        self.assertEqual(expected.deny, obj.deny)55        self.assertEqual(expected.comment, obj.comment)56class NetworkTestParse(NetworkTest):57    tests = [58        # rawrule                                     audit  allow  deny   comment        domain    all?   type/proto  all?59        ('network,'                             , exp(False, False, False, ''           , None  ,   True , None     , True )),60        ('network inet,'                        , exp(False, False, False, ''           , 'inet',   False, None     , True )),61        ('network inet stream,'                 , exp(False, False, False, ''           , 'inet',   False, 'stream' , False)),62        ('deny network inet stream, # comment'  , exp(False, False, True , ' # comment' , 'inet',   False, 'stream' , False)),63        ('audit allow network tcp,'             , exp(True , True , False, ''           , None  ,   True , 'tcp'    , False)),64        ('network stream,'                      , exp(False, False, False, ''           , None  ,   True , 'stream' , False)),65    ]66    def _run_test(self, rawrule, expected):67        self.assertTrue(NetworkRule.match(rawrule))68        obj = NetworkRule.parse(rawrule)69        self.assertEqual(rawrule.strip(), obj.raw_rule)70        self._compare_obj(obj, expected)71class NetworkTestParseInvalid(NetworkTest):72    tests = [73        ('network foo,'                     , AppArmorException),74        ('network foo bar,'                 , AppArmorException),75        ('network foo tcp,'                 , AppArmorException),76        ('network inet bar,'                , AppArmorException),77    ]78    def _run_test(self, rawrule, expected):79        self.assertTrue(NetworkRule.match(rawrule))  # the above invalid rules still match the main regex!80        with self.assertRaises(expected):81            NetworkRule.parse(rawrule)82class NetworkTestParseFromLog(NetworkTest):83    def test_net_from_log(self):84        parser = ReadLog('', '', '')85        event = 'type=AVC msg=audit(1428699242.551:386): apparmor="DENIED" operation="create" profile="/bin/ping" pid=10589 comm="ping" family="inet" sock_type="raw" protocol=1'86        parsed_event = parser.parse_event(event)87        self.assertEqual(parsed_event, {88            'request_mask': None,89            'denied_mask': None,90            'error_code': 0,91            'family': 'inet',92            'magic_token': 0,93            'parent': 0,94            'profile': '/bin/ping',95            'protocol': 'icmp',96            'sock_type': 'raw',97            'operation': 'create',98            'resource': None,99            'info': None,100            'aamode': 'REJECTING',101            'time': 1428699242,102            'active_hat': None,103            'pid': 10589,104            'task': 0,105            'attr': None,106            'name2': None,107            'name': None,108        })109        obj = NetworkRule(parsed_event['family'], parsed_event['sock_type'], log_event=parsed_event)110        #              audit  allow  deny   comment        domain    all?   type/proto  all?111        expected = exp(False, False, False, ''           , 'inet',   False, 'raw'    , False)112        self._compare_obj(obj, expected)113        self.assertEqual(obj.get_raw(1), '  network inet raw,')114class NetworkFromInit(NetworkTest):115    tests = [116        # NetworkRule object                                  audit  allow  deny   comment        domain    all?   type/proto  all?117        (NetworkRule('inet', 'raw', deny=True)          , exp(False, False, True , ''           , 'inet',   False, 'raw'    , False)),118        (NetworkRule('inet', 'raw')                     , exp(False, False, False, ''           , 'inet',   False, 'raw'    , False)),119        (NetworkRule('inet', NetworkRule.ALL)           , exp(False, False, False, ''           , 'inet',   False, None     , True )),120        (NetworkRule(NetworkRule.ALL, NetworkRule.ALL)  , exp(False, False, False, ''           , None  ,   True , None     , True )),121        (NetworkRule(NetworkRule.ALL, 'tcp')            , exp(False, False, False, ''           , None  ,   True , 'tcp'    , False)),122        (NetworkRule(NetworkRule.ALL, 'stream')         , exp(False, False, False, ''           , None  ,   True , 'stream' , False)),123    ]124    def _run_test(self, obj, expected):125        self._compare_obj(obj, expected)126class InvalidNetworkInit(AATest):127    tests = [128        # init params                     expected exception129        (['inet', ''               ]    , AppArmorBug), # empty type_or_protocol130        ([''    , 'tcp'            ]    , AppArmorBug), # empty domain131        (['    ', 'tcp'            ]    , AppArmorBug), # whitespace domain132        (['inet', '   '            ]    , AppArmorBug), # whitespace type_or_protocol133        (['xyxy', 'tcp'            ]    , AppArmorBug), # invalid domain134        (['inet', 'xyxy'           ]    , AppArmorBug), # invalid type_or_protocol135        ([dict(), 'tcp'            ]    , AppArmorBug), # wrong type for domain136        ([None  , 'tcp'            ]    , AppArmorBug), # wrong type for domain137        (['inet', dict()           ]    , AppArmorBug), # wrong type for type_or_protocol138        (['inet', None             ]    , AppArmorBug), # wrong type for type_or_protocol139    ]140    def _run_test(self, params, expected):141        with self.assertRaises(expected):142            NetworkRule(params[0], params[1])143    def test_missing_params_1(self):144        with self.assertRaises(TypeError):145            NetworkRule()146    def test_missing_params_2(self):147        with self.assertRaises(TypeError):148            NetworkRule('inet')149class InvalidNetworkTest(AATest):150    def _check_invalid_rawrule(self, rawrule):151        obj = None152        self.assertFalse(NetworkRule.match(rawrule))153        with self.assertRaises(AppArmorException):154            obj = NetworkRule.parse(rawrule)155        self.assertIsNone(obj, 'NetworkRule handed back an object unexpectedly')156    def test_invalid_net_missing_comma(self):157        self._check_invalid_rawrule('network')  # missing comma158    def test_invalid_net_non_NetworkRule(self):159        self._check_invalid_rawrule('dbus,')  # not a network rule160    def test_empty_net_data_1(self):161        obj = NetworkRule('inet', 'stream')162        obj.domain = ''163        # no domain set, and ALL not set164        with self.assertRaises(AppArmorBug):165            obj.get_clean(1)166    def test_empty_net_data_2(self):167        obj = NetworkRule('inet', 'stream')168        obj.type_or_protocol = ''169        # no type_or_protocol set, and ALL not set170        with self.assertRaises(AppArmorBug):171            obj.get_clean(1)172class WriteNetworkTestAATest(AATest):173    def _run_test(self, rawrule, expected):174        self.assertTrue(NetworkRule.match(rawrule))175        obj = NetworkRule.parse(rawrule)176        clean = obj.get_clean()177        raw = obj.get_raw()178        self.assertEqual(expected.strip(), clean, 'unexpected clean rule')179        self.assertEqual(rawrule.strip(), raw, 'unexpected raw rule')180    tests = [181        #  raw rule                                               clean rule182        ('     network         ,    # foo        '              , 'network, # foo'),183        ('    audit     network inet,'                          , 'audit network inet,'),184        ('   deny network         inet      stream,# foo bar'   , 'deny network inet stream, # foo bar'),185        ('   deny network         inet      ,# foo bar'         , 'deny network inet, # foo bar'),186        ('   allow network         tcp      ,# foo bar'         , 'allow network tcp, # foo bar'),187    ]188    def test_write_manually(self):189        obj = NetworkRule('inet', 'stream', allow_keyword=True)190        expected = '    allow network inet stream,'191        self.assertEqual(expected, obj.get_clean(2), 'unexpected clean rule')192        self.assertEqual(expected, obj.get_raw(2), 'unexpected raw rule')193class NetworkCoveredTest(AATest):194    def _run_test(self, param, expected):195        obj = NetworkRule.parse(self.rule)196        check_obj = NetworkRule.parse(param)197        self.assertTrue(NetworkRule.match(param))198        self.assertEqual(obj.is_equal(check_obj), expected[0], 'Mismatch in is_equal, expected %s' % expected[0])199        self.assertEqual(obj.is_equal(check_obj, True), expected[1], 'Mismatch in is_equal/strict, expected %s' % expected[1])200        self.assertEqual(obj.is_covered(check_obj), expected[2], 'Mismatch in is_covered, expected %s' % expected[2])201        self.assertEqual(obj.is_covered(check_obj, True, True), expected[3], 'Mismatch in is_covered/exact, expected %s' % expected[3])202class NetworkCoveredTest_01(NetworkCoveredTest):203    rule = 'network inet,'204    tests = [205        #   rule                                equal     strict equal    covered     covered exact206        ('network,'                         , [ False   , False         , False     , False     ]),207        ('network inet,'                    , [ True    , True          , True      , True      ]),208        ('network inet, # comment'          , [ True    , False         , True      , True      ]),209        ('allow network inet,'              , [ True    , False         , True      , True      ]),210        ('network     inet,'                , [ True    , False         , True      , True      ]),211        ('network inet stream,'             , [ False   , False         , True      , True      ]),212        ('network inet tcp,'                , [ False   , False         , True      , True      ]),213        ('audit network inet,'              , [ False   , False         , False     , False     ]),214        ('audit network,'                   , [ False   , False         , False     , False     ]),215        ('network unix,'                    , [ False   , False         , False     , False     ]),216        ('network tcp,'                     , [ False   , False         , False     , False     ]),217        ('audit deny network inet,'         , [ False   , False         , False     , False     ]),218        ('deny network inet,'               , [ False   , False         , False     , False     ]),219    ]220class NetworkCoveredTest_02(NetworkCoveredTest):221    rule = 'audit network inet,'222    tests = [223        #   rule                                equal     strict equal    covered     covered exact224        (      'network inet,'              , [ False   , False         , True      , False     ]),225        ('audit network inet,'              , [ True    , True          , True      , True      ]),226        (      'network inet stream,'       , [ False   , False         , True      , False     ]),227        ('audit network inet stream,'       , [ False   , False         , True      , True      ]),228        (      'network,'                   , [ False   , False         , False     , False     ]),229        ('audit network,'                   , [ False   , False         , False     , False     ]),230        ('network unix,'                    , [ False   , False         , False     , False     ]),231    ]232class NetworkCoveredTest_03(NetworkCoveredTest):233    rule = 'network inet stream,'234    tests = [235        #   rule                                equal     strict equal    covered     covered exact236        (      'network inet stream,'       , [ True    , True          , True      , True      ]),237        ('allow network inet stream,'       , [ True    , False         , True      , True      ]),238        (      'network inet,'              , [ False   , False         , False     , False     ]),239        (      'network,'                   , [ False   , False         , False     , False     ]),240        (      'network inet tcp,'          , [ False   , False         , False     , False     ]),241        ('audit network,'                   , [ False   , False         , False     , False     ]),242        ('audit network inet stream,'       , [ False   , False         , False     , False     ]),243        (      'network unix,'              , [ False   , False         , False     , False     ]),244        (      'network,'                   , [ False   , False         , False     , False     ]),245    ]246class NetworkCoveredTest_04(NetworkCoveredTest):247    rule = 'network,'248    tests = [249        #   rule                                equal     strict equal    covered     covered exact250        (      'network,'                   , [ True    , True          , True      , True      ]),251        ('allow network,'                   , [ True    , False         , True      , True      ]),252        (      'network inet,'              , [ False   , False         , True      , True      ]),253        (      'network inet6 stream,'      , [ False   , False         , True      , True      ]),254        (      'network tcp,'               , [ False   , False         , True      , True      ]),255        (      'network inet raw,'          , [ False   , False         , True      , True      ]),256        ('audit network,'                   , [ False   , False         , False     , False     ]),257        ('deny  network,'                   , [ False   , False         , False     , False     ]),258    ]259class NetworkCoveredTest_05(NetworkCoveredTest):260    rule = 'deny network inet,'261    tests = [262        #   rule                                equal     strict equal    covered     covered exact263        (      'deny network inet,'         , [ True    , True          , True      , True      ]),264        ('audit deny network inet,'         , [ False   , False         , False     , False     ]),265        (           'network inet,'         , [ False   , False         , False     , False     ]), # XXX should covered be true here?266        (      'deny network unix,'         , [ False   , False         , False     , False     ]),267        (      'deny network,'              , [ False   , False         , False     , False     ]),268    ]269class NetworkCoveredTest_Invalid(AATest):270    def test_borked_obj_is_covered_1(self):271        obj = NetworkRule.parse('network inet,')272        testobj = NetworkRule('inet', 'stream')273        testobj.domain = ''274        with self.assertRaises(AppArmorBug):275            obj.is_covered(testobj)276    def test_borked_obj_is_covered_2(self):277        obj = NetworkRule.parse('network inet,')278        testobj = NetworkRule('inet', 'stream')279        testobj.type_or_protocol = ''280        with self.assertRaises(AppArmorBug):281            obj.is_covered(testobj)282    def test_invalid_is_covered(self):283        obj = NetworkRule.parse('network inet,')284        testobj = BaseRule()  # different type285        with self.assertRaises(AppArmorBug):286            obj.is_covered(testobj)287    def test_invalid_is_equal(self):288        obj = NetworkRule.parse('network inet,')289        testobj = BaseRule()  # different type290        with self.assertRaises(AppArmorBug):291            obj.is_equal(testobj)292class NetworkLogprofHeaderTest(AATest):293    tests = [294        ('network,',                    [                               _('Network Family'), _('ALL'),     _('Socket Type'), _('ALL'),     ]),295        ('network inet,',               [                               _('Network Family'), 'inet',       _('Socket Type'), _('ALL'),     ]),296        ('network inet stream,',        [                               _('Network Family'), 'inet',       _('Socket Type'), 'stream',     ]),297        ('deny network,',               [_('Qualifier'), 'deny',        _('Network Family'), _('ALL'),     _('Socket Type'), _('ALL'),     ]),298        ('allow network inet,',         [_('Qualifier'), 'allow',       _('Network Family'), 'inet',       _('Socket Type'), _('ALL'),     ]),299        ('audit network inet stream,',  [_('Qualifier'), 'audit',       _('Network Family'), 'inet',       _('Socket Type'), 'stream',     ]),300        ('audit deny network inet,',    [_('Qualifier'), 'audit deny',  _('Network Family'), 'inet',       _('Socket Type'), _('ALL'),     ]),301    ]302    def _run_test(self, params, expected):303        obj = NetworkRule.parse(params)304        self.assertEqual(obj.logprof_header(), expected)305class NetworkRuleReprTest(AATest):306    tests = [307        (NetworkRule('inet', 'stream'),                             '<NetworkRule> network inet stream,'),308        (NetworkRule.parse(' allow  network  inet  stream, # foo'), '<NetworkRule> allow  network  inet  stream, # foo'),309    ]310    def _run_test(self, params, expected):311        self.assertEqual(str(params), expected)312## --- tests for NetworkRuleset --- #313class NetworkRulesTest(AATest):314    def test_empty_ruleset(self):315        ruleset = NetworkRuleset()316        ruleset_2 = NetworkRuleset()317        self.assertEqual([], ruleset.get_raw(2))318        self.assertEqual([], ruleset.get_clean(2))319        self.assertEqual([], ruleset_2.get_raw(2))320        self.assertEqual([], ruleset_2.get_clean(2))321    def test_ruleset_1(self):322        ruleset = NetworkRuleset()323        rules = [324            'network tcp,',325            'network inet,',326        ]327        expected_raw = [328            'network tcp,',329            'network inet,',330            '',331        ]332        expected_clean = [333            'network inet,',334            'network tcp,',335            '',336        ]337        for rule in rules:338            ruleset.add(NetworkRule.parse(rule))339        self.assertEqual(expected_raw, ruleset.get_raw())340        self.assertEqual(expected_clean, ruleset.get_clean())341    def test_ruleset_2(self):342        ruleset = NetworkRuleset()343        rules = [344            'network inet6 raw,',345            'allow network inet,',346            'deny network udp, # example comment',347        ]348        expected_raw = [349            '  network inet6 raw,',350            '  allow network inet,',351            '  deny network udp, # example comment',352            '',353        ]354        expected_clean = [355            '  deny network udp, # example comment',356            '',357            '  allow network inet,',358            '  network inet6 raw,',359            '',360        ]361        for rule in rules:362            ruleset.add(NetworkRule.parse(rule))363        self.assertEqual(expected_raw, ruleset.get_raw(1))364        self.assertEqual(expected_clean, ruleset.get_clean(1))365class NetworkGlobTestAATest(AATest):366    def setUp(self):367        self.maxDiff = None368        self.ruleset = NetworkRuleset()369    def test_glob_1(self):370        self.assertEqual(self.ruleset.get_glob('network inet,'), 'network,')371    # not supported or used yet372    # def test_glob_2(self):373    #     self.assertEqual(self.ruleset.get_glob('network inet raw,'), 'network inet,')374    def test_glob_ext(self):375        with self.assertRaises(NotImplementedError):376            # get_glob_ext is not available for network rules377            self.ruleset.get_glob_ext('network inet raw,')378class NetworkDeleteTestAATest(AATest):379    pass380class NetworkRulesetReprTest(AATest):381    def test_network_ruleset_repr(self):382        obj = NetworkRuleset()383        obj.add(NetworkRule('inet', 'stream'))384        obj.add(NetworkRule.parse(' allow  network  inet  stream, # foo'))385        expected = '<NetworkRuleset>\n  network inet stream,\n  allow  network  inet  stream, # foo\n</NetworkRuleset>'386        self.assertEqual(str(obj), expected)387setup_all_loops(__name__)388if __name__ == '__main__':...index.js
Source:index.js  
1am4core.useTheme(am4themes_animated)2var chart = am4core.create("chartdiv", am4charts.XYChart);3chart.padding(40, 40, 40, 40);4chart.numberFormatter.bigNumberPrefixes = [5  { "number": 1e+3, "suffix": "K" },6  { "number": 1e+6, "suffix": "M" },7  { "number": 1e+9, "suffix": "B" }8];9var label = chart.plotContainer.createChild(am4core.Label);10label.x = am4core.percent(97);11label.y = am4core.percent(95);12label.horizontalCenter = "right";13label.verticalCenter = "middle";14label.dx = -15;15label.fontSize = 50;16var playButton = chart.plotContainer.createChild(am4core.PlayButton);17playButton.x = am4core.percent(97);18playButton.y = am4core.percent(95);19playButton.verticalCenter = "middle";20playButton.events.on("toggled", function(event) {21  if (event.target.isActive) {22    play();23  }24  else {25    stop();26  }27})28var stepDuration = 4000;29var categoryAxis = chart.yAxes.push(new am4charts.CategoryAxis());30categoryAxis.renderer.grid.template.location = 0;31categoryAxis.dataFields.category = "network";32categoryAxis.renderer.minGridDistance = 1;33categoryAxis.renderer.inversed = true;34categoryAxis.renderer.grid.template.disabled = true;35var valueAxis = chart.xAxes.push(new am4charts.ValueAxis());36valueAxis.min = 0;37valueAxis.rangeChangeEasing = am4core.ease.linear;38valueAxis.rangeChangeDuration = stepDuration;39valueAxis.extraMax = 0.1;40var series = chart.series.push(new am4charts.ColumnSeries());41series.dataFields.categoryY = "network";42series.dataFields.valueX = "MAU";43series.tooltipText = "{valueX.value}"44series.columns.template.strokeOpacity = 0;45series.columns.template.column.cornerRadiusBottomRight = 5;46series.columns.template.column.cornerRadiusTopRight = 5;47series.interpolationDuration = stepDuration;48series.interpolationEasing = am4core.ease.linear;49var labelBullet = series.bullets.push(new am4charts.LabelBullet())50labelBullet.label.horizontalCenter = "right";51labelBullet.label.text = "{values.valueX.workingValue.formatNumber('#.0as')}";52labelBullet.label.textAlign = "end";53labelBullet.label.dx = -10;54chart.zoomOutButton.disabled = true;55// as by default columns of the same series are of the same color, we add adapter which takes colors from chart.colors color set56series.columns.template.adapter.add("fill", function(fill, target){57  return chart.colors.getIndex(target.dataItem.index);58});59var year = 2003;60label.text = year.toString();61var interval;62function play() {63  interval = setInterval(function(){64    nextYear();65  }, stepDuration)66  nextYear();67}68function stop() {69  if (interval) {70    clearInterval(interval);71  }72}73function nextYear() {74  year++75  if (year > 2018) {76    year = 2003;77  }78  var newData = allData[year];79  var itemsWithNonZero = 0;80  for (var i = 0; i < chart.data.length; i++) {81    chart.data[i].MAU = newData[i].MAU;82    if (chart.data[i].MAU > 0) {83      itemsWithNonZero++;84    }85  }86  if (year == 2003) {87    series.interpolationDuration = stepDuration / 4;88    valueAxis.rangeChangeDuration = stepDuration / 4;89  }90  else {91    series.interpolationDuration = stepDuration;92    valueAxis.rangeChangeDuration = stepDuration;93  }94  chart.invalidateRawData();95  label.text = year.toString();96  categoryAxis.zoom({ start: 0, end: itemsWithNonZero / categoryAxis.dataItems.length });97}98categoryAxis.sortBySeries = series;99var allData = {100  "2003": [101    {102      "network": "Facebook",103      "MAU": 0104    },105    {106      "network": "Flickr",107      "MAU": 0108    },109    {110      "network": "Google Buzz",111      "MAU": 0112    },113    {114      "network": "Friendster",115      "MAU": 4470000116    },117    {118      "network": "Google+",119      "MAU": 0120    },121    {122      "network": "Hi5",123      "MAU": 0124    },125    {126      "network": "Instagram",127      "MAU": 0128    },129    {130      "network": "MySpace",131      "MAU": 0132    },133    {134      "network": "Orkut",135      "MAU": 0136    },137    {138      "network": "Pinterest",139      "MAU": 0140    },141    {142      "network": "Reddit",143      "MAU": 0144    },145    {146      "network": "Snapchat",147      "MAU": 0148    },149    {150      "network": "TikTok",151      "MAU": 0152    },153    {154      "network": "Tumblr",155      "MAU": 0156    },157    {158      "network": "Twitter",159      "MAU": 0160    },161    {162      "network": "WeChat",163      "MAU": 0164    },165    {166      "network": "Weibo",167      "MAU": 0168    },169    {170      "network": "Whatsapp",171      "MAU": 0172    },173    {174      "network": "YouTube",175      "MAU": 0176    }177  ],178  "2004": [179    {180      "network": "Facebook",181      "MAU": 0182    },183    {184      "network": "Flickr",185      "MAU": 3675135186    },187    {188      "network": "Friendster",189      "MAU": 5970054190    },191    {192      "network": "Google Buzz",193      "MAU": 0194    },195    {196      "network": "Google+",197      "MAU": 0198    },199    {200      "network": "Hi5",201      "MAU": 0202    },203    {204      "network": "Instagram",205      "MAU": 0206    },207    {208      "network": "MySpace",209      "MAU": 980036210    },211    {212      "network": "Orkut",213      "MAU": 4900180214    },215    {216      "network": "Pinterest",217      "MAU": 0218    },219    {220      "network": "Reddit",221      "MAU": 0222    },223    {224      "network": "Snapchat",225      "MAU": 0226    },227    {228      "network": "TikTok",229      "MAU": 0230    },231    {232      "network": "Tumblr",233      "MAU": 0234    },235    {236      "network": "Twitter",237      "MAU": 0238    },239    {240      "network": "WeChat",241      "MAU": 0242    },243    {244      "network": "Weibo",245      "MAU": 0246    },247    {248      "network": "Whatsapp",249      "MAU": 0250    },251    {252      "network": "YouTube",253      "MAU": 0254    }255  ],256  "2005": [257    {258      "network": "Facebook",259      "MAU": 0260    },261    {262      "network": "Flickr",263      "MAU": 7399354264    },265    {266      "network": "Friendster",267      "MAU": 7459742268    },269    {270      "network": "Google Buzz",271      "MAU": 0272    },273    {274      "network": "Google+",275      "MAU": 0276    },277    {278      "network": "Hi5",279      "MAU": 9731610280    },281    {282      "network": "Instagram",283      "MAU": 0284    },285    {286      "network": "MySpace",287      "MAU": 19490059288    },289    {290      "network": "Orkut",291      "MAU": 9865805292    },293    {294      "network": "Pinterest",295      "MAU": 0296    },297    {298      "network": "Reddit",299      "MAU": 0300    },301    {302      "network": "Snapchat",303      "MAU": 0304    },305    {306      "network": "TikTok",307      "MAU": 0308    },309    {310      "network": "Tumblr",311      "MAU": 0312    },313    {314      "network": "Twitter",315      "MAU": 0316    },317    {318      "network": "WeChat",319      "MAU": 0320    },321    {322      "network": "Weibo",323      "MAU": 0324    },325    {326      "network": "Whatsapp",327      "MAU": 0328    },329    {330      "network": "YouTube",331      "MAU": 1946322332    }333  ],334  "2006": [335    {336      "network": "Facebook",337      "MAU": 0338    },339    {340      "network": "Flickr",341      "MAU": 14949270342    },343    {344      "network": "Friendster",345      "MAU": 8989854346    },347    {348      "network": "Google Buzz",349      "MAU": 0350    },351    {352      "network": "Google+",353      "MAU": 0354    },355    {356      "network": "Hi5",357      "MAU": 19932360358    },359    {360      "network": "Instagram",361      "MAU": 0362    },363    {364      "network": "MySpace",365      "MAU": 54763260366    },367    {368      "network": "Orkut",369      "MAU": 14966180370    },371    {372      "network": "Pinterest",373      "MAU": 0374    },375    {376      "network": "Reddit",377      "MAU": 248309378    },379    {380      "network": "Snapchat",381      "MAU": 0382    },383    {384      "network": "TikTok",385      "MAU": 0386    },387    {388      "network": "Tumblr",389      "MAU": 0390    },391    {392      "network": "Twitter",393      "MAU": 0394    },395    {396      "network": "WeChat",397      "MAU": 0398    },399    {400      "network": "Weibo",401      "MAU": 0402    },403    {404      "network": "Whatsapp",405      "MAU": 0406    },407    {408      "network": "YouTube",409      "MAU": 19878248410    }411  ],412  "2007": [413    {414      "network": "Facebook",415      "MAU": 0416    },417    {418      "network": "Flickr",419      "MAU": 29299875420    },421    {422      "network": "Friendster",423      "MAU": 24253200424    },425    {426      "network": "Google Buzz",427      "MAU": 0428    },429    {430      "network": "Google+",431      "MAU": 0432    },433    {434      "network": "Hi5",435      "MAU": 29533250436    },437    {438      "network": "Instagram",439      "MAU": 0440    },441    {442      "network": "MySpace",443      "MAU": 69299875444    },445    {446      "network": "Orkut",447      "MAU": 26916562448    },449    {450      "network": "Pinterest",451      "MAU": 0452    },453    {454      "network": "Reddit",455      "MAU": 488331456    },457    {458      "network": "Snapchat",459      "MAU": 0460    },461    {462      "network": "TikTok",463      "MAU": 0464    },465    {466      "network": "Tumblr",467      "MAU": 0468    },469    {470      "network": "Twitter",471      "MAU": 0472    },473    {474      "network": "WeChat",475      "MAU": 0476    },477    {478      "network": "Weibo",479      "MAU": 0480    },481    {482      "network": "Whatsapp",483      "MAU": 0484    },485    {486      "network": "YouTube",487      "MAU": 143932250488    }489  ],490  "2008": [491    {492      "network": "Facebook",493      "MAU": 100000000494    },495    {496      "network": "Flickr",497      "MAU": 30000000498    },499    {500      "network": "Friendster",501      "MAU": 51008911502    },503    {504      "network": "Google Buzz",505      "MAU": 0506    },507    {508      "network": "Google+",509      "MAU": 0510    },511    {512      "network": "Hi5",513      "MAU": 55045618514    },515    {516      "network": "Instagram",517      "MAU": 0518    },519    {520      "network": "MySpace",521      "MAU": 72408233522    },523    {524      "network": "Orkut",525      "MAU": 44357628526    },527    {528      "network": "Pinterest",529      "MAU": 0530    },531    {532      "network": "Reddit",533      "MAU": 1944940534    },535    {536      "network": "Snapchat",537      "MAU": 0538    },539    {540      "network": "TikTok",541      "MAU": 0542    },543    {544      "network": "Tumblr",545      "MAU": 0546    },547    {548      "network": "Twitter",549      "MAU": 0550    },551    {552      "network": "WeChat",553      "MAU": 0554    },555    {556      "network": "Weibo",557      "MAU": 0558    },559    {560      "network": "Whatsapp",561      "MAU": 0562    },563    {564      "network": "YouTube",565      "MAU": 294493950566    }567  ],568  "2009": [569    {570      "network": "Facebook",571      "MAU": 276000000572    },573    {574      "network": "Flickr",575      "MAU": 41834525576    },577    {578      "network": "Friendster",579      "MAU": 28804331580    },581    {582      "network": "Google Buzz",583      "MAU": 0584    },585    {586      "network": "Google+",587      "MAU": 0588    },589    {590      "network": "Hi5",591      "MAU": 57893524592    },593    {594      "network": "Instagram",595      "MAU": 0596    },597    {598      "network": "MySpace",599      "MAU": 70133095600    },601    {602      "network": "Orkut",603      "MAU": 47366905604    },605    {606      "network": "Pinterest",607      "MAU": 0608    },609    {610      "network": "Reddit",611      "MAU": 3893524612    },613    {614      "network": "Snapchat",615      "MAU": 0616    },617    {618      "network": "TikTok",619      "MAU": 0620    },621    {622      "network": "Tumblr",623      "MAU": 0624    },625    {626      "network": "Twitter",627      "MAU": 0628    },629    {630      "network": "WeChat",631      "MAU": 0632    },633    {634      "network": "Weibo",635      "MAU": 0636    },637    {638      "network": "Whatsapp",639      "MAU": 0640    },641    {642      "network": "YouTube",643      "MAU": 413611440644    }645  ],646  "2010": [647    {648      "network": "Facebook",649      "MAU": 517750000650    },651    {652      "network": "Flickr",653      "MAU": 54708063654    },655    {656      "network": "Friendster",657      "MAU": 0658    },659    {660      "network": "Google Buzz",661      "MAU": 166029650662    },663    {664      "network": "Google+",665      "MAU": 0666    },667    {668      "network": "Hi5",669      "MAU": 59953290670    },671    {672      "network": "Instagram",673      "MAU": 0674    },675    {676      "network": "MySpace",677      "MAU": 68046710678    },679    {680      "network": "Orkut",681      "MAU": 49941613682    },683    {684      "network": "Pinterest",685      "MAU": 0686    },687    {688      "network": "Reddit",689      "MAU": 0690    },691    {692      "network": "Snapchat",693      "MAU": 0694    },695    {696      "network": "TikTok",697      "MAU": 0698    },699    {700      "network": "Tumblr",701      "MAU": 0702    },703    {704      "network": "Twitter",705      "MAU": 43250000706    },707    {708      "network": "WeChat",709      "MAU": 0710    },711    {712      "network": "Weibo",713      "MAU": 19532900714    },715    {716      "network": "Whatsapp",717      "MAU": 0718    },719    {720      "network": "YouTube",721      "MAU": 480551990722    }723  ],724  "2011": [725    {726      "network": "Facebook",727      "MAU": 766000000728    },729    {730      "network": "Flickr",731      "MAU": 66954600732    },733    {734      "network": "Friendster",735      "MAU": 0736    },737    {738      "network": "Google Buzz",739      "MAU": 170000000740    },741    {742      "network": "Google+",743      "MAU": 0744    },745    {746      "network": "Hi5",747      "MAU": 46610848748    },749    {750      "network": "Instagram",751      "MAU": 0752    },753    {754      "network": "MySpace",755      "MAU": 46003536756    },757    {758      "network": "Orkut",759      "MAU": 47609080760    },761    {762      "network": "Pinterest",763      "MAU": 0764    },765    {766      "network": "Reddit",767      "MAU": 0768    },769    {770      "network": "Snapchat",771      "MAU": 0772    },773    {774      "network": "TikTok",775      "MAU": 0776    },777    {778      "network": "Tumblr",779      "MAU": 0780    },781    {782      "network": "Twitter",783      "MAU": 92750000784    },785    {786      "network": "WeChat",787      "MAU": 47818400788    },789    {790      "network": "Weibo",791      "MAU": 48691040792    },793    {794      "network": "Whatsapp",795      "MAU": 0796    },797    {798      "network": "YouTube",799      "MAU": 642669824800    }801  ],802  "2012": [803    {804      "network": "Facebook",805      "MAU": 979750000806    },807    {808      "network": "Flickr",809      "MAU": 79664888810    },811    {812      "network": "Friendster",813      "MAU": 0814    },815    {816      "network": "Google Buzz",817      "MAU": 170000000818    },819    {820      "network": "Google+",821      "MAU": 107319100822    },823    {824      "network": "Hi5",825      "MAU": 0826    },827    {828      "network": "Instagram",829      "MAU": 0830    },831    {832      "network": "MySpace",833      "MAU": 0834    },835    {836      "network": "Orkut",837      "MAU": 45067022838    },839    {840      "network": "Pinterest",841      "MAU": 0842    },843    {844      "network": "Reddit",845      "MAU": 0846    },847    {848      "network": "Snapchat",849      "MAU": 0850    },851    {852      "network": "TikTok",853      "MAU": 0854    },855    {856      "network": "Tumblr",857      "MAU": 146890156858    },859    {860      "network": "Twitter",861      "MAU": 160250000862    },863    {864      "network": "WeChat",865      "MAU": 118123370866    },867    {868      "network": "Weibo",869      "MAU": 79195730870    },871    {872      "network": "Whatsapp",873      "MAU": 0874    },875    {876      "network": "YouTube",877      "MAU": 844638200878    }879  ],880  "2013": [881    {882      "network": "Facebook",883      "MAU": 1170500000884    },885    {886      "network": "Flickr",887      "MAU": 80000000888    },889    {890      "network": "Friendster",891      "MAU": 0892    },893    {894      "network": "Google Buzz",895      "MAU": 170000000896    },897    {898      "network": "Google+",899      "MAU": 205654700900    },901    {902      "network": "Hi5",903      "MAU": 0904    },905    {906      "network": "Instagram",907      "MAU": 117500000908    },909    {910      "network": "MySpace",911      "MAU": 0912    },913    {914      "network": "Orkut",915      "MAU": 0916    },917    {918      "network": "Pinterest",919      "MAU": 0920    },921    {922      "network": "Reddit",923      "MAU": 0924    },925    {926      "network": "Snapchat",927      "MAU": 0928    },929    {930      "network": "TikTok",931      "MAU": 0932    },933    {934      "network": "Tumblr",935      "MAU": 293482050936    },937    {938      "network": "Twitter",939      "MAU": 223675000940    },941    {942      "network": "WeChat",943      "MAU": 196523760944    },945    {946      "network": "Weibo",947      "MAU": 118261880948    },949    {950      "network": "Whatsapp",951      "MAU": 300000000952    },953    {954      "network": "YouTube",955      "MAU": 1065223075956    }957  ],958  "2014": [959    {960      "network": "Facebook",961      "MAU": 1334000000962    },963    {964      "network": "Flickr",965      "MAU": 0966    },967    {968      "network": "Friendster",969      "MAU": 0970    },971    {972      "network": "Google Buzz",973      "MAU": 170000000974    },975    {976      "network": "Google+",977      "MAU": 254859015978    },979    {980      "network": "Hi5",981      "MAU": 0982    },983    {984      "network": "Instagram",985      "MAU": 250000000986    },987    {988      "network": "MySpace",989      "MAU": 0990    },991    {992      "network": "Orkut",993      "MAU": 0994    },995    {996      "network": "Pinterest",997      "MAU": 0998    },999    {1000      "network": "Reddit",1001      "MAU": 1357869561002    },1003    {1004      "network": "Snapchat",1005      "MAU": 01006    },1007    {1008      "network": "TikTok",1009      "MAU": 01010    },1011    {1012      "network": "Tumblr",1013      "MAU": 3887211631014    },1015    {1016      "network": "Twitter",1017      "MAU": 2236750001018    },1019    {1020      "network": "WeChat",1021      "MAU": 4442324151022    },1023    {1024      "network": "Weibo",1025      "MAU": 1548903451026    },1027    {1028      "network": "Whatsapp",1029      "MAU": 4987500001030    },1031    {1032      "network": "YouTube",1033      "MAU": 12494517251034    }1035  ],1036  "2015": [1037    {1038      "network": "Facebook",1039      "MAU": 15167500001040    },1041    {1042      "network": "Flickr",1043      "MAU": 01044    },1045    {1046      "network": "Friendster",1047      "MAU": 01048    },1049    {1050      "network": "Google Buzz",1051      "MAU": 1700000001052    },1053    {1054      "network": "Google+",1055      "MAU": 2989500151056    },1057    {1058      "network": "Hi5",1059      "MAU": 01060    },1061    {1062      "network": "Instagram",1063      "MAU": 4000000001064    },1065    {1066      "network": "MySpace",1067      "MAU": 01068    },1069    {1070      "network": "Orkut",1071      "MAU": 01072    },1073    {1074      "network": "Pinterest",1075      "MAU": 01076    },1077    {1078      "network": "Reddit",1079      "MAU": 1633466761080    },1081    {1082      "network": "Snapchat",1083      "MAU": 01084    },1085    {1086      "network": "TikTok",1087      "MAU": 01088    },1089    {1090      "network": "Tumblr",1091      "MAU": 4759233631092    },1093    {1094      "network": "Twitter",1095      "MAU": 3045000001096    },1097    {1098      "network": "WeChat",1099      "MAU": 6608434071100    },1101    {1102      "network": "Weibo",1103      "MAU": 2087166851104    },1105    {1106      "network": "Whatsapp",1107      "MAU": 8000000001108    },1109    {1110      "network": "YouTube",1111      "MAU": 13281333601112    }1113  ],1114  "2016": [1115    {1116      "network": "Facebook",1117      "MAU": 17535000001118    },1119    {1120      "network": "Flickr",1121      "MAU": 01122    },1123    {1124      "network": "Friendster",1125      "MAU": 01126    },1127    {1128      "network": "Google Buzz",1129      "MAU": 01130    },1131    {1132      "network": "Google+",1133      "MAU": 3986480001134    },1135    {1136      "network": "Hi5",1137      "MAU": 01138    },1139    {1140      "network": "Instagram",1141      "MAU": 5500000001142    },1143    {1144      "network": "MySpace",1145      "MAU": 01146    },1147    {1148      "network": "Orkut",1149      "MAU": 01150    },1151    {1152      "network": "Pinterest",1153      "MAU": 1432500001154    },1155    {1156      "network": "Reddit",1157      "MAU": 2389724801158    },1159    {1160      "network": "Snapchat",1161      "MAU": 2386480001162    },1163    {1164      "network": "TikTok",1165      "MAU": 01166    },1167    {1168      "network": "Tumblr",1169      "MAU": 5657967201170    },1171    {1172      "network": "Twitter",1173      "MAU": 3145000001174    },1175    {1176      "network": "WeChat",1177      "MAU": 8475123201178    },1179    {1180      "network": "Weibo",1181      "MAU": 2810265601182    },1183    {1184      "network": "Whatsapp",1185      "MAU": 10000000001186    },1187    {1188      "network": "YouTube",1189      "MAU": 13990536001190    }1191  ],1192  "2017": [1193    {1194      "network": "Facebook",1195      "MAU": 20357500001196    },1197    {1198      "network": "Flickr",1199      "MAU": 01200    },1201    {1202      "network": "Friendster",1203      "MAU": 01204    },1205    {1206      "network": "Google Buzz",1207      "MAU": 01208    },1209    {1210      "network": "Google+",1211      "MAU": 4956570001212    },1213    {1214      "network": "Hi5",1215      "MAU": 01216    },1217    {1218      "network": "Instagram",1219      "MAU": 7500000001220    },1221    {1222      "network": "MySpace",1223      "MAU": 01224    },1225    {1226      "network": "Orkut",1227      "MAU": 01228    },1229    {1230      "network": "Pinterest",1231      "MAU": 1950000001232    },1233    {1234      "network": "Reddit",1235      "MAU": 2973942001236    },1237    {1238      "network": "Snapchat",1239      "MAU": 01240    },1241    {1242      "network": "TikTok",1243      "MAU": 2391425001244    },1245    {1246      "network": "Tumblr",1247      "MAU": 5937839601248    },1249    {1250      "network": "Twitter",1251      "MAU": 3282500001252    },1253    {1254      "network": "WeChat",1255      "MAU": 9217427501256    },1257    {1258      "network": "Weibo",1259      "MAU": 3575690301260    },1261    {1262      "network": "Whatsapp",1263      "MAU": 13333333331264    },1265    {1266      "network": "YouTube",1267      "MAU": 14956570001268    }1269  ],1270  "2018": [1271    {1272      "network": "Facebook",1273      "MAU": 22552500001274    },1275    {1276      "network": "Flickr",1277      "MAU": 01278    },1279    {1280      "network": "Friendster",1281      "MAU": 01282    },1283    {1284      "network": "Google Buzz",1285      "MAU": 01286    },1287    {1288      "network": "Google+",1289      "MAU": 4300000001290    },1291    {1292      "network": "Hi5",1293      "MAU": 01294    },1295    {1296      "network": "Instagram",1297      "MAU": 10000000001298    },1299    {1300      "network": "MySpace",1301      "MAU": 01302    },1303    {1304      "network": "Orkut",1305      "MAU": 01306    },1307    {1308      "network": "Pinterest",1309      "MAU": 2465000001310    },1311    {1312      "network": "Reddit",1313      "MAU": 3550000001314    },1315    {1316      "network": "Snapchat",1317      "MAU": 01318    },1319    {1320      "network": "TikTok",1321      "MAU": 5000000001322    },1323    {1324      "network": "Tumblr",1325      "MAU": 6240000001326    },1327    {1328      "network": "Twitter",1329      "MAU": 3295000001330    },1331    {1332      "network": "WeChat",1333      "MAU": 10000000001334    },1335    {1336      "network": "Weibo",1337      "MAU": 4310000001338    },1339    {1340      "network": "Whatsapp",1341      "MAU": 14333333331342    },1343    {1344      "network": "YouTube",1345      "MAU": 19000000001346    }1347  ]1348}1349chart.data = JSON.parse(JSON.stringify(allData[year]));1350categoryAxis.zoom({ start: 0, end: 1 / chart.data.length });1351series.events.on("inited", function() {1352  setTimeout(function() {1353    playButton.isActive = true; // this starts interval1354  }, 2000)...test_network.py
Source:test_network.py  
1#    Copyright 2014 Red Hat, Inc.2#3#    Licensed under the Apache License, Version 2.0 (the "License"); you may4#    not use this file except in compliance with the License. You may obtain5#    a copy of the License at6#7#         http://www.apache.org/licenses/LICENSE-2.08#9#    Unless required by applicable law or agreed to in writing, software10#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT11#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the12#    License for the specific language governing permissions and limitations13#    under the License.14import mock15import netaddr16from nova.objects import network as network_obj17from nova.tests.unit.objects import test_objects18from nova.tests import uuidsentinel as uuids19fake_network = {20    'deleted': False,21    'created_at': None,22    'updated_at': None,23    'deleted_at': None,24    'id': 1,25    'label': 'Fake Network',26    'injected': False,27    'cidr': '192.168.1.0/24',28    'cidr_v6': '1234::/64',29    'multi_host': False,30    'netmask': '255.255.255.0',31    'gateway': '192.168.1.1',32    'broadcast': '192.168.1.255',33    'netmask_v6': 64,34    'gateway_v6': '1234::1',35    'bridge': 'br100',36    'bridge_interface': 'eth0',37    'dns1': '8.8.8.8',38    'dns2': '8.8.4.4',39    'vlan': None,40    'vpn_public_address': None,41    'vpn_public_port': None,42    'vpn_private_address': None,43    'dhcp_start': '192.168.1.10',44    'rxtx_base': None,45    'project_id': None,46    'priority': None,47    'host': None,48    'uuid': uuids.network_instance,49    'mtu': None,50    'dhcp_server': '192.168.1.1',51    'enable_dhcp': True,52    'share_address': False,53}54class _TestNetworkObject(object):55    def _compare(self, obj, db_obj):56        for field in obj.fields:57            db_val = db_obj[field]58            obj_val = obj[field]59            if isinstance(obj_val, netaddr.IPAddress):60                obj_val = str(obj_val)61            if isinstance(obj_val, netaddr.IPNetwork):62                obj_val = str(obj_val)63            if field == 'netmask_v6':64                db_val = str(netaddr.IPNetwork('1::/%i' % db_val).netmask)65            self.assertEqual(db_val, obj_val)66    @mock.patch('nova.db.network_get')67    def test_get_by_id(self, get):68        get.return_value = fake_network69        network = network_obj.Network.get_by_id(self.context, 'foo')70        self._compare(network, fake_network)71        get.assert_called_once_with(self.context, 'foo',72                                    project_only='allow_none')73    @mock.patch('nova.db.network_get_by_uuid')74    def test_get_by_uuid(self, get):75        get.return_value = fake_network76        network = network_obj.Network.get_by_uuid(self.context, 'foo')77        self._compare(network, fake_network)78        get.assert_called_once_with(self.context, 'foo')79    @mock.patch('nova.db.network_get_by_cidr')80    def test_get_by_cidr(self, get):81        get.return_value = fake_network82        network = network_obj.Network.get_by_cidr(self.context,83                                                  '192.168.1.0/24')84        self._compare(network, fake_network)85        get.assert_called_once_with(self.context, '192.168.1.0/24')86    @mock.patch('nova.db.network_update')87    @mock.patch('nova.db.network_set_host')88    def test_save(self, set_host, update):89        result = dict(fake_network, injected=True)90        network = network_obj.Network._from_db_object(self.context,91                                                      network_obj.Network(),92                                                      fake_network)93        network.obj_reset_changes()94        network.save()95        network.label = 'bar'96        update.return_value = result97        network.save()98        update.assert_called_once_with(self.context, network.id,99                                       {'label': 'bar'})100        self.assertFalse(set_host.called)101        self._compare(network, result)102    @mock.patch('nova.db.network_update')103    @mock.patch('nova.db.network_set_host')104    @mock.patch('nova.db.network_get')105    def test_save_with_host(self, get, set_host, update):106        result = dict(fake_network, injected=True)107        network = network_obj.Network._from_db_object(self.context,108                                                      network_obj.Network(),109                                                      fake_network)110        network.obj_reset_changes()111        network.host = 'foo'112        get.return_value = result113        network.save()114        set_host.assert_called_once_with(self.context, network.id, 'foo')115        self.assertFalse(update.called)116        self._compare(network, result)117    @mock.patch('nova.db.network_update')118    @mock.patch('nova.db.network_set_host')119    def test_save_with_host_and_other(self, set_host, update):120        result = dict(fake_network, injected=True)121        network = network_obj.Network._from_db_object(self.context,122                                                      network_obj.Network(),123                                                      fake_network)124        network.obj_reset_changes()125        network.host = 'foo'126        network.label = 'bar'127        update.return_value = result128        network.save()129        set_host.assert_called_once_with(self.context, network.id, 'foo')130        update.assert_called_once_with(self.context, network.id,131                                       {'label': 'bar'})132        self._compare(network, result)133    @mock.patch('nova.db.network_associate')134    def test_associate(self, associate):135        network_obj.Network.associate(self.context, 'project',136                                      network_id=123)137        associate.assert_called_once_with(self.context, 'project',138                                          network_id=123, force=False)139    @mock.patch('nova.db.network_disassociate')140    def test_disassociate(self, disassociate):141        network_obj.Network.disassociate(self.context, 123,142                                         host=True, project=True)143        disassociate.assert_called_once_with(self.context, 123, True, True)144    @mock.patch('nova.db.network_create_safe')145    def test_create(self, create):146        create.return_value = fake_network147        network = network_obj.Network(context=self.context, label='foo')148        network.create()149        create.assert_called_once_with(self.context, {'label': 'foo'})150        self._compare(network, fake_network)151    @mock.patch('nova.db.network_delete_safe')152    def test_destroy(self, delete):153        network = network_obj.Network(context=self.context, id=123)154        network.destroy()155        delete.assert_called_once_with(self.context, 123)156        self.assertTrue(network.deleted)157        self.assertNotIn('deleted', network.obj_what_changed())158    @mock.patch('nova.db.network_get_all')159    def test_get_all(self, get_all):160        get_all.return_value = [fake_network]161        networks = network_obj.NetworkList.get_all(self.context)162        self.assertEqual(1, len(networks))163        get_all.assert_called_once_with(self.context, 'allow_none')164        self._compare(networks[0], fake_network)165    @mock.patch('nova.db.network_get_all_by_uuids')166    def test_get_all_by_uuids(self, get_all):167        get_all.return_value = [fake_network]168        networks = network_obj.NetworkList.get_by_uuids(self.context,169                                                        ['foo'])170        self.assertEqual(1, len(networks))171        get_all.assert_called_once_with(self.context, ['foo'], 'allow_none')172        self._compare(networks[0], fake_network)173    @mock.patch('nova.db.network_get_all_by_host')174    def test_get_all_by_host(self, get_all):175        get_all.return_value = [fake_network]176        networks = network_obj.NetworkList.get_by_host(self.context, 'host')177        self.assertEqual(1, len(networks))178        get_all.assert_called_once_with(self.context, 'host')179        self._compare(networks[0], fake_network)180    @mock.patch('nova.db.network_in_use_on_host')181    def test_in_use_on_host(self, in_use):182        in_use.return_value = True183        self.assertTrue(network_obj.Network.in_use_on_host(self.context,184                                                           123, 'foo'))185        in_use.assert_called_once_with(self.context, 123, 'foo')186    @mock.patch('nova.db.project_get_networks')187    def test_get_all_by_project(self, get_nets):188        get_nets.return_value = [fake_network]189        networks = network_obj.NetworkList.get_by_project(self.context, 123)190        self.assertEqual(1, len(networks))191        get_nets.assert_called_once_with(self.context, 123, associate=True)192        self._compare(networks[0], fake_network)193    def test_compat_version_1_1(self):194        network = network_obj.Network._from_db_object(self.context,195                                                      network_obj.Network(),196                                                      fake_network)197        primitive = network.obj_to_primitive(target_version='1.1')198        self.assertNotIn('mtu', primitive)199        self.assertNotIn('enable_dhcp', primitive)200        self.assertNotIn('dhcp_server', primitive)201        self.assertNotIn('share_address', primitive)202class TestNetworkObject(test_objects._LocalTest,203                        _TestNetworkObject):204    pass205class TestRemoteNetworkObject(test_objects._RemoteTest,206                              _TestNetworkObject):...chains.ts
Source:chains.ts  
1import { ChainDataList } from "../helpers";2export const CHAIN_DATA_LIST: ChainDataList = {3  1: {4    chainId: 1,5    chain: "ETH",6    network: "mainnet",7    networkId: 18  },9  2: {10    chainId: 2,11    chain: "EXP",12    network: "expanse",13    networkId: 114  },15  3: {16    chainId: 3,17    chain: "ETH",18    network: "ropsten",19    networkId: 320  },21  4: {22    chainId: 4,23    chain: "ETH",24    network: "rinkeby",25    networkId: 426  },27  5: {28    chainId: 5,29    chain: "ETH",30    network: "goerli",31    networkId: 532  },33  6: {34    chainId: 6,35    chain: "ETC",36    network: "kotti",37    networkId: 638  },39  8: {40    chainId: 8,41    chain: "UBQ",42    network: "ubiq",43    networkId: 8844  },45  9: {46    chainId: 9,47    chain: "UBQ",48    network: "ubiq-testnet",49    networkId: 250  },51  10: {52    chainId: 10,53    chain: "ETH",54    network: "optimism",55    networkId: 1056  },57  11: {58    chainId: 11,59    chain: "META",60    network: "metadium",61    networkId: 1162  },63  12: {64    chainId: 12,65    chain: "META",66    network: "metadium-testnet",67    networkId: 1268  },69  18: {70    chainId: 18,71    chain: "TST",72    network: "thundercore-testnet",73    networkId: 1874  },75  22: {76    chainId: 22,77    chain: "LYX",78    network: "lukso-l14-testnet",79    networkId: 2280  },81  23: {82    chainId: 23,83    chain: "LYX",84    network: "lukso-l15-testnet",85    networkId: 2386  },87  25: {88    chainId: 25,89    chain: "CRO",90    network: "cronos",91    networkId: 2592  },93  30: {94    chainId: 30,95    chain: "RSK",96    network: "rsk",97    networkId: 3098  },99  31: {100    chainId: 31,101    chain: "RSK",102    network: "rsk-testnet",103    networkId: 31104  },105  42: {106    chainId: 42,107    chain: "ETH",108    network: "kovan",109    networkId: 42110  },111  56: {112    chainId: 56,113    chain: "BSC",114    network: "binance",115    networkId: 56116  },117  60: {118    chainId: 60,119    chain: "GO",120    network: "gochain",121    networkId: 60122  },123  61: {124    chainId: 61,125    chain: "ETC",126    network: "etc",127    networkId: 1128  },129  62: {130    chainId: 62,131    chain: "ETC",132    network: "etc-morden",133    networkId: 2134  },135  63: {136    chainId: 63,137    chain: "ETC",138    network: "etc-testnet",139    networkId: 7140  },141  64: {142    chainId: 64,143    chain: "ELLA",144    network: "ellaism",145    networkId: 64146  },147  69: {148    chainId: 69,149    chain: "ETH",150    network: "optimism-kovan",151    networkId: 69152  },153  76: {154    chainId: 76,155    chain: "MIX",156    network: "mix",157    networkId: 76158  },159  77: {160    chainId: 77,161    chain: "POA",162    network: "poa-sokol",163    networkId: 77164  },165  88: {166    chainId: 88,167    chain: "TOMO",168    network: "tomochain",169    networkId: 88170  },171  97: {172    chainId: 97,173    chain: "BSC",174    network: "binance-testnet",175    networkId: 97176  },177  99: {178    chainId: 99,179    chain: "POA",180    network: "poa-core",181    networkId: 99182  },183  100: {184    chainId: 100,185    chain: "XDAI",186    network: "xdai",187    networkId: 100188  },189  101: {190    chainId: 101,191    chain: "ETI",192    network: "etherinc",193    networkId: 1194  },195  108: {196    chainId: 108,197    chain: "TT",198    network: "thundercore",199    networkId: 108200  },201  162: {202    chainId: 162,203    chain: "PHT",204    network: "sirius",205    networkId: 162206  },207  163: {208    chainId: 163,209    chain: "PHT",210    network: "lightstreams",211    networkId: 163212  },213  211: {214    chainId: 211,215    chain: "FTN",216    network: "freight",217    networkId: 0218  },219  250: {220    chainId: 250,221    chain: "FTM",222    network: "fantom",223    networkId: 250224  },225  269: {226    chainId: 269,227    chain: "HPB",228    network: "hpb",229    networkId: 100230  },231  338: {232    chainId: 338,233    chain: "CRO",234    network: "cronos-testnet",235    networkId: 338236  },237  385: {238    chainId: 385,239    chain: "CRO",240    network: "lisinski",241    networkId: 385242  },243  820: {244    chainId: 820,245    chain: "CLO",246    network: "callisto",247    networkId: 1248  },249  821: {250    chainId: 821,251    chain: "CLO",252    network: "callisto-testnet",253    networkId: 2254  },255  137: {256    chainId: 137,257    chain: "MATIC",258    network: "matic",259    networkId: 137260  },261  1284: {262    chainId: 1284,263    chain: "GLMR",264    network: "moonbeam",265    networkId: 1284266  },267  1285: {268    chainId: 1285,269    chain: "MOVR",270    network: "moonriver",271    networkId: 1285272  },273  42161: {274    chainId: 42161,275    chain: "ETH",276    network: "arbitrum",277    networkId: 42161278  },279  42220: {280    chainId: 42220,281    chain: "CELO",282    network: "celo",283    networkId: 42220284  },285  44787: {286    chainId: 44787,287    chain: "CELO",288    network: "celo-alfajores",289    networkId: 44787290  },291  62320: {292    chainId: 62320,293    chain: "CELO",294    network: "celo-baklava",295    networkId: 62320296  },297  80001: {298    chainId: 80001,299    chain: "MUMBAI",300    network: "mumbai",301    networkId: 80001302  },303  43113: {304    chainId: 43113,305    chain: "AVAX",306    network: "avalanche-fuji-testnet",307    networkId: 43113308  },309  43114: {310    chainId: 43114,311    chain: "AVAX",312    network: "avalanche-fuji-mainnet",313    networkId: 43114314  },315  246529: {316    chainId: 246529,317    chain: "ARTIS sigma1",318    network: "artis-s1",319    networkId: 246529320  },321  246785: {322    chainId: 246785,323    chain: "ARTIS tau1",324    network: "artis-t1",325    networkId: 246785326  },327  1007: {328    chainId: 1007,329    chain: "NewChain TestNet",330    network: "newchain-testnet",331    networkId: 1007332  },333  1012: {334    chainId: 1012,335    chain: "NewChain MainNet",336    network: "newchain-mainnet",337    networkId: 1012338  },339  421611: {340    chainId: 421611,341    chain: "ETH",342    network: "arbitrum-rinkeby",343    networkId: 421611344  },345  1666600000: {346    chainId: 1666600000,347    chain: "ONE",348    network: "harmony-shard1",349    networkId: 1666600000350  },351  1313161554: {352    chainId: 1313161554,353    chain: "AETH",354    network: "aurora",355    networkId: 1313161554356  }...Using AI Code Generation
1const synthetixioSynpress = require('synthetixio-synpress');2const network = synthetixioSynpress.network;3const synthetixioSynpress = require('synthetixio-synpress');4const synpress = synthetixioSynpress.synpress;5const network = synthetixioSynpress.network;6const network = require('synthetixio-synpress').network;7const synpress = require('synthetixio-synpress').synpress;8const network = require('synthetixio-synpress').network;9const synpress = require('synthetixio-synpress').synpress;10const synthetixioSynpress = require('synthetixio-synpress');11const synpress = synthetixioSynpress.synpress;12const network = synthetixioSynpress.network;13const network = require('synthetixio-synpress').network;14const synpress = require('synthetixio-synpress').synpress;15const network = require('synthetixio-synpress').network;16const synpress = require('synthetixio-synpress').synpress;17const synthetixioSynpress = require('synthetixio-synpress');18const synpress = synthetixioSynpress.synpress;19const network = synthetixioSynpress.network;20const network = require('synthetixio-synpress').network;21const synpress = require('synthetixio-synpress').synpress;22const network = require('synthetixio-synpress').network;23const synpress = require('synthetixio-synpress').synpress;24const synthetixioSynpress = require('synthetixio-synpress');25const synpress = synthetixioSynpress.synpress;26const network = synthetixioSynpress.network;27const network = require('synthetixio-synpress').network;28const synpress = require('synthetixio-synpress').synpress;29const network = require('synUsing AI Code Generation
1const { network } = require('synthetixio-synpress');2async function getPrice() {3  const price = await network.getPrice('ETH');4  console.log(price);5}6getPrice();7{8  priceBN: BigNumber { s: 1, e: 3, c: [ 168959 ] }9}10const { network } = require('synthetixio-synpress');11async function getPrice() {12  const price = await network.getPrice('ETH');13  console.log(price);14}15getPrice();16{17  priceBN: BigNumber { s: 1, e: 3, c: [ 168959 ] }18}19const { network } = require('synthetixio-synpress');20async function getPrice() {21  const price = await network.getPrice('ETH');22  console.log(price);23}24getPrice();25{26  priceBN: BigNumber { s: 1, e: 3, c: [ 168959 ] }27}28const { network } = require('synthetixio-synpress');29async function getPrice() {30  const price = await network.getPrice('ETH');31  console.log(price);32}33getPrice();34{Using AI Code Generation
1const Synpress = require("synpress");2const network = new Synpress.Network();3network.getExchangeRate("sUSD", "ETH").then((result) => {4  console.log(result);5});6const Synpress = require("synpress");7const network = new Synpress.Network();8network.getExchangeRate("sUSD", "ETH").then((result) => {9  console.log(result);10});11const Synpress = require("synpress");12const network = new Synpress.Network();13network.getExchangeRate("sUSD", "ETH").then((result) => {14  console.log(result);15});16const Synpress = require("synpress");17const network = new Synpress.Network();18network.getExchangeRate("sUSD", "ETH").then((result) => {19  console.log(result);20});Using AI Code Generation
1const { Synpress } = require('synthetixio-synpress');2const { Deployer } = require('synthetixio-contracts');3const Web3 = require('web3');4const HDWalletProvider = require('truffle-hdwallet-provider');5const { config } = require('./config.js');6const provider = new HDWalletProvider(7);8const web3 = new Web3(provider);9const network = 'ganache';10const synpress = new Synpress({11});12(async () => {13  const gasPrice = await synpress.getGasPrice();14  const deployer = new Deployer({15  });16  const deployment = await deployer.deploy({17  });18  console.log(deployment);19})();20{ SyntLearn 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!!
