filename
stringlengths 4
198
| content
stringlengths 25
939k
| environment
list | variablearg
list | constarg
list | variableargjson
stringclasses 1
value | constargjson
stringlengths 2
3.9k
| lang
stringclasses 3
values | constargcount
float64 0
129
⌀ | variableargcount
float64 0
0
⌀ | sentence
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|
hub.go | // Package eventhub provides functionality for interacting with Azure Event Hubs.
package eventhub
// MIT License
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE
import (
"context"
"encoding/xml"
"fmt"
"io/ioutil"
"net/http"
"os"
"path"
"sync"
"github.com/Azure/azure-amqp-common-go/aad"
"github.com/Azure/azure-amqp-common-go/auth"
"github.com/Azure/azure-amqp-common-go/conn"
"github.com/Azure/azure-amqp-common-go/log"
"github.com/Azure/azure-amqp-common-go/persist"
"github.com/Azure/azure-amqp-common-go/sas"
"github.com/Azure/azure-event-hubs-go/atom"
"github.com/Azure/azure-sdk-for-go/services/eventhub/mgmt/2017-04-01/eventhub"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/date"
"github.com/Azure/go-autorest/autorest/to"
)
const (
maxUserAgentLen = 128
rootUserAgent = "/golang-event-hubs"
// Version is the semantic version number
Version = "0.4.0"
)
type (
// Hub provides the ability to send and receive Event Hub messages
Hub struct {
name string
namespace *namespace
receivers map[string]*receiver
sender *sender
senderPartitionID *string
receiverMu sync.Mutex
senderMu sync.Mutex
offsetPersister persist.CheckpointPersister
userAgent string
}
// Handler is the function signature for any receiver of events
Handler func(ctx context.Context, event *Event) error
// Sender provides the ability to send a messages
Sender interface {
Send(ctx context.Context, event *Event, opts ...SendOption) error
SendBatch(ctx context.Context, batch *EventBatch, opts ...SendOption) error
}
// PartitionedReceiver provides the ability to receive messages from a given partition
PartitionedReceiver interface {
Receive(ctx context.Context, partitionID string, handler Handler, opts ...ReceiveOption) (ListenerHandle, error)
}
// Manager provides the ability to query management node information about a node
Manager interface {
GetRuntimeInformation(context.Context) (HubRuntimeInformation, error)
GetPartitionInformation(context.Context, string) (HubPartitionRuntimeInformation, error)
}
// HubOption provides structure for configuring new Event Hub instances
HubOption func(h *Hub) error
// HubManager provides CRUD functionality for Event Hubs
HubManager struct {
*entityManager
}
// HubEntity is the Azure Event Hub description of a Hub for management activities
HubEntity struct {
*HubDescription
Name string
}
// hubFeed is a specialized feed containing hubEntries
hubFeed struct {
*atom.Feed
Entries []hubEntry `xml:"entry"`
}
// hubEntry is a specialized Hub feed entry
hubEntry struct {
*atom.Entry
Content *hubContent `xml:"content"`
}
// hubContent is a specialized Hub body for an Atom entry
hubContent struct {
XMLName xml.Name `xml:"content"`
Type string `xml:"type,attr"`
HubDescription HubDescription `xml:"EventHubDescription"`
}
// HubDescription is the content type for Event Hub management requests
HubDescription struct {
XMLName xml.Name `xml:"EventHubDescription"`
MessageRetentionInDays *int32 `xml:"MessageRetentionInDays,omitempty"`
SizeInBytes *int64 `xml:"SizeInBytes,omitempty"`
Status *eventhub.EntityStatus `xml:"Status,omitempty"`
CreatedAt *date.Time `xml:"CreatedAt,omitempty"`
UpdatedAt *date.Time `xml:"UpdatedAt,omitempty"`
PartitionCount *int32 `xml:"PartitionCount,omitempty"`
PartitionIDs *[]string `xml:"PartitionIds>string,omitempty"`
EntityAvailabilityStatus *string `xml:"EntityAvailabilityStatus,omitempty"`
BaseEntityDescription
}
)
// NewHubManagerFromConnectionString builds a HubManager from an Event Hub connection string
func NewHubManagerFromConnectionString(connStr string) (*HubManager, error) {
ns, err := newNamespace(namespaceWithConnectionString(connStr))
if err != nil {
return nil, err
}
return &HubManager{
entityManager: newEntityManager(ns.getHTTPSHostURI(), ns.tokenProvider),
}, nil
}
// NewHubManagerFromAzureEnvironment builds a HubManager from a Event Hub name, SAS or AAD token provider and Azure Environment
func NewHubManagerFromAzureEnvironment(namespace string, tokenProvider auth.TokenProvider, env azure.Environment) (*HubManager, error) {
ns, err := newNamespace(namespaceWithAzureEnvironment(namespace, tokenProvider, env))
if err != nil {
return nil, err
}
return &HubManager{
entityManager: newEntityManager(ns.getHTTPSHostURI(), ns.tokenProvider),
}, nil
}
// Delete deletes an Event Hub entity by name
func (hm *HubManager) Delete(ctx context.Context, name string) error {
span, ctx := hm.startSpanFromContext(ctx, "eh.HubManager.Delete")
defer span.Finish()
res, err := hm.entityManager.Delete(ctx, "/"+name)
if res != nil {
defer res.Body.Close()
}
return err
}
// Put creates or updates an Event Hubs Hub
func (hm *HubManager) Put(ctx context.Context, name string, hd HubDescription) (*HubEntity, error) {
span, ctx := hm.startSpanFromContext(ctx, "eh.HubManager.Put")
defer span.Finish()
hd.ServiceBusSchema = to.StringPtr(serviceBusSchema)
he := &hubEntry{
Entry: &atom.Entry{
AtomSchema: atomSchema,
},
Content: &hubContent{
Type: applicationXML,
HubDescription: hd,
},
}
reqBytes, err := xml.Marshal(he)
if err != nil {
log.For(ctx).Error(err)
return nil, err
}
reqBytes = xmlDoc(reqBytes)
res, err := hm.entityManager.Put(ctx, "/"+name, reqBytes)
if res != nil {
defer res.Body.Close()
}
if err != nil {
log.For(ctx).Error(err)
return nil, err
}
b, err := ioutil.ReadAll(res.Body)
if err != nil {
log.For(ctx).Error(err)
return nil, err
}
var entry hubEntry
err = xml.Unmarshal(b, &entry)
if err != nil {
return nil, formatManagementError(b)
}
return hubEntryToEntity(&entry), nil
}
// List fetches all of the Hub for an Event Hubs Namespace
func (hm *HubManager) List(ctx context.Context) ([]*HubEntity, error) {
span, ctx := hm.startSpanFromContext(ctx, "eh.HubManager.List")
defer span.Finish()
res, err := hm.entityManager.Get(ctx, `/$Resources/EventHubs`)
if res != nil {
defer res.Body.Close()
}
if err != nil {
log.For(ctx).Error(err)
return nil, err
}
b, err := ioutil.ReadAll(res.Body)
if err != nil {
log.For(ctx).Error(err)
return nil, err
}
var feed hubFeed
err = xml.Unmarshal(b, &feed)
if err != nil {
return nil, formatManagementError(b)
}
qd := make([]*HubEntity, len(feed.Entries))
for idx, entry := range feed.Entries {
qd[idx] = hubEntryToEntity(&entry)
}
return qd, nil
}
// Get fetches an Event Hubs Hub entity by name
func (hm *HubManager) Get(ctx context.Context, name string) (*HubEntity, error) {
span, ctx := hm.startSpanFromContext(ctx, "eh.HubManager.Get")
defer span.Finish()
res, err := hm.entityManager.Get(ctx, name)
if res != nil {
defer res.Body.Close()
}
if err != nil {
log.For(ctx).Error(err)
return nil, err
}
if res.StatusCode == http.StatusNotFound {
return nil, nil
}
b, err := ioutil.ReadAll(res.Body)
if err != nil {
log.For(ctx).Error(err)
return nil, err
}
var entry hubEntry
err = xml.Unmarshal(b, &entry)
if err != nil {
if isEmptyFeed(b) {
return nil, nil
}
return nil, formatManagementError(b)
}
return hubEntryToEntity(&entry), nil
}
func isEmptyFeed(b []byte) bool {
var emptyFeed hubFeed
feedErr := xml.Unmarshal(b, &emptyFeed)
return feedErr == nil && emptyFeed.Title == "Publicly Listed Services"
}
func hubEntryToEntity(entry *hubEntry) *HubEntity {
return &HubEntity{
HubDescription: &entry.Content.HubDescription,
Name: entry.Title,
}
}
// NewHub creates a new Event Hub client for sending and receiving messages
func NewHub(namespace, name string, tokenProvider auth.TokenProvider, opts ...HubOption) (*Hub, error) {
ns, err := newNamespace(namespaceWithAzureEnvironment(namespace, tokenProvider, azure.PublicCloud))
if err != nil {
return nil, err
}
h := &Hub{
name: name,
namespace: ns,
offsetPersister: persist.NewMemoryPersister(),
userAgent: rootUserAgent,
receivers: make(map[string]*receiver),
}
for _, opt := range opts {
err := opt(h)
if err != nil {
return nil, err
}
}
return h, nil
}
// NewHubWithNamespaceNameAndEnvironment creates a new Event Hub client for sending and receiving messages from
// environment variables with supplied namespace and name which will attempt to build a token provider from
// environment variables. If unable to build a AAD Token Provider it will fall back to a SAS token provider. If neither
// can be built, it will return error.
//
// SAS TokenProvider environment variables:
// There are two sets of environment variables which can produce a SAS TokenProvider
//
// 1) Expected Environment Variables:
// - "EVENTHUB_KEY_NAME" the name of the Event Hub key
// - "EVENTHUB_KEY_VALUE" the secret for the Event Hub key named in "EVENTHUB_KEY_NAME"
//
// 2) Expected Environment Variable:
// - "EVENTHUB_CONNECTION_STRING" connection string from the Azure portal
//
//
// AAD TokenProvider environment variables:
// 1. client Credentials: attempt to authenticate with a Service Principal via "AZURE_TENANT_ID", "AZURE_CLIENT_ID" and
// "AZURE_CLIENT_SECRET"
//
// 2. client Certificate: attempt to authenticate with a Service Principal via "AZURE_TENANT_ID", "AZURE_CLIENT_ID",
// "AZURE_CERTIFICATE_PATH" and "AZURE_CERTIFICATE_PASSWORD"
//
// 3. Managed Service Identity (MSI): attempt to authenticate via MSI on the default local MSI internally addressable IP
// and port. See: adal.GetMSIVMEndpoint()
//
//
// The Azure Environment used can be specified using the name of the Azure Environment set in "AZURE_ENVIRONMENT" var.
func NewHubWithNamespaceNameAndEnvironment(namespace, name string, opts ...HubOption) (*Hub, error) {
var provider auth.TokenProvider
provider, sasErr := sas.NewTokenProvider(sas.TokenProviderWithEnvironmentVars())
if sasErr == nil {
return NewHub(namespace, name, provider, opts...)
}
provider, aadErr := aad.NewJWTProvider(aad.JWTProviderWithEnvironmentVars())
if aadErr == nil {
return NewHub(namespace, name, provider, opts...)
}
return nil, fmt.Errorf("neither Azure Active Directory nor SAS token provider could be built - AAD error: %v, SAS error: %v", aadErr, sasErr)
}
// NewHubFromEnvironment creates a new Event Hub client for sending and receiving messages from environment variables
//
// Expected Environment Variables:
// - "EVENTHUB_NAMESPACE" the namespace of the Event Hub instance
// - "EVENTHUB_NAME" the name of the Event Hub instance
//
//
// This method depends on NewHubWithNamespaceNameAndEnvironment which will attempt to build a token provider from
// environment variables. If unable to build a AAD Token Provider it will fall back to a SAS token provider. If neither
// can be built, it will return error.
//
// SAS TokenProvider environment variables:
// There are two sets of environment variables which can produce a SAS TokenProvider
//
// 1) Expected Environment Variables:
// - "EVENTHUB_NAMESPACE" the namespace of the Event Hub instance
// - "EVENTHUB_KEY_NAME" the name of the Event Hub key
// - "EVENTHUB_KEY_VALUE" the secret for the Event Hub key named in "EVENTHUB_KEY_NAME"
//
// 2) Expected Environment Variable:
// - "EVENTHUB_CONNECTION_STRING" connection string from the Azure portal
//
//
// AAD TokenProvider environment variables:
// 1. client Credentials: attempt to authenticate with a Service Principal via "AZURE_TENANT_ID", "AZURE_CLIENT_ID" and
// "AZURE_CLIENT_SECRET"
//
// 2. client Certificate: attempt to authenticate with a Service Principal via "AZURE_TENANT_ID", "AZURE_CLIENT_ID",
// "AZURE_CERTIFICATE_PATH" and "AZURE_CERTIFICATE_PASSWORD"
//
// 3. Managed Service Identity (MSI): attempt to authenticate via MSI
//
//
// The Azure Environment used can be specified using the name of the Azure Environment set in "AZURE_ENVIRONMENT" var.
func NewHubFromEnvironment(opts ...HubOption) (*Hub, error) {
const envErrMsg = "environment var %s must not be empty"
var namespace, name string
if namespace = os.Getenv("EVENTHUB_NAMESPACE"); namespace == "" {
return nil, fmt.Errorf(envErrMsg, "EVENTHUB_NAMESPACE")
}
if name = os.Getenv("EVENTHUB_NAME"); name == "" {
return nil, fmt.Errorf(envErrMsg, "EVENTHUB_NAME")
}
return NewHubWithNamespaceNameAndEnvironment(namespace, name, opts...)
}
// NewHubFromConnectionString creates a new Event Hub client for sending and receiving messages from a connection string
// formatted like the following:
//
// Endpoint=sb://namespace.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=superSecret1234=;EntityPath=hubName
func NewHubFromConnectionString(connStr string, opts ...HubOption) (*Hub, error) {
parsed, err := conn.ParsedConnectionFromStr(connStr)
if err != nil {
return nil, err
}
ns, err := newNamespace(namespaceWithConnectionString(connStr))
if err != nil {
return nil, err
}
h := &Hub{
name: parsed.HubName,
namespace: ns,
offsetPersister: persist.NewMemoryPersister(),
userAgent: rootUserAgent,
receivers: make(map[string]*receiver),
}
for _, opt := range opts {
err := opt(h)
if err != nil {
return nil, err
}
}
return h, err
}
// GetRuntimeInformation fetches runtime information from the Event Hub management node
func (h *Hub) GetRuntimeInformation(ctx context.Context) (*HubRuntimeInformation, error) {
span, ctx := h.startSpanFromContext(ctx, "eh.Hub.GetRuntimeInformation")
defer span.Finish()
client := newClient(h.namespace, h.name)
conn, err := h.namespace.newConnection()
if err != nil {
log.For(ctx).Error(err)
return nil, err
}
info, err := client.GetHubRuntimeInformation(ctx, conn)
if err != nil {
log.For(ctx).Error(err)
return nil, err
}
return info, nil
}
// GetPartitionInformation fetches runtime information about a specific partition from the Event Hub management node
func (h *Hub) GetPartitionInformation(ctx context.Context, partitionID string) (*HubPartitionRuntimeInformation, error) {
span, ctx := h.startSpanFromContext(ctx, "eh.Hub.GetPartitionInformation")
defer span.Finish()
client := newClient(h.namespace, h.name)
conn, err := h.namespace.newConnection()
if err != nil {
return nil, err
}
info, err := client.GetHubPartitionRuntimeInformation(ctx, conn, partitionID)
if err != nil {
return nil, err
}
return info, nil
}
// Close drains and closes all of the existing senders, receivers and connections
func (h *Hub) Close(ctx context.Context) error {
span, ctx := h.startSpanFromContext(ctx, "eh.Hub.Close")
defer span.Finish()
var lastErr error
for _, r := range h.receivers {
if err := r.Close(ctx); err != nil {
log.For(ctx).Error(err)
lastErr = err
}
}
return lastErr
}
// Receive subscribes for messages sent to the provided entityPath.
func (h *Hub) Receive(ctx context.Context, partitionID string, handler Handler, opts ...ReceiveOption) (*ListenerHandle, error) {
span, ctx := h.startSpanFromContext(ctx, "eh.Hub.Receive")
defer span.Finish()
h.receiverMu.Lock()
defer h.receiverMu.Unlock()
receiver, err := h.newReceiver(ctx, partitionID, opts...)
if err != nil {
return nil, err
}
// Todo: change this to use name rather than identifier
if r, ok := h.receivers[receiver.getIdentifier()]; ok {
if err := r.Close(ctx); err != nil {
log.For(ctx).Error(err)
}
}
h.receivers[receiver.getIdentifier()] = receiver
listenerContext := receiver.Listen(handler)
return listenerContext, nil
}
// Send sends an event to the Event Hub
func (h *Hub) Send(ctx context.Context, event *Event, opts ...SendOption) error {
span, ctx := h.startSpanFromContext(ctx, "eh.Hub.Send")
defer span.Finish()
sender, err := h.getSender(ctx)
if err != nil {
return err
}
return sender.Send(ctx, event, opts...)
}
// SendBatch sends an EventBatch to the Event Hub
func (h *Hub) SendBatch(ctx context.Context, batch *EventBatch, opts ...SendOption) error {
span, ctx := h.startSpanFromContext(ctx, "eh.Hub.SendBatch")
defer span.Finish()
sender, err := h.getSender(ctx)
if err != nil {
return err
}
event, err := batch.toEvent()
if err != nil {
return err
}
return sender.Send(ctx, event, opts...)
}
// HubWithPartitionedSender configures the Hub instance to send to a specific event Hub partition
func HubWithPartitionedSender(partitionID string) HubOption {
return func(h *Hub) error {
h.senderPartitionID = &partitionID
return nil
}
}
// HubWithOffsetPersistence configures the Hub instance to read and write offsets so that if a Hub is interrupted, it
// can resume after the last consumed event.
func HubWithOffsetPersistence(offsetPersister persist.CheckpointPersister) HubOption {
return func(h *Hub) error {
h.offsetPersister = offsetPersister
return nil
}
}
// HubWithUserAgent configures the Hub to append the given string to the user agent sent to the server
//
// This option can be specified multiple times to add additional segments.
//
// Max user agent length is specified by the const maxUserAgentLen.
func HubWithUserAgent(userAgent string) HubOption {
return func(h *Hub) error {
return h.appendAgent(userAgent)
}
}
// HubWithEnvironment configures the Hub to use the specified environment.
//
// By default, the Hub instance will use Azure US Public cloud environment
func HubWithEnvironment(env azure.Environment) HubOption {
return func(h *Hub) error {
h.namespace.host = "amqps://" + h.namespace.name + "." + env.ServiceBusEndpointSuffix
return nil
}
}
func (h *Hub) appendAgent(userAgent string) error {
ua := path.Join(h.userAgent, userAgent)
if len(ua) > maxUserAgentLen {
return fmt.Errorf("user agent string has surpassed the max length of %d", maxUserAgentLen)
}
h.userAgent = ua
return nil
}
func (h *Hub) getSender(ctx context.Context) (*sender, error) {
h.senderMu.Lock()
defer h.senderMu.Unlock()
span, ctx := h.startSpanFromContext(ctx, "eh.Hub.getSender")
defer span.Finish()
if h.sender == nil {
s, err := h.newSender(ctx)
if err != nil {
log.For(ctx).Error(err)
return nil, err
}
h.sender = s
}
return h.sender, nil
}
| [
"\"EVENTHUB_NAMESPACE\"",
"\"EVENTHUB_NAME\""
]
| []
| [
"EVENTHUB_NAMESPACE",
"EVENTHUB_NAME"
]
| [] | ["EVENTHUB_NAMESPACE", "EVENTHUB_NAME"] | go | 2 | 0 | |
TEST/neural_network/test_nn.py | ######################################################
#
# PyRAI2MD test neural network
#
# Author Jingbai Li
# Oct 11 2021
#
######################################################
import os, sys, shutil, json, subprocess
def TestNN():
""" neural network test
1. energy grad nac training and prediction
2. energy grad soc training and prediction
"""
pyrai2mddir = os.environ['PYRAI2MD']
testdir = '%s/neural_network' % (os.getcwd())
record = {
'egn' : 'FileNotFound',
'egs' : 'FileNotFound',
'permute' : 'FileNotFound',
'invd' : 'FileNotFound',
'egn_train' : 'FileNotFound',
'egn_predict' : 'FileNotFound',
'egs_train' : 'FileNotFound',
'egs_predict' : 'FileNotFound',
}
filepath = '%s/TEST/neural_network/train_data/egn.json' % (pyrai2mddir)
if os.path.exists(filepath):
record['egn'] = filepath
filepath = '%s/TEST/neural_network/train_data/egs.json' % (pyrai2mddir)
if os.path.exists(filepath):
record['egs'] = filepath
filepath = '%s/TEST/neural_network/train_data/allpath' % (pyrai2mddir)
if os.path.exists(filepath):
record['permute'] = filepath
filepath = '%s/TEST/neural_network/train_data/invd' % (pyrai2mddir)
if os.path.exists(filepath):
record['invd'] = filepath
filepath = '%s/TEST/neural_network/train_data/egn_train' % (pyrai2mddir)
if os.path.exists(filepath):
record['egn_train'] = filepath
filepath = '%s/TEST/neural_network/train_data/egn_predict' % (pyrai2mddir)
if os.path.exists(filepath):
record['egn_predict'] = filepath
filepath = '%s/TEST/neural_network/train_data/egs_train' % (pyrai2mddir)
if os.path.exists(filepath):
record['egs_train'] = filepath
filepath = '%s/TEST/neural_network/train_data/egs_predict' % (pyrai2mddir)
if os.path.exists(filepath):
record['egs_predict'] = filepath
summary = """
*---------------------------------------------------*
| |
| Neural Network Test Calculation |
| |
*---------------------------------------------------*
Check files and settings:
-------------------------------------------------------
"""
for key, location in record.items():
summary += ' %-10s %s\n' % (key, location)
for key, location in record.items():
if location == 'FileNotFound':
summary += '\n Test files are incomplete, please download it again, skip test\n\n'
return summary, 'FAILED(test file unavailable)'
if location == 'VariableNotFound':
summary += '\n Environment variables are not set, cannot find program, skip test\n\n'
return summary, 'FAILED(enviroment variable missing)'
CopyInput(record, testdir)
summary += """
Copy files:
%-10s --> %s/egn.json
%-10s --> %s/egs.json
%-10s --> %s/allpath
%-10s --> %s/invd
%-10s --> %s/egn_train
%-10s --> %s/egn_predict
%-10s --> %s/egs_train
%-10s --> %s/egs_predict
Run MOLCAS CASSCF:
""" % ('egn', testdir,
'egs', testdir,
'permute', testdir,
'invd', testdir,
'egn_train', testdir,
'egn_predict', testdir,
'egs_train', testdir,
'egs_predict', testdir)
results, code = RunNN(record, testdir, pyrai2mddir)
summary += """
-------------------------------------------------------
Neural Networks OUTPUT
-------------------------------------------------------
%s
-------------------------------------------------------
""" % (results)
return summary, code
def CopyInput(record, testdir):
if os.path.exists(testdir) == False:
os.makedirs(testdir)
shutil.copy2(record['egn'], '%s/egn.json' % (testdir))
shutil.copy2(record['egs'], '%s/egs.json' % (testdir))
shutil.copy2(record['permute'], '%s/allpath' % (testdir))
shutil.copy2(record['invd'], '%s/invd' % (testdir))
shutil.copy2(record['egn_train'], '%s/egn_train' % (testdir))
shutil.copy2(record['egn_predict'], '%s/egn_predict' % (testdir))
shutil.copy2(record['egs_train'], '%s/egs_train' % (testdir))
shutil.copy2(record['egs_predict'], '%s/egs_predict' % (testdir))
def Collect(testdir, title):
with open('%s/NN-%s.log' % (testdir, title), 'r') as logfile:
log = logfile.read().splitlines()
for n, line in enumerate(log):
if """ Number of atoms:""" in line:
results = log[n - 1:]
break
results = '\n'.join(results) + '\n'
return results
def Check(testdir):
with open('%s/max_abs_dev.txt' % (testdir), 'r') as logfile:
log = logfile.read().splitlines()
results = """%s
...
%s
""" % ( '\n'.join(log[:10]), '\n'.join(log[-10:]))
return results
def RunNN(record, testdir, pyrai2mddir):
maindir = os.getcwd()
results = ''
os.chdir(testdir)
subprocess.run('python3 %s/pyrai2md.py egn_train > stdout_egn' % (pyrai2mddir), shell = True)
os.chdir(maindir)
tmp = Collect(testdir, 'egn')
results += tmp
if len(tmp.splitlines()) < 10:
code = 'FAILED(egn training runtime error)'
return results, code
else:
results += ' egn training done, entering egn prediction...\n'
os.chdir(testdir)
subprocess.run('python3 %s/pyrai2md.py egn_predict >> stdout_egn' % (pyrai2mddir), shell = True)
os.chdir(maindir)
tmp = Check(testdir)
results += tmp
if len(tmp.splitlines()) < 10:
code = 'FAILED(egn prediction runtime error)'
return results, code
else:
results += ' egn prediction done, entering egs training...\n'
os.chdir(testdir)
subprocess.run('python3 %s/pyrai2md.py egs_train > stdout_egs' % (pyrai2mddir), shell = True)
os.chdir(maindir)
tmp = Collect(testdir, 'egs')
results += tmp
if len(tmp.splitlines()) < 10:
code = 'FAILED(egn training runtime error)'
return results, code
else:
results += ' egs training done, entering egs prediction...\n'
os.chdir(testdir)
subprocess.run('python3 %s/pyrai2md.py egs_predict >> stdout_egs' % (pyrai2mddir), shell = True)
os.chdir(maindir)
tmp = Check(testdir)
results += tmp
if len(tmp.splitlines()) < 10:
code = 'FAILED(egs prediction runtime error)'
return results, code
else:
code = 'PASSED'
results += ' egs prediction done\n'
return results, code
| []
| []
| [
"PYRAI2MD"
]
| [] | ["PYRAI2MD"] | python | 1 | 0 | |
lambda-functions/block-credit-card/lambda_function.py | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 22 2020
@author: Michael Wallner (Amazon Web Services)
@email: [email protected]
"""
# Import libraries
import os
import json
import boto3
from boto3.dynamodb.conditions import Key, Attr
# DynamoDB client
dynamodb = boto3.resource('dynamodb')
# Global table name
TABLE = dynamodb.Table(os.getenv('TABLE_NAME'))
def block_credit_card(customer):
"""Read customer and flag her/his credit card as blocked.
Args:
customer (str): the unique customer identifier
Returns:
response (json): the boto3 response
Examples:
>>> response = block_credit_card(customer="abc-42")
"""
# Query customer records based on partition key
result_map = TABLE.query(KeyConditionExpression=Key('customer_id').eq(customer))["Items"][0]
# Over-write the card being blocked
result_map["is_blocked"] = True
# Put item with credit card being blocked
response = TABLE.put_item(Item=result_map)
# Troubleshhoting
print("block_credit_card response:", response)
return response
def lambda_handler(event, context):
"""Main entry function.
Args:
event (json): events coming from Amazon Connect
context (json): context attributes
Returns:
output (json): returning success or failure
Examples:
>>> output = lambda_handler(event={...}, context={...})
"""
# Debugging
print("Event from Amazon Connect:", event)
try:
# Get event values (especially customer id)
result_map = event["Details"]["ContactData"]["Attributes"]
customer = result_map["Customer"]
# Block the credit card
response = block_credit_card(customer=customer)
output = {
'statusCode': 200,
'body': "Success!"
}
except:
output = {
'statusCode': 400,
'body': "Bad Request!"
}
return output | []
| []
| [
"TABLE_NAME"
]
| [] | ["TABLE_NAME"] | python | 1 | 0 | |
schema/openfaas/v1alpha2/crd.go | // Copyright (c) OpenFaaS Author(s) 2018. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
package v1alpha2
import (
"github.com/openfaas/faas-cli/schema"
"github.com/openfaas/faas-cli/stack"
)
//APIVersionLatest latest API version of CRD
const APIVersionLatest = "openfaas.com/v1alpha2"
//Spec describe characteristics of the object
type Spec struct {
//Name name of the function
Name string `yaml:"name"`
//Image docker image name of the function
Image string `yaml:"image"`
Environment map[string]string `yaml:"environment,omitempty"`
Labels *map[string]string `yaml:"labels,omitempty"`
//Limits for the function
Limits *stack.FunctionResources `yaml:"limits,omitempty"`
//Requests of resources requested by function
Requests *stack.FunctionResources `yaml:"requests,omitempty"`
Constraints *[]string `yaml:"constraints,omitempty"`
//Secrets list of secrets to be made available to function
Secrets []string `yaml:"secrets,omitempty"`
}
//CRD root level YAML definition for the object
type CRD struct {
//APIVersion CRD API version
APIVersion string `yaml:"apiVersion"`
//Kind kind of the object
Kind string `yaml:"kind"`
Metadata schema.Metadata `yaml:"metadata"`
Spec Spec `yaml:"spec"`
}
| []
| []
| []
| [] | [] | go | null | null | null |
paper/alds/script/load_networks.py | # %%
from __future__ import print_function
# make sure the setup is correct everywhere
import os
import sys
# change working directory to src
from IPython import get_ipython
import experiment
from experiment.util.file import get_parameters
# make sure it's using only GPU here...
os.environ["CUDA_VISIBLE_DEVICES"] = "0" # noqa
# switch to root folder for data
folder = os.path.abspath("")
if "paper/alds/script" in folder:
src_folder = os.path.join(folder, "../../..")
os.chdir(src_folder)
# %% define a few parameters
# experiment file for which to retrieve networks
FILE = "paper/alds/param/cifar/retrain/resnet20.yaml"
# specific network to retrieve
# check out parameter file for available methods.
METHOD_REF = "ReferenceNet" # unpruned network
METHOD = "ALDSNet" # our method
TARGET_PR = 0.5 # get the target prune ratio
N_IDX = 0 # repetition index (0,1,2)
# %% make sure matplotlib works correctly
IN_JUPYTER = True
try:
get_ipython().run_line_magic("matplotlib", "inline")
except AttributeError:
IN_JUPYTER = False
# %% a couple of convenience functions
def get_results(file, logger):
"""Grab all the results according to the parameter file."""
# Loop through all experiments
for param in get_parameters(file, 1, 0):
# initialize logger and setup parameters
logger.initialize_from_param(param)
# get evaluator
evaluator = experiment.Evaluator(logger)
# run the experiment (only if necessary)
try:
state = logger.get_global_state()
except ValueError:
evaluator.run()
state = logger.get_global_state()
# extract the results
return evaluator, state
# %% initialize and get results
# get a logger and evaluator
LOGGER = experiment.Logger()
# get the results from the prune experiment
# you can check out the different stats from there
EVALUATOR, RESULTS = get_results(FILE, LOGGER)
# %% load a specific network and test it
# now try loading a network according to the desired parameters
NET_HANDLE = EVALUATOR.get_by_pr(
prune_ratio=TARGET_PR, method=METHOD, n_idx=N_IDX
)
DEVICE = EVALUATOR._device
# retrieve the reference network as well and test it.
NET_ORIGINAL = EVALUATOR.get_by_pr(
prune_ratio=TARGET_PR, method=METHOD_REF, n_idx=N_IDX
).compressed_net
# reset stdout after our logger modifies it so we can see printing
sys.stdout = sys.stdout._stdout_original
# %% test the networks and print accuracy
NET_HANDLE = NET_HANDLE.to(DEVICE)
LOSS, ACC1, ACC5 = EVALUATOR._net_trainer.test(NET_HANDLE)
NET_HANDLE.to("cpu")
print(
"Pruned network: "
f"size: {NET_HANDLE.size()}, loss: {LOSS:.3f}, "
f"acc1: {ACC1:.3f}, acc5: {ACC5:.3f}"
)
NET_ORIGINAL.to(DEVICE)
LOSS_ORIG, ACC1_ORIG, ACC5_ORIG = EVALUATOR._net_trainer.test(NET_HANDLE)
NET_ORIGINAL.to("cpu")
print(
"Original network: "
f"size: {NET_ORIGINAL.size()}, loss: {LOSS_ORIG:.3f}, "
f"acc1: {ACC1_ORIG:.3f}, acc5: {ACC5_ORIG:.3f}"
) | []
| []
| [
"CUDA_VISIBLE_DEVICES"
]
| [] | ["CUDA_VISIBLE_DEVICES"] | python | 1 | 0 | |
accelbyte_py_sdk/api/social/operations/user_statistic/get_user_stat_items.py | # Copyright (c) 2021 AccelByte Inc. All Rights Reserved.
# This is licensed software from AccelByte Inc, for limitations
# and restrictions contact your company contract manager.
#
# Code generated. DO NOT EDIT!
# template file: justice_py_sdk_codegen/__main__.py
# pylint: disable=duplicate-code
# pylint: disable=line-too-long
# pylint: disable=missing-function-docstring
# pylint: disable=missing-module-docstring
# pylint: disable=too-many-arguments
# pylint: disable=too-many-branches
# pylint: disable=too-many-instance-attributes
# pylint: disable=too-many-lines
# pylint: disable=too-many-locals
# pylint: disable=too-many-public-methods
# pylint: disable=too-many-return-statements
# pylint: disable=too-many-statements
# pylint: disable=unused-import
# justice-social-service (1.29.2)
from __future__ import annotations
from typing import Any, Dict, List, Optional, Tuple, Union
from .....core import Operation
from .....core import HeaderStr
from .....core import HttpResponse
from ...models import UserStatItemPagingSlicedResult
class GetUserStatItems(Operation):
"""List user's statItems (getUserStatItems)
List user's statItems.
Other detail info:
* Required permission : resource="ADMIN:NAMESPACE:{namespace}:USER:{userId}:STATITEM", action=2 (READ)
* Returns : stat items
Required Permission(s):
- ADMIN:NAMESPACE:{namespace}:USER:{userId}:STATITEM [READ]
Properties:
url: /social/v1/admin/namespaces/{namespace}/users/{userId}/statitems
method: GET
tags: ["UserStatistic"]
consumes: []
produces: ["application/json"]
securities: [BEARER_AUTH] or [BEARER_AUTH]
namespace: (namespace) REQUIRED str in path
user_id: (userId) REQUIRED str in path
limit: (limit) OPTIONAL int in query
offset: (offset) OPTIONAL int in query
stat_codes: (statCodes) OPTIONAL str in query
tags: (tags) OPTIONAL str in query
Responses:
200: OK - UserStatItemPagingSlicedResult (successful operation)
"""
# region fields
_url: str = "/social/v1/admin/namespaces/{namespace}/users/{userId}/statitems"
_method: str = "GET"
_consumes: List[str] = []
_produces: List[str] = ["application/json"]
_securities: List[List[str]] = [["BEARER_AUTH"], ["BEARER_AUTH"]]
_location_query: str = None
namespace: str # REQUIRED in [path]
user_id: str # REQUIRED in [path]
limit: int # OPTIONAL in [query]
offset: int # OPTIONAL in [query]
stat_codes: str # OPTIONAL in [query]
tags: str # OPTIONAL in [query]
# endregion fields
# region properties
@property
def url(self) -> str:
return self._url
@property
def method(self) -> str:
return self._method
@property
def consumes(self) -> List[str]:
return self._consumes
@property
def produces(self) -> List[str]:
return self._produces
@property
def securities(self) -> List[List[str]]:
return self._securities
@property
def location_query(self) -> str:
return self._location_query
# endregion properties
# region get methods
# endregion get methods
# region get_x_params methods
def get_all_params(self) -> dict:
return {
"path": self.get_path_params(),
"query": self.get_query_params(),
}
def get_path_params(self) -> dict:
result = {}
if hasattr(self, "namespace"):
result["namespace"] = self.namespace
if hasattr(self, "user_id"):
result["userId"] = self.user_id
return result
def get_query_params(self) -> dict:
result = {}
if hasattr(self, "limit"):
result["limit"] = self.limit
if hasattr(self, "offset"):
result["offset"] = self.offset
if hasattr(self, "stat_codes"):
result["statCodes"] = self.stat_codes
if hasattr(self, "tags"):
result["tags"] = self.tags
return result
# endregion get_x_params methods
# region is/has methods
# endregion is/has methods
# region with_x methods
def with_namespace(self, value: str) -> GetUserStatItems:
self.namespace = value
return self
def with_user_id(self, value: str) -> GetUserStatItems:
self.user_id = value
return self
def with_limit(self, value: int) -> GetUserStatItems:
self.limit = value
return self
def with_offset(self, value: int) -> GetUserStatItems:
self.offset = value
return self
def with_stat_codes(self, value: str) -> GetUserStatItems:
self.stat_codes = value
return self
def with_tags(self, value: str) -> GetUserStatItems:
self.tags = value
return self
# endregion with_x methods
# region to methods
def to_dict(self, include_empty: bool = False) -> dict:
result: dict = {}
if hasattr(self, "namespace") and self.namespace:
result["namespace"] = str(self.namespace)
elif include_empty:
result["namespace"] = ""
if hasattr(self, "user_id") and self.user_id:
result["userId"] = str(self.user_id)
elif include_empty:
result["userId"] = ""
if hasattr(self, "limit") and self.limit:
result["limit"] = int(self.limit)
elif include_empty:
result["limit"] = 0
if hasattr(self, "offset") and self.offset:
result["offset"] = int(self.offset)
elif include_empty:
result["offset"] = 0
if hasattr(self, "stat_codes") and self.stat_codes:
result["statCodes"] = str(self.stat_codes)
elif include_empty:
result["statCodes"] = ""
if hasattr(self, "tags") and self.tags:
result["tags"] = str(self.tags)
elif include_empty:
result["tags"] = ""
return result
# endregion to methods
# region response methods
# noinspection PyMethodMayBeStatic
def parse_response(self, code: int, content_type: str, content: Any) -> Tuple[Union[None, UserStatItemPagingSlicedResult], Union[None, HttpResponse]]:
"""Parse the given response.
200: OK - UserStatItemPagingSlicedResult (successful operation)
---: HttpResponse (Undocumented Response)
---: HttpResponse (Unexpected Content-Type Error)
---: HttpResponse (Unhandled Error)
"""
pre_processed_response, error = self.pre_process_response(code=code, content_type=content_type, content=content)
if error is not None:
return None, None if error.is_no_content() else error
code, content_type, content = pre_processed_response
if code == 200:
return UserStatItemPagingSlicedResult.create_from_dict(content), None
return None, self.handle_undocumented_response(code=code, content_type=content_type, content=content)
# endregion response methods
# region static methods
@classmethod
def create(
cls,
namespace: str,
user_id: str,
limit: Optional[int] = None,
offset: Optional[int] = None,
stat_codes: Optional[str] = None,
tags: Optional[str] = None,
) -> GetUserStatItems:
instance = cls()
instance.namespace = namespace
instance.user_id = user_id
if limit is not None:
instance.limit = limit
if offset is not None:
instance.offset = offset
if stat_codes is not None:
instance.stat_codes = stat_codes
if tags is not None:
instance.tags = tags
return instance
@classmethod
def create_from_dict(cls, dict_: dict, include_empty: bool = False) -> GetUserStatItems:
instance = cls()
if "namespace" in dict_ and dict_["namespace"] is not None:
instance.namespace = str(dict_["namespace"])
elif include_empty:
instance.namespace = ""
if "userId" in dict_ and dict_["userId"] is not None:
instance.user_id = str(dict_["userId"])
elif include_empty:
instance.user_id = ""
if "limit" in dict_ and dict_["limit"] is not None:
instance.limit = int(dict_["limit"])
elif include_empty:
instance.limit = 0
if "offset" in dict_ and dict_["offset"] is not None:
instance.offset = int(dict_["offset"])
elif include_empty:
instance.offset = 0
if "statCodes" in dict_ and dict_["statCodes"] is not None:
instance.stat_codes = str(dict_["statCodes"])
elif include_empty:
instance.stat_codes = ""
if "tags" in dict_ and dict_["tags"] is not None:
instance.tags = str(dict_["tags"])
elif include_empty:
instance.tags = ""
return instance
@staticmethod
def get_field_info() -> Dict[str, str]:
return {
"namespace": "namespace",
"userId": "user_id",
"limit": "limit",
"offset": "offset",
"statCodes": "stat_codes",
"tags": "tags",
}
@staticmethod
def get_required_map() -> Dict[str, bool]:
return {
"namespace": True,
"userId": True,
"limit": False,
"offset": False,
"statCodes": False,
"tags": False,
}
# endregion static methods
| []
| []
| []
| [] | [] | python | null | null | null |
cmd/gardener-extension-provider-openstack/app/app.go | // Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package app
import (
"context"
"fmt"
"os"
druidv1alpha1 "github.com/gardener/etcd-druid/api/v1alpha1"
openstackinstall "github.com/gardener/gardener-extension-provider-openstack/pkg/apis/openstack/install"
openstackcmd "github.com/gardener/gardener-extension-provider-openstack/pkg/cmd"
openstackbackupbucket "github.com/gardener/gardener-extension-provider-openstack/pkg/controller/backupbucket"
openstackbackupentry "github.com/gardener/gardener-extension-provider-openstack/pkg/controller/backupentry"
openstackcontrolplane "github.com/gardener/gardener-extension-provider-openstack/pkg/controller/controlplane"
"github.com/gardener/gardener-extension-provider-openstack/pkg/controller/healthcheck"
openstackinfrastructure "github.com/gardener/gardener-extension-provider-openstack/pkg/controller/infrastructure"
openstackworker "github.com/gardener/gardener-extension-provider-openstack/pkg/controller/worker"
"github.com/gardener/gardener-extension-provider-openstack/pkg/openstack"
openstackcontrolplaneexposure "github.com/gardener/gardener-extension-provider-openstack/pkg/webhook/controlplaneexposure"
"github.com/gardener/gardener/extensions/pkg/controller"
controllercmd "github.com/gardener/gardener/extensions/pkg/controller/cmd"
"github.com/gardener/gardener/extensions/pkg/controller/worker"
"github.com/gardener/gardener/extensions/pkg/util"
webhookcmd "github.com/gardener/gardener/extensions/pkg/webhook/cmd"
machinev1alpha1 "github.com/gardener/machine-controller-manager/pkg/apis/machine/v1alpha1"
"github.com/spf13/cobra"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/manager"
)
// NewControllerManagerCommand creates a new command for running a OpenStack provider controller.
func NewControllerManagerCommand(ctx context.Context) *cobra.Command {
var (
restOpts = &controllercmd.RESTOptions{}
mgrOpts = &controllercmd.ManagerOptions{
LeaderElection: true,
LeaderElectionID: controllercmd.LeaderElectionNameID(openstack.Name),
LeaderElectionNamespace: os.Getenv("LEADER_ELECTION_NAMESPACE"),
WebhookServerPort: 443,
WebhookCertDir: "/tmp/gardener-extensions-cert",
}
configFileOpts = &openstackcmd.ConfigOptions{}
// options for the backupbucket controller
backupBucketCtrlOpts = &controllercmd.ControllerOptions{
MaxConcurrentReconciles: 5,
}
// options for the backupentry controller
backupEntryCtrlOpts = &controllercmd.ControllerOptions{
MaxConcurrentReconciles: 5,
}
// options for the health care controller
healthCheckCtrlOpts = &controllercmd.ControllerOptions{
MaxConcurrentReconciles: 5,
}
// options for the infrastructure controller
infraCtrlOpts = &controllercmd.ControllerOptions{
MaxConcurrentReconciles: 5,
}
reconcileOpts = &controllercmd.ReconcilerOptions{}
// options for the control plane controller
controlPlaneCtrlOpts = &controllercmd.ControllerOptions{
MaxConcurrentReconciles: 5,
}
// options for the worker controller
workerCtrlOpts = &controllercmd.ControllerOptions{
MaxConcurrentReconciles: 5,
}
workerReconcileOpts = &worker.Options{
DeployCRDs: true,
}
workerCtrlOptsUnprefixed = controllercmd.NewOptionAggregator(workerCtrlOpts, workerReconcileOpts)
// options for the webhook server
webhookServerOptions = &webhookcmd.ServerOptions{
Namespace: os.Getenv("WEBHOOK_CONFIG_NAMESPACE"),
}
controllerSwitches = openstackcmd.ControllerSwitchOptions()
webhookSwitches = openstackcmd.WebhookSwitchOptions()
webhookOptions = webhookcmd.NewAddToManagerOptions(openstack.Name, webhookServerOptions, webhookSwitches)
aggOption = controllercmd.NewOptionAggregator(
restOpts,
mgrOpts,
controllercmd.PrefixOption("backupbucket-", backupBucketCtrlOpts),
controllercmd.PrefixOption("backupentry-", backupEntryCtrlOpts),
controllercmd.PrefixOption("controlplane-", controlPlaneCtrlOpts),
controllercmd.PrefixOption("infrastructure-", infraCtrlOpts),
controllercmd.PrefixOption("worker-", &workerCtrlOptsUnprefixed),
controllercmd.PrefixOption("healthcheck-", healthCheckCtrlOpts),
controllerSwitches,
configFileOpts,
reconcileOpts,
webhookOptions,
)
)
cmd := &cobra.Command{
Use: fmt.Sprintf("%s-controller-manager", openstack.Name),
Run: func(cmd *cobra.Command, args []string) {
if err := aggOption.Complete(); err != nil {
controllercmd.LogErrAndExit(err, "Error completing options")
}
util.ApplyClientConnectionConfigurationToRESTConfig(configFileOpts.Completed().Config.ClientConnection, restOpts.Completed().Config)
if workerReconcileOpts.Completed().DeployCRDs {
if err := worker.ApplyMachineResourcesForConfig(ctx, restOpts.Completed().Config); err != nil {
controllercmd.LogErrAndExit(err, "Error ensuring the machine CRDs")
}
}
mgr, err := manager.New(restOpts.Completed().Config, mgrOpts.Completed().Options())
if err != nil {
controllercmd.LogErrAndExit(err, "Could not instantiate manager")
}
scheme := mgr.GetScheme()
if err := controller.AddToScheme(scheme); err != nil {
controllercmd.LogErrAndExit(err, "Could not update manager scheme")
}
if err := druidv1alpha1.AddToScheme(scheme); err != nil {
controllercmd.LogErrAndExit(err, "Could not update manager scheme")
}
if err := openstackinstall.AddToScheme(scheme); err != nil {
controllercmd.LogErrAndExit(err, "Could not update manager scheme")
}
// add common meta types to schema for controller-runtime to use v1.ListOptions
metav1.AddToGroupVersion(scheme, machinev1alpha1.SchemeGroupVersion)
// add types required for Health check
scheme.AddKnownTypes(machinev1alpha1.SchemeGroupVersion,
&machinev1alpha1.MachineDeploymentList{},
)
configFileOpts.Completed().ApplyETCDStorage(&openstackcontrolplaneexposure.DefaultAddOptions.ETCDStorage)
configFileOpts.Completed().ApplyHealthCheckConfig(&healthcheck.DefaultAddOptions.HealthCheckConfig)
healthCheckCtrlOpts.Completed().Apply(&healthcheck.DefaultAddOptions.Controller)
backupBucketCtrlOpts.Completed().Apply(&openstackbackupbucket.DefaultAddOptions.Controller)
backupEntryCtrlOpts.Completed().Apply(&openstackbackupentry.DefaultAddOptions.Controller)
controlPlaneCtrlOpts.Completed().Apply(&openstackcontrolplane.DefaultAddOptions.Controller)
infraCtrlOpts.Completed().Apply(&openstackinfrastructure.DefaultAddOptions.Controller)
reconcileOpts.Completed().Apply(&openstackinfrastructure.DefaultAddOptions.IgnoreOperationAnnotation)
reconcileOpts.Completed().Apply(&openstackcontrolplane.DefaultAddOptions.IgnoreOperationAnnotation)
reconcileOpts.Completed().Apply(&openstackworker.DefaultAddOptions.IgnoreOperationAnnotation)
workerCtrlOpts.Completed().Apply(&openstackworker.DefaultAddOptions.Controller)
if _, _, err := webhookOptions.Completed().AddToManager(mgr); err != nil {
controllercmd.LogErrAndExit(err, "Could not add webhooks to manager")
}
if err := controllerSwitches.Completed().AddToManager(mgr); err != nil {
controllercmd.LogErrAndExit(err, "Could not add controllers to manager")
}
if err := mgr.Start(ctx.Done()); err != nil {
controllercmd.LogErrAndExit(err, "Error running manager")
}
},
}
aggOption.AddFlags(cmd.Flags())
return cmd
}
| [
"\"LEADER_ELECTION_NAMESPACE\"",
"\"WEBHOOK_CONFIG_NAMESPACE\""
]
| []
| [
"LEADER_ELECTION_NAMESPACE",
"WEBHOOK_CONFIG_NAMESPACE"
]
| [] | ["LEADER_ELECTION_NAMESPACE", "WEBHOOK_CONFIG_NAMESPACE"] | go | 2 | 0 | |
src/train_2d_cnn_fold.py | import glob
import os
import random
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from torch.utils.data import Dataset
import matplotlib.pyplot as plt
import cv2
import scipy.ndimage as ndimage
import torch.optim as optim
import time
import shutil
from sklearn.metrics import roc_curve, auc
from argparse import ArgumentParser, Namespace
import torch.nn.functional as F
from torch.autograd import Variable
from torch.utils.data import DataLoader
import math
from functools import partial
from mpl_toolkits.axes_grid1 import make_axes_locatable
import torchio as tio
from tqdm.auto import tqdm
from clf_model_utils.miccai_2d_dataset import MICCAI2DDataset
import json
import wandb
import fastai
from fastai.vision.all import *
from fastai.data.core import DataLoaders
from fastai.callback.all import *
from fastai.callback.wandb import WandbCallback
import torch.nn.functional as F
from timm import create_model
from fastai.vision.learner import _update_first_layer
from fastai.vision.learner import _add_norm
LOG_WANDB = False
# This is modified from https://libauc.org/
class AUCMLoss(torch.nn.Module):
"""
AUCM Loss with squared-hinge function: a novel loss function to directly optimize AUROC
inputs:
margin: margin term for AUCM loss, e.g., m in [0, 1]
imratio: imbalance ratio, i.e., the ratio of number of postive samples to number of total samples
outputs:
loss value
Reference:
Yuan, Z., Yan, Y., Sonka, M. and Yang, T.,
Large-scale Robust Deep AUC Maximization: A New Surrogate Loss and Empirical Studies on Medical Image Classification.
International Conference on Computer Vision (ICCV 2021)
Link:
https://arxiv.org/abs/2012.03173
"""
def __init__(self, margin=1.0, imratio=None, device=None):
super(AUCMLoss, self).__init__()
if not device:
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
else:
self.device = device
self.margin = margin
self.p = imratio
# https://discuss.pytorch.org/t/valueerror-cant-optimize-a-non-leaf-tensor/21751
self.a = torch.zeros(1, dtype=torch.float32, device=self.device, requires_grad=True).to(self.device) #cuda()
self.b = torch.zeros(1, dtype=torch.float32, device=self.device, requires_grad=True).to(self.device) #.cuda()
self.alpha = torch.zeros(1, dtype=torch.float32, device=self.device, requires_grad=True).to(self.device) #.cuda()
def forward(self, input, target):
y_pred = (torch.softmax(input, 1)[:,1]).unsqueeze(1)
y_true = target.unsqueeze(1)
if self.p is None:
self.p = (y_true==1).float().sum()/y_true.shape[0]
y_pred = y_pred.reshape(-1, 1) # be carefull about these shapes
y_true = y_true.reshape(-1, 1)
loss = (1-self.p)*torch.mean((y_pred - self.a)**2*(1==y_true).float()) + \
self.p*torch.mean((y_pred - self.b)**2*(0==y_true).float()) + \
2*self.alpha*(self.p*(1-self.p)*self.margin + \
torch.mean((self.p*y_pred*(0==y_true).float() - (1-self.p)*y_pred*(1==y_true).float())) )- \
self.p*(1-self.p)*self.alpha**2
return loss
def datestr():
now = time.gmtime()
return '{:02}_{:02}___{:02}_{:02}'.format(now.tm_mday, now.tm_mon, now.tm_hour, now.tm_min)
def make_dirs(path):
if os.path.exists(path):
shutil.rmtree(path)
os.mkdir(path)
else:
os.makedirs(path)
def show_2d_batch(batch, preds=None, scale=4, save_fn=None):
_images, _labels = batch
images = _images.cpu().numpy()[:,0,:,:] # reduce rgb dimension to grayscale
labels = _labels.cpu().numpy()
cmap = matplotlib.cm.rainbow
norm = matplotlib.colors.Normalize(vmin=np.percentile(images, 2), vmax=np.percentile(images, 98))
if preds is not None:
pred_lbls = list(preds.cpu().numpy())
else:
pred_lbls = [-1 for _ in labels]
n_root = int(np.ceil(np.sqrt(len(images))))
plt.close('all')
f, axs = plt.subplots(n_root, n_root, figsize=((scale + 1)*n_root, scale*n_root))
axs = axs.flatten()
for img, lbl, pred, ax in zip(images, labels, pred_lbls, axs):
axim = ax.imshow(img, cmap=cmap, norm=norm)
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=0.05)
f.colorbar(matplotlib.cm.ScalarMappable(norm=norm, cmap=cmap), cax=cax, orientation='vertical')
ax.set_title(f'GT: {lbl}, Pred: {pred:.3f}', fontsize=16)
ax.set_xticks([])
ax.set_yticks([])
# hide empties
for ax_index in range(len(images), len(axs)):
axs[ax_index].axis('off')
plt.tight_layout()
plt.subplots_adjust(left = 0.1, right = 0.9, wspace=0.2, hspace=0.05)
if save_fn is not None:
plt.savefig(save_fn, transparent=False)
else:
plt.show()
class RocStarLoss(torch.nn.Module):
"""Smooth approximation for ROC AUC
"""
def __init__(self, delta = 1.0, sample_size = 100, sample_size_gamma = 100, update_gamma_each=100):
r"""
Args:
delta: Param from article
sample_size (int): Number of examples to take for ROC AUC approximation
sample_size_gamma (int): Number of examples to take for Gamma parameter approximation
update_gamma_each (int): Number of steps after which to recompute gamma value.
"""
super().__init__()
self.delta = delta
self.sample_size = sample_size
self.sample_size_gamma = sample_size_gamma
self.update_gamma_each = update_gamma_each
self.steps = 0
size = max(sample_size, sample_size_gamma)
# Randomly init labels
self.y_pred_history = torch.rand((size, 1)).cuda()
self.y_true_history = torch.randint(2, (size, 1)).cuda()
def forward(self, y_pred, target):
"""
Args:
y_pred: Tensor of model predictions in [0, 1] range. Shape (B x 1)
y_true: Tensor of true labels in {0, 1}. Shape (B x 1)
"""
y_pred_1 = (torch.softmax(y_pred, 1)[:,1]).unsqueeze(1)
y_true = target.unsqueeze(1)
if self.steps % self.update_gamma_each == 0:
self.update_gamma()
self.steps += 1
positive = y_pred_1[y_true > 0]
negative = y_pred_1[y_true < 1]
# Take last `sample_size` elements from history
y_pred_history = self.y_pred_history[- self.sample_size:]
y_true_history = self.y_true_history[- self.sample_size:]
positive_history = y_pred_history[y_true_history > 0]
negative_history = y_pred_history[y_true_history < 1]
if positive.size(0) > 0:
diff = negative_history.view(1, -1) + self.gamma - positive.view(-1, 1)
loss_positive = torch.nn.functional.relu(diff ** 2).mean()
else:
loss_positive = 0
if negative.size(0) > 0:
diff = negative.view(1, -1) + self.gamma - positive_history.view(-1, 1)
loss_negative = torch.nn.functional.relu(diff ** 2).mean()
else:
loss_negative = 0
loss = loss_negative + loss_positive
# Update FIFO queue
batch_size = y_pred_1.size(0)
self.y_pred_history = torch.cat((self.y_pred_history[batch_size:], y_pred_1.clone().detach()))
self.y_true_history = torch.cat((self.y_true_history[batch_size:], y_pred_1.clone().detach()))
return loss
def update_gamma(self):
# Take last `sample_size_gamma` elements from history
y_pred = self.y_pred_history[- self.sample_size_gamma:]
y_true = self.y_true_history[- self.sample_size_gamma:]
positive = y_pred[y_true > 0]
negative = y_pred[y_true < 1]
# Create matrix of size sample_size_gamma x sample_size_gamma
diff = positive.view(-1, 1) - negative.view(1, -1)
AUC = (diff > 0).type(torch.float).mean()
num_wrong_ordered = (1 - AUC) * diff.flatten().size(0)
# Adjuct gamma, so that among correct ordered samples `delta * num_wrong_ordered` were considered
# ordered incorrectly with gamma added
correct_ordered = diff[diff > 0].flatten().sort().values
idx = min(int(num_wrong_ordered * self.delta), len(correct_ordered)-1)
self.gamma = correct_ordered[idx]
@patch
@delegates(subplots)
def plot_metrics(self: Recorder, nrows=None, ncols=None, figsize=None, **kwargs):
metrics = np.stack(self.values)
names = self.metric_names[1:-1]
n = len(names) - 1
if nrows is None and ncols is None:
nrows = int(math.sqrt(n))
ncols = int(np.ceil(n / nrows))
elif nrows is None: nrows = int(np.ceil(n / ncols))
elif ncols is None: ncols = int(np.ceil(n / nrows))
figsize = figsize or (ncols * 6, nrows * 4)
fig, axs = subplots(nrows, ncols, figsize=figsize, **kwargs)
axs = [ax if i < n else ax.set_axis_off() for i, ax in enumerate(axs.flatten())][:n]
for i, (name, ax) in enumerate(zip(names, [axs[0]] + axs)):
ax.plot(metrics[:, i], color='#1f77b4' if i == 0 else '#ff7f0e', label='valid' if i > 0 else 'train')
ax.set_title(name if i > 1 else 'losses')
ax.legend(loc='best')
save_fn = None
if 'save_fn' in kwargs:
save_fn = kwargs['save_fn']
if save_fn is not None:
plt.savefig(save_fn, transparent=False)
else:
plt.show()
# timm + fastai functions copied from https://walkwithfastai.com/vision.external.timm
def create_timm_body(arch:str, pretrained=True, cut=None, n_in=3):
"Creates a body from any model in the `timm` library."
if 'vit' in arch:
model = create_model(arch, pretrained=pretrained, num_classes=0)
else:
model = create_model(arch, pretrained=pretrained, num_classes=0, global_pool='')
_update_first_layer(model, n_in, pretrained)
if cut is None:
ll = list(enumerate(model.children()))
cut = next(i for i,o in reversed(ll) if has_pool_type(o))
if isinstance(cut, int): return nn.Sequential(*list(model.children())[:cut])
elif callable(cut): return cut(model)
else: raise NamedError("cut must be either integer or function")
def create_timm_model(arch:str, n_out, cut=None, pretrained=True, n_in=3, init=nn.init.kaiming_normal_, custom_head=None,
concat_pool=True, **kwargs):
"Create custom architecture using `arch`, `n_in` and `n_out` from the `timm` library"
body = create_timm_body(arch, pretrained, None, n_in)
if custom_head is None:
nf = num_features_model(nn.Sequential(*body.children()))
head = create_head(nf, n_out, concat_pool=concat_pool, **kwargs)
else: head = custom_head
model = nn.Sequential(body, head)
if init is not None: apply_init(model[1], init)
return model
def timm_learner(dls, arch:str, loss_func=None, pretrained=True, cut=None, splitter=None,
y_range=None, config=None, n_out=None, normalize=True, **kwargs):
"Build a convnet style learner from `dls` and `arch` using the `timm` library"
if config is None: config = {}
if n_out is None: n_out = get_c(dls)
assert n_out, "`n_out` is not defined, and could not be inferred from data, set `dls.c` or pass `n_out`"
if y_range is None and 'y_range' in config: y_range = config.pop('y_range')
model = create_timm_model(arch, n_out, default_split, pretrained, y_range=y_range, **config)
kwargs.pop('ps')
learn = Learner(dls, model, loss_func=loss_func, splitter=default_split, **kwargs)
if pretrained: learn.freeze()
return learn
def main(fold:int, train_df_fn:str, npy_dir:str, bs:int, epochs:int,
lr:float=1e-4, arch:str='resnet34', ps:float=0.6,
optim:str='ranger', im_sz:int=256, loss_name:str="rocstar"):
modality = str(os.path.dirname(npy_dir)).split('_')[-1]
name = f'fold-{fold}'
group_name = f'{modality}_{arch}_bs{bs}_ep{epochs}_{loss_name}_lr{lr}_ps{ps}_{optim}_sz{im_sz}'
train_dir = npy_dir
out_folder = os.path.join('./output', group_name, name)
make_dirs(out_folder)
# start logging
global LOG_WANDB
wandb_config_fn = None
if os.path.exists('../wandb_params.json'):
wandb_config_fn = '../wandb_params.json'
if os.path.exists('./wandb_params.json'):
wandb_config_fn = './wandb_params.json'
if wandb_config_fn is not None:
with open(wandb_config_fn) as f:
config = json.load(f)
wandb.init(**config,
name=name, group=group_name,
tags=['MGMT-classification', f'fold-{fold}', modality],
config={
'bs':bs, 'epochs':epochs, 'fold':fold,
'ep':epochs, 'lr':lr, 'arch':arch, 'ps':ps,
'optim':optim, 'sz':im_sz, 'loss_name': loss_name,
'modality' : modality
},
sync_tensorboard=True)
LOG_WANDB = True
df = pd.read_csv(train_df_fn)
train_df = df[df.fold != fold]
val_df = df[df.fold == fold]
image_size = (im_sz,im_sz)
if len(val_df) == 0:
val_df = df[df.fold == 0]
tio_augmentations = tio.Compose([
tio.RandomAffine(p=0.5),
tio.RandomBiasField(p=0.3),
tio.RandomGhosting(p=0.05),
tio.RandomElasticDeformation(p=0.2),
tio.RandomSpike(p=0.05),
tio.RandomNoise(p=0.1),
tio.RandomAnisotropy(p=0.05),
tio.RandomBlur(p=0.1),
tio.RandomGamma(0.1, p=0.15),
])
ds_t = MICCAI2DDataset(
train_df,
npy_dir=npy_dir,
image_size=image_size,
tio_augmentations=tio_augmentations,
is_train=True
)
ds_v = MICCAI2DDataset(
val_df,
npy_dir=npy_dir,
image_size=image_size,
tio_augmentations=None,
is_train=False
)
num_workers = 8
dls = DataLoaders.from_dsets(ds_t, ds_v, bs=bs, device='cuda', num_workers=num_workers)
loss = LabelSmoothingCrossEntropyFlat(eps=0.2)
create_learner = cnn_learner
if arch == 'densetnet121':
base = densenet121
elif arch == 'resnet18':
base = resnet18
elif arch == 'resnet34':
base = resnet34
elif arch == 'resnet50':
base = resnet50
elif arch == 'resnet101':
base = resnet101
elif arch == 'densenet169':
base = densenet169
else:
create_learner = timm_learner
base = arch
if optim == "ranger":
opt_func = fastai.optimizer.ranger
else:
opt_func = fastai.optimizer.Adam
if loss_name == 'rocstar':
second_loss = RocStarLoss()
elif loss_name == 'bce':
second_loss = loss
elif loss_name == 'libauc':
second_loss = AUCMLoss()
else:
raise Exception
learn = create_learner(
dls,
base,
pretrained=True,
n_out=2,
loss_func=loss,
opt_func=opt_func,
metrics=[
RocAucBinary(),
accuracy
],
ps=ps
).to_fp16()
# train head first with CE
learn.fit_one_cycle(1, lr)
learn.unfreeze()
model_path = os.path.join('..', out_folder, 'final')
cbs = [WandbCallback(log=None, log_preds=False, log_model=False)] if LOG_WANDB else []
#best_path = os.path.join('..', out_folder, 'best')
#save_cb = SaveModelCallback(monitor='roc_auc_score', fname=best_path, reset_on_fit=True)
#cbs.append(save_cb)
# continue with main loss
learn.loss_func = second_loss
learn.fit_flat_cos(epochs, lr, div_final=2, pct_start=0.99, cbs=cbs)
learn.save(model_path, with_opt=False)
#plot_fn = os.path.join(out_folder, 'plot_metrics.png')
#plt.close('all')
#learn.recorder.plot_metrics()
#plt.savefig(plot_fn)
#if LOG_WANDB:
# wandb.log({'training': wandb.Image(plot_fn)})
# eval
if fold >= 0:
dl_test = DataLoader(ds_v, 32, num_workers=8, shuffle=False)
test_preds = learn.get_preds(dl=dl_test)
test_p, test_gt = test_preds
test_p = torch.softmax(test_p, 1)
test_p = test_p.numpy()[:,1]
test_gt = test_gt.numpy()
tta_preds = learn.tta(dl=dl_test)
tta_p, tta_gt = tta_preds
tta_p = torch.softmax(tta_p, 1)
tta_p = tta_p.numpy()[:,1]
tta_gt = tta_gt.numpy()
fpr, tpr, _ = roc_curve(np.array(test_gt), np.array(test_p))
tta_fpr, tta_tpr, _ = roc_curve(np.array(tta_gt), np.array(tta_p))
roc_auc = auc(fpr, tpr)
tta_roc_auc = auc(tta_fpr, tta_tpr)
acc = np.sum((np.array(test_gt) > 0.5) == (np.array(test_p) > 0.5)) / len(test_gt)
tta_acc = np.sum((np.array(test_gt) > 0.5) == (np.array(test_p) > 0.5)) / len(test_gt)
auc_fn = os.path.join(out_folder, 'auc.png')
plt.close('all')
plt.figure()
lw = 2
plt.plot(fpr, tpr, color='darkorange',
lw=lw, label=f'ROC curve (area = {roc_auc:.2f}), Acc. = {acc*100:.2f}')
plt.plot(tta_fpr, tta_tpr, color='red',
lw=lw, label=f'TTA ROC curve (area = {tta_roc_auc:.2f}), Acc. = {tta_acc*100:.2f}')
plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic')
plt.legend(loc="lower right")
plt.savefig(auc_fn, transparent=False)
if LOG_WANDB:
wandb.log({'validation': wandb.Image(auc_fn)})
wandb.log({'auc' : roc_auc})
wandb.log({'auc-tta' : tta_roc_auc})
wandb.log({'acc' : acc})
wandb.log({'acc-tta' : tta_acc})
result_df = val_df.copy()
result_df['pred_mgmt'] = list(test_p)
result_df['pred_mgmt_tta'] = list(tta_p)
result_df.to_csv(os.path.join(out_folder, 'oof.csv'))
if __name__ == '__main__':
parser = ArgumentParser(parents=[])
parser.add_argument('--fold', type=int)
parser.add_argument('--bs', type=int, default=32)
parser.add_argument('--epochs', type=int, default=30)
parser.add_argument('--lr', type=float, default=1e-4)
parser.add_argument('--train_df', type=str, default='./input/train_feature_data_v2.csv')
parser.add_argument('--npy_dir', type=str, default='./input/aligned_and_cropped_t2w/')
parser.add_argument('--arch', type=str, default='resnet34')
parser.add_argument('--ps', type=float, default=0.6)
parser.add_argument('--optim', type=str, default='ranger')
parser.add_argument('--im_sz', type=int, default=256)
parser.add_argument('--loss_name', type=str, default='auclib')
params = parser.parse_args()
fold = params.fold
train_df = params.train_df
npy_dir = params.npy_dir
bs = params.bs
epochs = params.epochs
lr = params.lr
arch = params.arch
ps = params.ps
optim = params.optim
im_sz = params.im_sz
loss_name = params.loss_name
main(fold, train_df, npy_dir, bs, epochs, lr, arch, ps, optim, im_sz, loss_name) | []
| []
| []
| [] | [] | python | null | null | null |
main.go | package main
import (
"os"
log "github.com/Sirupsen/logrus"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
r "gopkg.in/dancannon/gorethink.v2"
)
var (
rc *r.Session
tc *TwilioClient
apiKey string
)
func main() {
router := echo.New()
router.Use(middleware.Logger())
router.Use(middleware.Recover())
api := router.Group("/api")
api.Use(middleware.BasicAuth(AuthMiddleware))
api.GET("/users", UserListHandler)
api.PUT("/users", AddUserHandler)
api.DELETE("/users/:id", RemoveUserHandler)
api.GET("/webhooks", WebhookListHandler)
api.PUT("/webhooks", AddWebhookHandler)
api.DELETE("/webhooks/:id", RemoveWebhookHandler)
router.POST("/webhook/:name", WebhookHandler)
port := os.Getenv("PORT")
if port == "" {
port = ":1323"
}
icalURL := os.Getenv("PINGROLL_ICAL_URL")
if icalURL == "" {
log.Fatal("PINGROLL_ICAL_URL is required")
}
rehtinkUrl := os.Getenv("PINGROLL_RETHINK_URL")
if rehtinkUrl == "" {
log.Fatal("PINGROLL_RETHINK_URL is required")
}
twilioAccountSID := os.Getenv("PINGROLL_TWILIO_ACCOUNT_SID")
if twilioAccountSID == "" {
log.Fatal("PINGROLL_TWILIO_ACCOUNT_SID is required")
}
twilioAuthToken := os.Getenv("PINGROLL_TWILIO_AUTH_TOKEN")
if twilioAuthToken == "" {
log.Fatal("PINGROLL_TWILIO_AUTH_TOKEN is required")
}
twilioFromNumber := os.Getenv("PINGROLL_TWILIO_FROM_NUMBER")
if twilioFromNumber == "" {
log.Fatal("PINGROLL_TWILIO_FROM_NUMBER is required")
}
apiKey = os.Getenv("PINGROLL_API_KEY")
if apiKey == "" {
log.Fatal("PINGROLL_API_KEY is required")
}
var err error
rc, err = r.Connect(r.ConnectOpts{
Address: rehtinkUrl,
Database: "pingroll",
})
if err != nil {
log.Fatal(err)
}
tc = &TwilioClient{
AccountSID: twilioAccountSID,
AuthToken: twilioAuthToken,
FromNumber: twilioFromNumber,
}
ProcessIcal(icalURL)
router.Logger.Fatal(router.Start(port))
}
| [
"\"PORT\"",
"\"PINGROLL_ICAL_URL\"",
"\"PINGROLL_RETHINK_URL\"",
"\"PINGROLL_TWILIO_ACCOUNT_SID\"",
"\"PINGROLL_TWILIO_AUTH_TOKEN\"",
"\"PINGROLL_TWILIO_FROM_NUMBER\"",
"\"PINGROLL_API_KEY\""
]
| []
| [
"PORT",
"PINGROLL_API_KEY",
"PINGROLL_TWILIO_ACCOUNT_SID",
"PINGROLL_ICAL_URL",
"PINGROLL_TWILIO_AUTH_TOKEN",
"PINGROLL_TWILIO_FROM_NUMBER",
"PINGROLL_RETHINK_URL"
]
| [] | ["PORT", "PINGROLL_API_KEY", "PINGROLL_TWILIO_ACCOUNT_SID", "PINGROLL_ICAL_URL", "PINGROLL_TWILIO_AUTH_TOKEN", "PINGROLL_TWILIO_FROM_NUMBER", "PINGROLL_RETHINK_URL"] | go | 7 | 0 | |
tracee-ebpf/main.go | package main
import (
"embed"
"fmt"
"io"
"io/ioutil"
"log"
"math"
"net"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"github.com/aquasecurity/libbpfgo/helpers"
"github.com/aquasecurity/tracee/tracee-ebpf/tracee"
"github.com/syndtr/gocapability/capability"
cli "github.com/urfave/cli/v2"
)
var debug bool
var traceeInstallPath string
var buildPolicy string
// These vars are supposed to be injected at build time
//go:embed "dist/tracee.bpf/*"
//go:embed "dist/tracee.bpf.core.o"
var bpfBundleInjected embed.FS
var version string
func main() {
app := &cli.App{
Name: "Tracee",
Usage: "Trace OS events and syscalls using eBPF",
Version: version,
Action: func(c *cli.Context) error {
if c.Bool("list") {
printList()
return nil
}
cfg := tracee.Config{
PerfBufferSize: c.Int("perf-buffer-size"),
BlobPerfBufferSize: c.Int("blob-perf-buffer-size"),
SecurityAlerts: c.Bool("security-alerts"),
Debug: c.Bool("debug"),
}
if checkCommandIsHelp(c.StringSlice("output")) {
printOutputHelp()
return nil
}
output, err := prepareOutput(c.StringSlice("output"))
if err != nil {
return err
}
cfg.Output = &output
if checkCommandIsHelp(c.StringSlice("capture")) {
printCaptureHelp()
return nil
}
capture, err := prepareCapture(c.StringSlice("capture"))
if err != nil {
return err
}
cfg.Capture = &capture
if checkCommandIsHelp(c.StringSlice("trace")) {
printFilterHelp()
return nil
}
filter, err := prepareFilter(c.StringSlice("trace"))
if err != nil {
return err
}
cfg.Filter = &filter
if c.Bool("security-alerts") {
cfg.Filter.EventsToTrace = append(cfg.Filter.EventsToTrace, tracee.MemProtAlertEventID)
}
var bpfBytes []byte
// Check if user specified a bpf object path explicitly
bpfFilePath, err := checkTraceeBPFEnvPath()
if err != nil {
return err
}
if bpfFilePath != "" {
if debug {
fmt.Printf("BPF object file specified by TRACEE_BPF_FILE found: %s", bpfFilePath)
}
bpfBytes, err = ioutil.ReadFile(bpfFilePath)
if err != nil {
return err
}
} else if btfEnabled() {
if debug {
fmt.Println("BTF enabled, attempting to unpack CORE bpf object")
}
bpfFilePath = "embedded-core"
bpfBytes, err = unpackCOREBinary()
if err != nil {
return err
}
} else {
if debug {
fmt.Println("BTF is not enabled")
}
bpfFilePath, err = getBPFObjectPath()
if err != nil {
return err
}
bpfBytes, err = ioutil.ReadFile(bpfFilePath)
if err != nil {
return err
}
}
cfg.BPFObjPath = bpfFilePath
cfg.BPFObjBytes = bpfBytes
err = checkRequiredCapabilities()
if err != nil {
return err
}
missingKernelOptions := missingKernelConfigOptions()
if len(missingKernelOptions) != 0 {
return fmt.Errorf("kernel is not properly configured, missing: %v", missingKernelOptions)
}
t, err := tracee.New(cfg)
if err != nil {
return fmt.Errorf("error creating Tracee: %v", err)
}
return t.Run()
},
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "list",
Aliases: []string{"l"},
Value: false,
Usage: "just list tracable events",
},
&cli.StringSliceFlag{
Name: "trace",
Aliases: []string{"t"},
Value: nil,
Usage: "select events to trace by defining trace expressions. run '--trace help' for more info.",
},
&cli.StringSliceFlag{
Name: "capture",
Aliases: []string{"c"},
Value: nil,
Usage: "capture artifacts that were written, executed or found to be suspicious. run '--capture help' for more info.",
},
&cli.StringSliceFlag{
Name: "output",
Aliases: []string{"o"},
Value: cli.NewStringSlice("format:table"),
Usage: "Control how and where output is printed. run '--output help' for more info.",
},
&cli.BoolFlag{
Name: "security-alerts",
Value: false,
Usage: "alert on security related events",
},
&cli.IntFlag{
Name: "perf-buffer-size",
Aliases: []string{"b"},
Value: 1024,
Usage: "size, in pages, of the internal perf ring buffer used to submit events from the kernel",
},
&cli.IntFlag{
Name: "blob-perf-buffer-size",
Value: 1024,
Usage: "size, in pages, of the internal perf ring buffer used to send blobs from the kernel",
},
&cli.BoolFlag{
Name: "debug",
Value: false,
Usage: "write verbose debug messages to standard output and retain intermediate artifacts",
Destination: &debug,
},
&cli.StringFlag{
Name: "install-path",
Value: "/tmp/tracee",
Usage: "path where tracee will install or lookup it's resources",
Destination: &traceeInstallPath,
},
&cli.StringFlag{
Name: "build-policy",
Value: "if-needed",
Usage: "when to build the bpf program. possible options: 'never'/'always'/'if-needed'",
Destination: &buildPolicy,
},
},
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
func checkCommandIsHelp(s []string) bool {
if len(s) == 1 && s[0] == "help" {
return true
}
return false
}
func printOutputHelp() {
outputHelp := `Control how and where output is printed.
Possible options:
[format:]table output events in table format
[format:]table-verbose output events in table format with extra fields per event
[format:]json output events in json format
[format:]gob output events in gob format
[format:]gotemplate=/path/to/template output events formatted using a given gotemplate file
out-file:/path/to/file write the output to a specified file. create/trim the file if exists (default: stdout)
err-file:/path/to/file write the errors to a specified file. create/trim the file if exists (default: stderr)
option:{stack-addresses,detect-syscall,exec-env} augment output according to given options (default: none)
stack-addresses include stack memory addresses for each event
detect-syscall when tracing kernel functions which are not syscalls, detect and show the original syscall that called that function
exec-env when tracing execve/execveat, show the environment variables that were used for execution
relative-time use relative timestamp instead of wall timestamp for events
Examples:
--output json | output as json
--output gotemplate=/path/to/my.tmpl | output as the provided go template
--output out-file:/my/out err-file:/my/err | output to /my/out and errors to /my/err
Use this flag multiple times to choose multiple output options
`
fmt.Print(outputHelp)
}
func prepareOutput(outputSlice []string) (tracee.OutputConfig, error) {
res := tracee.OutputConfig{}
for _, o := range outputSlice {
outputParts := strings.SplitN(o, ":", 2)
numParts := len(outputParts)
if numParts == 1 {
res.Format = outputParts[0]
err := res.Validate()
if err != nil {
return res, err
}
outputParts = append(outputParts, outputParts[0])
outputParts[0] = "format"
}
switch outputParts[0] {
case "format":
res.Format = outputParts[1]
err := res.Validate()
if err != nil {
return res, err
}
case "out-file":
res.OutPath = outputParts[1]
case "err-file":
res.ErrPath = outputParts[1]
case "option":
switch outputParts[1] {
case "stack-addresses":
res.StackAddresses = true
case "detect-syscall":
res.DetectSyscall = true
case "exec-env":
res.ExecEnv = true
case "relative-time":
res.RelativeTime = true
default:
return res, fmt.Errorf("invalid output option: %s, use '--output help' for more info", outputParts[1])
}
default:
return res, fmt.Errorf("invalid output value: %s, use '--output help' for more info", outputParts[1])
}
}
if res.Format == "" {
res.Format = "table"
}
return res, nil
}
func printCaptureHelp() {
captureHelp := `Capture artifacts that were written, executed or found to be suspicious.
Captured artifacts will appear in the 'output-path' directory.
Possible options:
[artifact:]write[=/path/prefix*] capture written files. A filter can be given to only capture file writes whose path starts with some prefix (up to 50 characters). Up to 3 filters can be given.
[artifact:]exec capture executed files.
[artifact:]mem capture memory regions that had write+execute (w+x) protection, and then changed to execute (x) only.
[artifact:]all capture all of the above artifacts.
[artifact:]net=interface capture network traffic of the given interface
dir:/path/to/dir path where tracee will save produced artifacts. the artifact will be saved into an 'out' subdirectory. (default: /tmp/tracee).
profile creates a runtime profile of program executions and their metadata for forensics use.
clear-dir clear the captured artifacts output dir before starting (default: false).
Examples:
--capture exec | capture executed files into the default output directory
--capture all --capture dir:/my/dir --capture clear-dir | delete /my/dir/out and then capture all supported artifacts into it
--capture write=/usr/bin/* --capture write=/etc/* | capture files that were written into anywhere under /usr/bin/ or /etc/
--capture exec --capture profile | capture executed files and create a runtime profile in the output directory
--capture net=eth0 | capture network traffic of eth0
Use this flag multiple times to choose multiple capture options
`
fmt.Print(captureHelp)
}
func prepareCapture(captureSlice []string) (tracee.CaptureConfig, error) {
capture := tracee.CaptureConfig{}
outDir := "/tmp/tracee"
clearDir := false
var filterFileWrite []string
for i := range captureSlice {
cap := captureSlice[i]
if strings.HasPrefix(cap, "artifact:write") ||
strings.HasPrefix(cap, "artifact:exec") ||
strings.HasPrefix(cap, "artifact:mem") ||
strings.HasPrefix(cap, "artifact:all") {
cap = strings.TrimPrefix(cap, "artifact:")
}
if cap == "write" {
capture.FileWrite = true
} else if strings.HasPrefix(cap, "write=") && strings.HasSuffix(cap, "*") {
capture.FileWrite = true
pathPrefix := strings.TrimSuffix(strings.TrimPrefix(cap, "write="), "*")
if len(pathPrefix) == 0 {
return tracee.CaptureConfig{}, fmt.Errorf("capture write filter cannot be empty")
}
filterFileWrite = append(filterFileWrite, pathPrefix)
} else if cap == "exec" {
capture.Exec = true
} else if cap == "mem" {
capture.Mem = true
} else if strings.HasPrefix(cap, "net=") {
iface := strings.TrimPrefix(cap, "net=")
if _, err := net.InterfaceByName(iface); err != nil {
return tracee.CaptureConfig{}, fmt.Errorf("invalid network interface: %s", iface)
}
capture.NetIfaces = append(capture.NetIfaces, iface)
} else if cap == "all" {
capture.FileWrite = true
capture.Exec = true
capture.Mem = true
} else if cap == "clear-dir" {
clearDir = true
} else if strings.HasPrefix(cap, "dir:") {
outDir = strings.TrimPrefix(cap, "dir:")
if len(outDir) == 0 {
return tracee.CaptureConfig{}, fmt.Errorf("capture output dir cannot be empty")
}
} else if cap == "profile" {
capture.Exec = true
capture.Profile = true
} else {
return tracee.CaptureConfig{}, fmt.Errorf("invalid capture option specified, use '--capture help' for more info")
}
}
capture.FilterFileWrite = filterFileWrite
capture.OutputPath = filepath.Join(outDir, "out")
if clearDir {
os.RemoveAll(capture.OutputPath)
}
return capture, nil
}
func printFilterHelp() {
filterHelp := `Select which events to trace by defining trace expressions that operate on events or process metadata.
Only events that match all trace expressions will be traced (trace flags are ANDed).
The following types of expressions are supported:
Numerical expressions which compare numbers and allow the following operators: '=', '!=', '<', '>'.
Available numerical expressions: uid, pid, mntns, pidns.
String expressions which compares text and allow the following operators: '=', '!='.
Available string expressions: event, set, uts, comm.
Boolean expressions that check if a boolean is true and allow the following operator: '!'.
Available boolean expressions: container.
Event arguments can be accessed using 'event_name.event_arg' and provide a way to filter an event by its arguments.
Event arguments allow the following operators: '=', '!='.
Strings can be compared as a prefix if ending with '*'.
Event return value can be accessed using 'event_name.retval' and provide a way to filter an event by its return value.
Event return value expression has the same syntax as a numerical expression.
Non-boolean expressions can compare a field to multiple values separated by ','.
Multiple values are ORed if used with equals operator '=', but are ANDed if used with any other operator.
The field 'container' and 'pid' also support the special value 'new' which selects new containers or pids, respectively.
The field 'set' selects a set of events to trace according to predefined sets, which can be listed by using the 'list' flag.
The special 'follow' expression declares that not only processes that match the criteria will be traced, but also their descendants.
Examples:
--trace pid=new | only trace events from new processes
--trace pid=510,1709 | only trace events from pid 510 or pid 1709
--trace p=510 --trace p=1709 | only trace events from pid 510 or pid 1709 (same as above)
--trace container=new | only trace events from newly created containers
--trace container | only trace events from containers
--trace c | only trace events from containers (same as above)
--trace '!container' | only trace events from the host
--trace uid=0 | only trace events from uid 0
--trace mntns=4026531840 | only trace events from mntns id 4026531840
--trace pidns!=4026531836 | only trace events from pidns id not equal to 4026531840
--trace 'uid>0' | only trace events from uids greater than 0
--trace 'pid>0' --trace 'pid<1000' | only trace events from pids between 0 and 1000
--trace 'u>0' --trace u!=1000 | only trace events from uids greater than 0 but not 1000
--trace event=execve,open | only trace execve and open events
--trace event=open* | only trace events prefixed by "open"
--trace event!=open*,dup* | don't trace events prefixed by "open" or "dup"
--trace set=fs | trace all file-system related events
--trace s=fs --trace e!=open,openat | trace all file-system related events, but not open(at)
--trace uts!=ab356bc4dd554 | don't trace events from uts name ab356bc4dd554
--trace comm=ls | only trace events from ls command
--trace close.fd=5 | only trace 'close' events that have 'fd' equals 5
--trace openat.pathname=/tmp* | only trace 'openat' events that have 'pathname' prefixed by "/tmp"
--trace openat.pathname!=/tmp/1,/bin/ls | don't trace 'openat' events that have 'pathname' equals /tmp/1 or /bin/ls
--trace comm=bash --trace follow | trace all events that originated from bash or from one of the processes spawned by bash
Note: some of the above operators have special meanings in different shells.
To 'escape' those operators, please use single quotes, e.g.: 'uid>0'
`
fmt.Print(filterHelp)
}
func prepareFilter(filters []string) (tracee.Filter, error) {
filter := tracee.Filter{
UIDFilter: &tracee.UintFilter{
Equal: []uint64{},
NotEqual: []uint64{},
Less: tracee.LessNotSetUint,
Greater: tracee.GreaterNotSetUint,
Is32Bit: true,
},
PIDFilter: &tracee.UintFilter{
Equal: []uint64{},
NotEqual: []uint64{},
Less: tracee.LessNotSetUint,
Greater: tracee.GreaterNotSetUint,
Is32Bit: true,
},
NewPidFilter: &tracee.BoolFilter{},
MntNSFilter: &tracee.UintFilter{
Equal: []uint64{},
NotEqual: []uint64{},
Less: tracee.LessNotSetUint,
Greater: tracee.GreaterNotSetUint,
},
PidNSFilter: &tracee.UintFilter{
Equal: []uint64{},
NotEqual: []uint64{},
Less: tracee.LessNotSetUint,
Greater: tracee.GreaterNotSetUint,
},
UTSFilter: &tracee.StringFilter{
Equal: []string{},
NotEqual: []string{},
},
CommFilter: &tracee.StringFilter{
Equal: []string{},
NotEqual: []string{},
},
ContFilter: &tracee.BoolFilter{},
NewContFilter: &tracee.BoolFilter{},
RetFilter: &tracee.RetFilter{
Filters: make(map[int32]tracee.IntFilter),
},
ArgFilter: &tracee.ArgFilter{
Filters: make(map[int32]map[string]tracee.ArgFilterVal),
},
EventsToTrace: []int32{},
}
eventFilter := &tracee.StringFilter{Equal: []string{}, NotEqual: []string{}}
setFilter := &tracee.StringFilter{Equal: []string{}, NotEqual: []string{}}
eventsNameToID := make(map[string]int32, len(tracee.EventsIDToEvent))
for _, event := range tracee.EventsIDToEvent {
eventsNameToID[event.Name] = event.ID
}
for _, f := range filters {
filterName := f
operatorAndValues := ""
operatorIndex := strings.IndexAny(f, "=!<>")
if operatorIndex > 0 {
filterName = f[0:operatorIndex]
operatorAndValues = f[operatorIndex:]
}
if strings.Contains(f, ".retval") {
err := parseRetFilter(filterName, operatorAndValues, eventsNameToID, filter.RetFilter)
if err != nil {
return tracee.Filter{}, err
}
continue
}
if strings.Contains(f, ".") {
err := parseArgFilter(filterName, operatorAndValues, eventsNameToID, filter.ArgFilter)
if err != nil {
return tracee.Filter{}, err
}
continue
}
// The filters which are more common (container, event, pid, set, uid) can be given using a prefix of them.
// Other filters should be given using their full name.
// To avoid collisions between filters that share the same prefix, put the filters which should have an exact match first!
if filterName == "comm" {
err := parseStringFilter(operatorAndValues, filter.CommFilter)
if err != nil {
return tracee.Filter{}, err
}
continue
}
if strings.HasPrefix("container", f) || (strings.HasPrefix("!container", f) && len(f) > 1) {
filter.NewPidFilter.Enabled = true
filter.NewPidFilter.Value = true
err := parseBoolFilter(f, filter.ContFilter)
if err != nil {
return tracee.Filter{}, err
}
continue
}
if strings.HasPrefix("container", filterName) {
if operatorAndValues == "=new" {
filter.NewPidFilter.Enabled = true
filter.NewPidFilter.Value = true
filter.NewContFilter.Enabled = true
filter.NewContFilter.Value = true
continue
}
if operatorAndValues == "!=new" {
filter.ContFilter.Enabled = true
filter.ContFilter.Value = true
filter.NewPidFilter.Enabled = true
filter.NewPidFilter.Value = true
filter.NewContFilter.Enabled = true
filter.NewContFilter.Value = false
continue
}
}
if strings.HasPrefix("event", filterName) {
err := parseStringFilter(operatorAndValues, eventFilter)
if err != nil {
return tracee.Filter{}, err
}
continue
}
if filterName == "mntns" {
err := parseUintFilter(operatorAndValues, filter.MntNSFilter)
if err != nil {
return tracee.Filter{}, err
}
continue
}
if filterName == "pidns" {
err := parseUintFilter(operatorAndValues, filter.PidNSFilter)
if err != nil {
return tracee.Filter{}, err
}
continue
}
if strings.HasPrefix("pid", filterName) {
if operatorAndValues == "=new" {
filter.NewPidFilter.Enabled = true
filter.NewPidFilter.Value = true
continue
}
if operatorAndValues == "!=new" {
filter.NewPidFilter.Enabled = true
filter.NewPidFilter.Value = false
continue
}
err := parseUintFilter(operatorAndValues, filter.PIDFilter)
if err != nil {
return tracee.Filter{}, err
}
continue
}
if strings.HasPrefix("set", filterName) {
err := parseStringFilter(operatorAndValues, setFilter)
if err != nil {
return tracee.Filter{}, err
}
continue
}
if filterName == "uts" {
err := parseStringFilter(operatorAndValues, filter.UTSFilter)
if err != nil {
return tracee.Filter{}, err
}
continue
}
if strings.HasPrefix("uid", filterName) {
err := parseUintFilter(operatorAndValues, filter.UIDFilter)
if err != nil {
return tracee.Filter{}, err
}
continue
}
if strings.HasPrefix("follow", f) {
filter.Follow = true
continue
}
return tracee.Filter{}, fmt.Errorf("invalid filter option specified, use '--trace help' for more info")
}
var err error
filter.EventsToTrace, err = prepareEventsToTrace(eventFilter, setFilter, eventsNameToID)
if err != nil {
return tracee.Filter{}, err
}
return filter, nil
}
func parseUintFilter(operatorAndValues string, uintFilter *tracee.UintFilter) error {
uintFilter.Enabled = true
if len(operatorAndValues) < 2 {
return fmt.Errorf("invalid operator and/or values given to filter: %s", operatorAndValues)
}
valuesString := string(operatorAndValues[1:])
operatorString := string(operatorAndValues[0])
if operatorString == "!" {
if len(operatorAndValues) < 3 {
return fmt.Errorf("invalid operator and/or values given to filter: %s", operatorAndValues)
}
operatorString = operatorAndValues[0:2]
valuesString = operatorAndValues[2:]
}
values := strings.Split(valuesString, ",")
for i := range values {
val, err := strconv.ParseUint(values[i], 10, 64)
if err != nil {
return fmt.Errorf("invalid filter value: %s", values[i])
}
if uintFilter.Is32Bit && (val > math.MaxUint32) {
return fmt.Errorf("filter value is too big: %s", values[i])
}
switch operatorString {
case "=":
uintFilter.Equal = append(uintFilter.Equal, val)
case "!=":
uintFilter.NotEqual = append(uintFilter.NotEqual, val)
case ">":
if (uintFilter.Greater == tracee.GreaterNotSetUint) || (val > uintFilter.Greater) {
uintFilter.Greater = val
}
case "<":
if (uintFilter.Less == tracee.LessNotSetUint) || (val < uintFilter.Less) {
uintFilter.Less = val
}
default:
return fmt.Errorf("invalid filter operator: %s", operatorString)
}
}
return nil
}
func parseIntFilter(operatorAndValues string, intFilter *tracee.IntFilter) error {
intFilter.Enabled = true
if len(operatorAndValues) < 2 {
return fmt.Errorf("invalid operator and/or values given to filter: %s", operatorAndValues)
}
valuesString := string(operatorAndValues[1:])
operatorString := string(operatorAndValues[0])
if operatorString == "!" {
if len(operatorAndValues) < 3 {
return fmt.Errorf("invalid operator and/or values given to filter: %s", operatorAndValues)
}
operatorString = operatorAndValues[0:2]
valuesString = operatorAndValues[2:]
}
values := strings.Split(valuesString, ",")
for i := range values {
val, err := strconv.ParseInt(values[i], 10, 64)
if err != nil {
return fmt.Errorf("invalid filter value: %s", values[i])
}
if intFilter.Is32Bit && (val > math.MaxInt32) {
return fmt.Errorf("filter value is too big: %s", values[i])
}
switch operatorString {
case "=":
intFilter.Equal = append(intFilter.Equal, val)
case "!=":
intFilter.NotEqual = append(intFilter.NotEqual, val)
case ">":
if (intFilter.Greater == tracee.GreaterNotSetInt) || (val > intFilter.Greater) {
intFilter.Greater = val
}
case "<":
if (intFilter.Less == tracee.LessNotSetInt) || (val < intFilter.Less) {
intFilter.Less = val
}
default:
return fmt.Errorf("invalid filter operator: %s", operatorString)
}
}
return nil
}
func parseStringFilter(operatorAndValues string, stringFilter *tracee.StringFilter) error {
stringFilter.Enabled = true
if len(operatorAndValues) < 2 {
return fmt.Errorf("invalid operator and/or values given to filter: %s", operatorAndValues)
}
valuesString := string(operatorAndValues[1:])
operatorString := string(operatorAndValues[0])
if operatorString == "!" {
if len(operatorAndValues) < 3 {
return fmt.Errorf("invalid operator and/or values given to filter: %s", operatorAndValues)
}
operatorString = operatorAndValues[0:2]
valuesString = operatorAndValues[2:]
}
values := strings.Split(valuesString, ",")
for i := range values {
switch operatorString {
case "=":
stringFilter.Equal = append(stringFilter.Equal, values[i])
case "!=":
stringFilter.NotEqual = append(stringFilter.NotEqual, values[i])
default:
return fmt.Errorf("invalid filter operator: %s", operatorString)
}
}
return nil
}
func parseBoolFilter(value string, boolFilter *tracee.BoolFilter) error {
boolFilter.Enabled = true
boolFilter.Value = false
if value[0] != '!' {
boolFilter.Value = true
}
return nil
}
func parseArgFilter(filterName string, operatorAndValues string, eventsNameToID map[string]int32, argFilter *tracee.ArgFilter) error {
argFilter.Enabled = true
// Event argument filter has the following format: "event.argname=argval"
// filterName have the format event.argname, and operatorAndValues have the format "=argval"
splitFilter := strings.Split(filterName, ".")
if len(splitFilter) != 2 {
return fmt.Errorf("invalid argument filter format %s%s", filterName, operatorAndValues)
}
eventName := splitFilter[0]
argName := splitFilter[1]
id, ok := eventsNameToID[eventName]
if !ok {
return fmt.Errorf("invalid argument filter event name: %s", eventName)
}
eventParams, ok := tracee.EventsIDToParams[id]
if !ok {
return fmt.Errorf("invalid argument filter event name: %s", eventName)
}
// check if argument name exists for this event
argFound := false
for i := range eventParams {
if eventParams[i].Name == argName {
argFound = true
break
}
}
if !argFound {
return fmt.Errorf("invalid argument filter argument name: %s", argName)
}
strFilter := &tracee.StringFilter{
Equal: []string{},
NotEqual: []string{},
}
// Treat operatorAndValues as a string filter to avoid code duplication
err := parseStringFilter(operatorAndValues, strFilter)
if err != nil {
return err
}
if _, ok := argFilter.Filters[id]; !ok {
argFilter.Filters[id] = make(map[string]tracee.ArgFilterVal)
}
if _, ok := argFilter.Filters[id][argName]; !ok {
argFilter.Filters[id][argName] = tracee.ArgFilterVal{}
}
val := argFilter.Filters[id][argName]
val.Equal = append(val.Equal, strFilter.Equal...)
val.NotEqual = append(val.NotEqual, strFilter.NotEqual...)
argFilter.Filters[id][argName] = val
return nil
}
func parseRetFilter(filterName string, operatorAndValues string, eventsNameToID map[string]int32, retFilter *tracee.RetFilter) error {
retFilter.Enabled = true
// Ret filter has the following format: "event.ret=val"
// filterName have the format event.retval, and operatorAndValues have the format "=val"
splitFilter := strings.Split(filterName, ".")
if len(splitFilter) != 2 || splitFilter[1] != "retval" {
return fmt.Errorf("invalid retval filter format %s%s", filterName, operatorAndValues)
}
eventName := splitFilter[0]
id, ok := eventsNameToID[eventName]
if !ok {
return fmt.Errorf("invalid retval filter event name: %s", eventName)
}
if _, ok := retFilter.Filters[id]; !ok {
retFilter.Filters[id] = tracee.IntFilter{
Equal: []int64{},
NotEqual: []int64{},
Less: tracee.LessNotSetInt,
Greater: tracee.GreaterNotSetInt,
}
}
intFilter := retFilter.Filters[id]
// Treat operatorAndValues as an int filter to avoid code duplication
err := parseIntFilter(operatorAndValues, &intFilter)
if err != nil {
return err
}
retFilter.Filters[id] = intFilter
return nil
}
func prepareEventsToTrace(eventFilter *tracee.StringFilter, setFilter *tracee.StringFilter, eventsNameToID map[string]int32) ([]int32, error) {
eventFilter.Enabled = true
eventsToTrace := eventFilter.Equal
excludeEvents := eventFilter.NotEqual
setsToTrace := setFilter.Equal
var res []int32
setsToEvents := make(map[string][]int32)
isExcluded := make(map[int32]bool)
for id, event := range tracee.EventsIDToEvent {
for _, set := range event.Sets {
setsToEvents[set] = append(setsToEvents[set], id)
}
}
for _, name := range excludeEvents {
// Handle event prefixes with wildcards
if strings.HasSuffix(name, "*") {
found := false
prefix := name[:len(name)-1]
for event, id := range eventsNameToID {
if strings.HasPrefix(event, prefix) {
isExcluded[id] = true
found = true
}
}
if !found {
return nil, fmt.Errorf("invalid event to exclude: %s", name)
}
} else {
id, ok := eventsNameToID[name]
if !ok {
return nil, fmt.Errorf("invalid event to exclude: %s", name)
}
isExcluded[id] = true
}
}
if len(eventsToTrace) == 0 && len(setsToTrace) == 0 {
setsToTrace = append(setsToTrace, "default")
}
res = make([]int32, 0, len(tracee.EventsIDToEvent))
for _, name := range eventsToTrace {
// Handle event prefixes with wildcards
if strings.HasSuffix(name, "*") {
var ids []int32
found := false
prefix := name[:len(name)-1]
for event, id := range eventsNameToID {
if strings.HasPrefix(event, prefix) {
ids = append(ids, id)
found = true
}
}
if !found {
return nil, fmt.Errorf("invalid event to trace: %s", name)
}
res = append(res, ids...)
} else {
id, ok := eventsNameToID[name]
if !ok {
return nil, fmt.Errorf("invalid event to trace: %s", name)
}
res = append(res, id)
}
}
for _, set := range setsToTrace {
setEvents, ok := setsToEvents[set]
if !ok {
return nil, fmt.Errorf("invalid set to trace: %s", set)
}
for _, id := range setEvents {
if !isExcluded[id] {
res = append(res, id)
}
}
}
return res, nil
}
func checkRequiredCapabilities() error {
caps, err := getSelfCapabilities()
if err != nil {
return err
}
if !caps.Get(capability.EFFECTIVE, capability.CAP_SYS_ADMIN) {
return fmt.Errorf("insufficient privileges to run: missing CAP_SYS_ADMIN")
}
if !caps.Get(capability.EFFECTIVE, capability.CAP_IPC_LOCK) {
return fmt.Errorf("insufficient privileges to run: missing CAP_IPC_LOCK")
}
return nil
}
func missingKernelConfigOptions() []string {
requiredConfigOptions := map[uint32]string{
helpers.CONFIG_BPF: "y",
helpers.CONFIG_BPF_SYSCALL: "y",
helpers.CONFIG_KPROBE_EVENTS: "y",
helpers.CONFIG_BPF_EVENTS: "y",
}
kConfig := helpers.KernelConfig{}
err := kConfig.InitKernelConfig()
if err != nil {
// we were not able to get kernel config - ignore the check and try to continue
return []string{}
}
missing := []string{}
for requiredOption, setting := range requiredConfigOptions {
opt, err := kConfig.GetKernelConfigValue(requiredOption)
if err != nil {
missing = append(missing, helpers.KernelConfigKeyIDToString[requiredOption])
continue
}
if opt != setting {
missing = append(missing, helpers.KernelConfigKeyIDToString[requiredOption])
}
}
return missing
}
func getSelfCapabilities() (capability.Capabilities, error) {
cap, err := capability.NewPid2(0)
if err != nil {
return nil, err
}
err = cap.Load()
if err != nil {
return nil, err
}
return cap, nil
}
func fetchFormattedEventParams(eventID int32) string {
eventParams := tracee.EventsIDToParams[eventID]
var verboseEventParams string
verboseEventParams += "("
prefix := ""
for index, arg := range eventParams {
if index == 0 {
verboseEventParams += arg.Type + " " + arg.Name
prefix = ", "
continue
}
verboseEventParams += prefix + arg.Type + " " + arg.Name
}
verboseEventParams += ")"
return verboseEventParams
}
func getPad(padChar string, padLength int) (pad string) {
for i := 0; i < padLength; i++ {
pad += padChar
}
return
}
func printList() {
padChar, firstPadLen, secondPadLen := " ", 9, 36
titleHeaderPadFirst := getPad(padChar, firstPadLen)
titleHeaderPadSecond := getPad(padChar, secondPadLen)
var b strings.Builder
b.WriteString("System Calls: " + titleHeaderPadFirst + "Sets:" + titleHeaderPadSecond + "Arguments:\n")
b.WriteString("____________ " + titleHeaderPadFirst + "____ " + titleHeaderPadSecond + "_________" + "\n\n")
for i := 0; i < int(tracee.SysEnterEventID); i++ {
index := int32(i)
event, ok := tracee.EventsIDToEvent[index]
if !ok {
continue
}
if event.Sets != nil {
eventSets := fmt.Sprintf("%-22s %-40s %s\n", event.Name, fmt.Sprintf("%v", event.Sets), fetchFormattedEventParams(index))
b.WriteString(eventSets)
} else {
b.WriteString(event.Name + "\n")
}
}
b.WriteString("\n\nOther Events: " + titleHeaderPadFirst + "Sets:" + titleHeaderPadSecond + "Arguments:\n")
b.WriteString("____________ " + titleHeaderPadFirst + "____ " + titleHeaderPadSecond + "_________\n\n")
for i := int(tracee.SysEnterEventID); i < int(tracee.MaxEventID); i++ {
index := int32(i)
event := tracee.EventsIDToEvent[index]
if event.Sets != nil {
eventSets := fmt.Sprintf("%-22s %-40s %s\n", event.Name, fmt.Sprintf("%v", event.Sets), fetchFormattedEventParams(index))
b.WriteString(eventSets)
} else {
b.WriteString(event.Name + "\n")
}
}
fmt.Println(b.String())
}
// locateFile locates a file named file, or a directory if name is empty, and returns it's full path
// It first tries in the paths given by the dirs, and then a system lookup
func locateFile(file string, dirs []string) string {
var res string
if filepath.IsAbs(file) {
_, err := os.Stat(file)
if err == nil {
return file
}
}
for _, dir := range dirs {
if dir != "" {
fi, err := os.Stat(filepath.Join(dir, file))
if err == nil && ((file == "" && fi.IsDir()) || (file != "" && fi.Mode().IsRegular())) {
return filepath.Join(dir, file)
}
}
}
if file != "" && res == "" {
p, _ := exec.LookPath(file)
if p != "" {
return p
}
}
return ""
}
func checkTraceeBPFEnvPath() (string, error) {
bpfPath, present := os.LookupEnv("TRACEE_BPF_FILE")
if present {
if _, err := os.Stat(bpfPath); os.IsNotExist(err) {
return "", fmt.Errorf("path given in TRACEE_BPF_FILE doesn't exist!")
}
return bpfPath, nil
}
return "", nil
}
// getBPFObjectPath finds or builds ebpf object file and returns it's path
func getBPFObjectPath() (string, error) {
exePath, err := os.Executable()
if err != nil {
return "", err
}
//locations to search for the bpf file, in the following order
searchPaths := []string{
filepath.Dir(exePath),
traceeInstallPath,
}
bpfObjFileName := fmt.Sprintf("tracee.bpf.%s.%s.o", strings.ReplaceAll(tracee.UnameRelease(), ".", "_"), strings.ReplaceAll(version, ".", "_"))
bpfObjFilePath := locateFile(bpfObjFileName, searchPaths)
if bpfObjFilePath != "" && debug {
fmt.Printf("found bpf object file at: %s\n", bpfObjFilePath)
}
if (bpfObjFilePath == "" && buildPolicy != "never") || buildPolicy == "always" {
if debug {
fmt.Printf("attempting to build the bpf object file\n")
}
bpfObjInstallPath := filepath.Join(traceeInstallPath, bpfObjFileName)
err = makeBPFObject(bpfObjInstallPath)
if err != nil {
return "", err
}
if debug {
fmt.Printf("successfully built ebpf obj file into: %s\n", bpfObjInstallPath)
}
bpfObjFilePath = bpfObjInstallPath
}
if bpfObjFilePath == "" {
return "", fmt.Errorf("could not find or build the bpf object file")
}
return bpfObjFilePath, nil
}
func unpackCOREBinary() ([]byte, error) {
b, err := bpfBundleInjected.ReadFile("dist/tracee.bpf.core.o")
if err != nil {
return nil, err
}
if debug {
fmt.Println("unpacked CO:RE bpf object file into memory")
}
return b, nil
}
// unpackBPFBundle unpacks the bundle into the provided directory
func unpackBPFBundle(dir string) error {
basePath := "dist/tracee.bpf"
files, err := bpfBundleInjected.ReadDir(basePath)
if err != nil {
return fmt.Errorf("error reading embedded bpf bundle: %s", err.Error())
}
for _, f := range files {
outFile, err := os.Create(filepath.Join(dir, filepath.Base(f.Name())))
if err != nil {
return fmt.Errorf("error creating bpf file: %s", err.Error())
}
defer outFile.Close()
f, err := bpfBundleInjected.Open(filepath.Join(basePath, f.Name()))
if err != nil {
return fmt.Errorf("error opening bpf bundle file: %s", err.Error())
}
defer f.Close()
if _, err := io.Copy(outFile, f); err != nil {
return fmt.Errorf("error copying bpf file: %s", err.Error())
}
}
return nil
}
// makeBPFObject builds the ebpf object from source code into the provided path
func makeBPFObject(outFile string) error {
// drop capabilities for the compilation process
cap, err := getSelfCapabilities()
if err != nil {
return err
}
capNew, err := capability.NewPid2(0)
if err != err {
return err
}
capNew.Clear(capability.BOUNDS)
err = capNew.Apply(capability.BOUNDS)
if err != err {
return err
}
defer cap.Apply(capability.BOUNDS)
dir, err := ioutil.TempDir("", "tracee-make")
if err != nil {
return err
}
if debug {
fmt.Printf("building bpf object in: %s\n", dir)
} else {
defer os.RemoveAll(dir)
}
objFile := filepath.Join(dir, "tracee.bpf.o")
err = unpackBPFBundle(dir)
if err != nil {
return err
}
clang := locateFile("clang", []string{os.Getenv("CLANG")})
if clang == "" {
return fmt.Errorf("missing compilation dependency: clang")
}
cmdVer := exec.Command(clang, "--version")
verOut, err := cmdVer.CombinedOutput()
if err != nil {
return err
}
// we are looking for the "version x.y.z" part in the text output
start := strings.Index(string(verOut), "version") + 8
end := strings.Index(string(verOut), "\n")
verStr := string(verOut[start:end])
verMajor, err := strconv.Atoi(strings.SplitN(verStr, ".", 2)[0])
if err != nil {
if debug {
fmt.Printf("warning: could not detect clang version from: %s", string(verOut))
}
} else if verMajor < 9 {
return fmt.Errorf("detected clang version: %d is older than required minimum version: 9", verMajor)
}
llc := locateFile("llc", []string{os.Getenv("LLC")})
if llc == "" {
return fmt.Errorf("missing compilation dependency: llc")
}
llvmstrip := locateFile("llvm-strip", []string{os.Getenv("LLVM_STRIP")})
kernelHeaders := locateFile("", []string{os.Getenv("KERN_HEADERS")})
kernelBuildPath := locateFile("", []string{fmt.Sprintf("/lib/modules/%s/build", tracee.UnameRelease())})
kernelSourcePath := locateFile("", []string{fmt.Sprintf("/lib/modules/%s/source", tracee.UnameRelease())})
if kernelHeaders != "" {
// In case KERN_HEADERS is set, use it for both source/ and build/
kernelBuildPath = kernelHeaders
kernelSourcePath = kernelHeaders
}
if kernelBuildPath == "" {
return fmt.Errorf("missing kernel source code compilation dependency")
}
// In some distros (e.g. debian, suse), kernel headers are split to build/ and source/
// while in others (e.g. ubuntu, arch), all headers will be located under build/
if kernelSourcePath == "" {
kernelSourcePath = kernelBuildPath
}
linuxArch := os.Getenv("ARCH")
if linuxArch == "" {
linuxArch = strings.Replace(runtime.GOARCH, "amd64", "x86", 1)
}
// from the Makefile:
// $(CLANG) -S \
// -D__BPF_TRACING__ \
// -D__KERNEL__ \
// -D__TARGET_ARCH_$(linux_arch) \
// -I $(LIBBPF_HEADERS)/bpf \
// -include $(KERN_SRC_PATH)/include/linux/kconfig.h \
// -I $(KERN_SRC_PATH)/arch/$(linux_arch)/include \
// -I $(KERN_SRC_PATH)/arch/$(linux_arch)/include/uapi \
// -I $(KERN_BLD_PATH)/arch/$(linux_arch)/include/generated \
// -I $(KERN_BLD_PATH)/arch/$(linux_arch)/include/generated/uapi \
// -I $(KERN_SRC_PATH)/include \
// -I $(KERN_BLD_PATH)/include \
// -I $(KERN_SRC_PATH)/include/uapi \
// -I $(KERN_BLD_PATH)/include/generated \
// -I $(KERN_BLD_PATH)/include/generated/uapi \
// -I $(BPF_HEADERS) \
// -Wno-address-of-packed-member \
// -Wno-compare-distinct-pointer-types \
// -Wno-deprecated-declarations \
// -Wno-gnu-variable-sized-type-not-at-end \
// -Wno-pointer-sign \
// -Wno-pragma-once-outside-heade \
// -Wno-unknown-warning-option \
// -Wno-unused-value \
// -Wunused \
// -Wall \
// -fno-stack-protector \
// -fno-jump-tables \
// -fno-unwind-tables \
// -fno-asynchronous-unwind-tables \
// -xc \
// -nostdinc \
// -O2 -emit-llvm -c -g $< -o $(@:.o=.ll)
intermediateFile := strings.Replace(objFile, ".o", ".ll", 1)
// TODO: validate all files/directories. perhaps using locateFile
cmd1 := exec.Command(clang,
"-S",
"-D__BPF_TRACING__",
"-D__KERNEL__",
fmt.Sprintf("-D__TARGET_ARCH_%s", linuxArch),
fmt.Sprintf("-I%s", dir),
fmt.Sprintf("-include%s/include/linux/kconfig.h", kernelSourcePath),
fmt.Sprintf("-I%s/arch/%s/include", kernelSourcePath, linuxArch),
fmt.Sprintf("-I%s/arch/%s/include/uapi", kernelSourcePath, linuxArch),
fmt.Sprintf("-I%s/arch/%s/include/generated", kernelBuildPath, linuxArch),
fmt.Sprintf("-I%s/arch/%s/include/generated/uapi", kernelBuildPath, linuxArch),
fmt.Sprintf("-I%s/include", kernelSourcePath),
fmt.Sprintf("-I%s/include", kernelBuildPath),
fmt.Sprintf("-I%s/include/uapi", kernelSourcePath),
fmt.Sprintf("-I%s/include/generated", kernelBuildPath),
fmt.Sprintf("-I%s/include/generated/uapi", kernelBuildPath),
"-Wno-address-of-packed-member",
"-Wno-compare-distinct-pointer-types",
"-Wno-deprecated-declarations",
"-Wno-gnu-variable-sized-type-not-at-end",
"-Wno-pointer-sign",
"-Wno-pragma-once-outside-heade",
"-Wno-unknown-warning-option",
"-Wno-unused-value",
"-Wunused",
"-Wall",
"-fno-stack-protector",
"-fno-jump-tables",
"-fno-unwind-tables",
"-fno-asynchronous-unwind-tables",
"-xc",
"-nostdinc", "-O2", "-emit-llvm", "-c", "-g", filepath.Join(dir, "tracee.bpf.c"), fmt.Sprintf("-o%s", intermediateFile),
)
cmd1.Dir = dir
if debug {
fmt.Println(cmd1)
cmd1.Stdout = os.Stdout
cmd1.Stderr = os.Stderr
}
err = cmd1.Run()
if err != nil {
return fmt.Errorf("failed to make BPF object (clang): %v. Try using --debug for more info", err)
}
// from Makefile:
// $(LLC) -march=bpf -filetype=obj -o $@ $(@:.o=.ll)
cmd2 := exec.Command(llc,
"-march=bpf",
"-filetype=obj",
"-o", objFile,
intermediateFile,
)
cmd2.Dir = dir
if debug {
fmt.Println(cmd2)
cmd2.Stdout = os.Stdout
cmd2.Stderr = os.Stderr
}
err = cmd2.Run()
if err != nil {
return fmt.Errorf("failed to make BPF object (llc): %v. Try using --debug for more info", err)
}
// from Makefile:
// -$(LLVM_STRIP) -g $@
if llvmstrip != "" {
cmd3 := exec.Command(llvmstrip,
"-g", objFile,
)
cmd3.Dir = dir
if debug {
fmt.Println(cmd3)
cmd3.Stdout = os.Stdout
cmd3.Stderr = os.Stderr
}
err = cmd3.Run()
if err != nil {
return fmt.Errorf("failed to make BPF object (llvm-strip): %v. Try using --debug for more info", err)
}
}
if debug {
fmt.Printf("successfully built ebpf obj file at: %s\n", objFile)
}
os.MkdirAll(filepath.Dir(outFile), 0755)
err = tracee.CopyFileByPath(objFile, outFile)
if err != nil {
return err
}
return nil
}
func btfEnabled() bool {
_, err := os.Stat("/sys/kernel/btf/vmlinux")
return err == nil
}
| [
"\"CLANG\"",
"\"LLC\"",
"\"LLVM_STRIP\"",
"\"KERN_HEADERS\"",
"\"ARCH\""
]
| []
| [
"LLVM_STRIP",
"LLC",
"KERN_HEADERS",
"ARCH",
"CLANG"
]
| [] | ["LLVM_STRIP", "LLC", "KERN_HEADERS", "ARCH", "CLANG"] | go | 5 | 0 | |
instaloader/instaloader.py | import getpass
import json
import os
import platform
import re
import shutil
import string
import sys
import tempfile
from contextlib import contextmanager, suppress
from datetime import datetime, timezone
from functools import wraps
from io import BytesIO
from pathlib import Path
from typing import Any, Callable, IO, Iterator, List, Optional, Set, Union, cast
from urllib.parse import urlparse
import requests
import urllib3 # type: ignore
from .exceptions import *
from .instaloadercontext import InstaloaderContext, RateController
from .lateststamps import LatestStamps
from .nodeiterator import NodeIterator, resumable_iteration
from .structures import (Hashtag, Highlight, JsonExportable, Post, PostLocation, Profile, Story, StoryItem,
load_structure_from_file, save_structure_to_file, PostSidecarNode, TitlePic)
def _get_config_dir() -> str:
if platform.system() == "Windows":
# on Windows, use %LOCALAPPDATA%\Instaloader
localappdata = os.getenv("LOCALAPPDATA")
if localappdata is not None:
return os.path.join(localappdata, "Instaloader")
# legacy fallback - store in temp dir if %LOCALAPPDATA% is not set
return os.path.join(tempfile.gettempdir(), ".instaloader-" + getpass.getuser())
# on Unix, use ~/.config/instaloader
return os.path.join(os.getenv("XDG_CONFIG_HOME", os.path.expanduser("~/.config")), "instaloader")
def get_default_session_filename(username: str) -> str:
"""Returns default session filename for given username."""
configdir = _get_config_dir()
sessionfilename = "session-{}".format(username)
return os.path.join(configdir, sessionfilename)
def get_legacy_session_filename(username: str) -> str:
"""Returns legacy (until v4.4.3) default session filename for given username."""
dirname = tempfile.gettempdir() + "/" + ".instaloader-" + getpass.getuser()
filename = dirname + "/" + "session-" + username
return filename.lower()
def get_default_stamps_filename() -> str:
"""
Returns default filename for latest stamps database.
.. versionadded:: 4.8
"""
configdir = _get_config_dir()
return os.path.join(configdir, "latest-stamps.ini")
def format_string_contains_key(format_string: str, key: str) -> bool:
# pylint:disable=unused-variable
for literal_text, field_name, format_spec, conversion in string.Formatter().parse(format_string):
if field_name and (field_name == key or field_name.startswith(key + '.')):
return True
return False
def _requires_login(func: Callable) -> Callable:
"""Decorator to raise an exception if herewith-decorated function is called without being logged in"""
@wraps(func)
def call(instaloader, *args, **kwargs):
if not instaloader.context.is_logged_in:
raise LoginRequiredException("--login=USERNAME required.")
return func(instaloader, *args, **kwargs)
return call
def _retry_on_connection_error(func: Callable) -> Callable:
"""Decorator to retry the function max_connection_attemps number of times.
Herewith-decorated functions need an ``_attempt`` keyword argument.
This is to decorate functions that do network requests that may fail. Note that
:meth:`.get_json`, :meth:`.get_iphone_json`, :meth:`.graphql_query` and :meth:`.graphql_node_list` already have
their own logic for retrying, hence functions that only use these for network access must not be decorated with this
decorator."""
@wraps(func)
def call(instaloader, *args, **kwargs):
try:
return func(instaloader, *args, **kwargs)
except (urllib3.exceptions.HTTPError, requests.exceptions.RequestException, ConnectionException) as err:
error_string = "{}({}): {}".format(func.__name__, ', '.join([repr(arg) for arg in args]), err)
if (kwargs.get('_attempt') or 1) == instaloader.context.max_connection_attempts:
raise ConnectionException(error_string) from None
instaloader.context.error(error_string + " [retrying; skip with ^C]", repeat_at_end=False)
try:
if kwargs.get('_attempt'):
kwargs['_attempt'] += 1
else:
kwargs['_attempt'] = 2
instaloader.context.do_sleep()
return call(instaloader, *args, **kwargs)
except KeyboardInterrupt:
instaloader.context.error("[skipped by user]", repeat_at_end=False)
raise ConnectionException(error_string) from None
return call
class _ArbitraryItemFormatter(string.Formatter):
def __init__(self, item: Any):
self._item = item
def get_value(self, key, args, kwargs):
"""Override to substitute {ATTRIBUTE} by attributes of our _item."""
if key == 'filename' and isinstance(self._item, (Post, StoryItem, PostSidecarNode, TitlePic)):
return "{filename}"
if hasattr(self._item, key):
return getattr(self._item, key)
return super().get_value(key, args, kwargs)
def format_field(self, value, format_spec):
"""Override :meth:`string.Formatter.format_field` to have our
default format_spec for :class:`datetime.Datetime` objects, and to
let None yield an empty string rather than ``None``."""
if isinstance(value, datetime) and not format_spec:
return super().format_field(value, '%Y-%m-%d_%H-%M-%S')
if value is None:
return ''
return super().format_field(value, format_spec)
class _PostPathFormatter(_ArbitraryItemFormatter):
def get_value(self, key, args, kwargs):
ret = super().get_value(key, args, kwargs)
if not isinstance(ret, str):
return ret
return self.sanitize_path(ret)
@staticmethod
def sanitize_path(ret: str) -> str:
"""Replaces '/' with similar looking Division Slash and some other illegal filename characters on Windows."""
ret = ret.replace('/', '\u2215')
if platform.system() == 'Windows':
ret = ret.replace(':', '\uff1a').replace('<', '\ufe64').replace('>', '\ufe65').replace('\"', '\uff02')
ret = ret.replace('\\', '\ufe68').replace('|', '\uff5c').replace('?', '\ufe16').replace('*', '\uff0a')
ret = ret.replace('\n', ' ').replace('\r', ' ')
return ret
class Instaloader:
"""Instaloader Class.
:param quiet: :option:`--quiet`
:param user_agent: :option:`--user-agent`
:param dirname_pattern: :option:`--dirname-pattern`, default is ``{target}``
:param filename_pattern: :option:`--filename-pattern`, default is ``{date_utc}_UTC``
:param title_pattern:
:option:`--title-pattern`, default is ``{date_utc}_UTC_{typename}`` if ``dirname_pattern`` contains
``{target}`` or ``{profile}``, ``{target}_{date_utc}_UTC_{typename}`` otherwise.
:param download_pictures: not :option:`--no-pictures`
:param download_videos: not :option:`--no-videos`
:param download_video_thumbnails: not :option:`--no-video-thumbnails`
:param download_geotags: :option:`--geotags`
:param download_comments: :option:`--comments`
:param save_metadata: not :option:`--no-metadata-json`
:param compress_json: not :option:`--no-compress-json`
:param post_metadata_txt_pattern:
:option:`--post-metadata-txt`, default is ``{caption}``. Set to empty string to avoid creation of post metadata
txt file.
:param storyitem_metadata_txt_pattern: :option:`--storyitem-metadata-txt`, default is empty (=none)
:param max_connection_attempts: :option:`--max-connection-attempts`
:param request_timeout: :option:`--request-timeout`, set per-request timeout (seconds)
:param rate_controller: Generator for a :class:`RateController` to override rate controlling behavior
:param resume_prefix: :option:`--resume-prefix`, or None for :option:`--no-resume`.
:param check_resume_bbd: Whether to check the date of expiry of resume files and reject them if expired.
:param slide: :option:`--slide`
:param fatal_status_codes: :option:`--abort-on`
:param iphone_support: not :option:`--no-iphone`
.. attribute:: context
The associated :class:`InstaloaderContext` with low-level communication functions and logging.
"""
def __init__(self,
sleep: bool = True,
quiet: bool = False,
user_agent: Optional[str] = None,
dirname_pattern: Optional[str] = None,
filename_pattern: Optional[str] = None,
download_pictures=True,
download_videos: bool = True,
download_video_thumbnails: bool = True,
download_geotags: bool = False,
download_comments: bool = False,
save_metadata: bool = True,
compress_json: bool = True,
post_metadata_txt_pattern: str = None,
storyitem_metadata_txt_pattern: str = None,
max_connection_attempts: int = 3,
request_timeout: float = 300.0,
rate_controller: Optional[Callable[[InstaloaderContext], RateController]] = None,
resume_prefix: Optional[str] = "iterator",
check_resume_bbd: bool = True,
slide: Optional[str] = None,
fatal_status_codes: Optional[List[int]] = None,
iphone_support: bool = True,
title_pattern: Optional[str] = None):
self.context = InstaloaderContext(sleep, quiet, user_agent, max_connection_attempts,
request_timeout, rate_controller, fatal_status_codes,
iphone_support)
# configuration parameters
self.dirname_pattern = dirname_pattern or "{target}"
self.filename_pattern = filename_pattern or "{date_utc}_UTC"
if title_pattern is not None:
self.title_pattern = title_pattern
else:
if (format_string_contains_key(self.dirname_pattern, 'profile') or
format_string_contains_key(self.dirname_pattern, 'target')):
self.title_pattern = '{date_utc}_UTC_{typename}'
else:
self.title_pattern = '{target}_{date_utc}_UTC_{typename}'
self.download_pictures = download_pictures
self.download_videos = download_videos
self.download_video_thumbnails = download_video_thumbnails
self.download_geotags = download_geotags
self.download_comments = download_comments
self.save_metadata = save_metadata
self.compress_json = compress_json
self.post_metadata_txt_pattern = '{caption}' if post_metadata_txt_pattern is None \
else post_metadata_txt_pattern
self.storyitem_metadata_txt_pattern = '' if storyitem_metadata_txt_pattern is None \
else storyitem_metadata_txt_pattern
self.resume_prefix = resume_prefix
self.check_resume_bbd = check_resume_bbd
self.slide = slide or ""
self.slide_start = 0
self.slide_end = -1
if self.slide != "":
splitted = self.slide.split('-')
if len(splitted) == 1:
if splitted[0] == 'last':
# download only last image of a sidecar
self.slide_start = -1
else:
if int(splitted[0]) > 0:
self.slide_start = self.slide_end = int(splitted[0])-1
else:
raise InvalidArgumentException("--slide parameter must be greater than 0.")
elif len(splitted) == 2:
if splitted[1] == 'last':
self.slide_start = int(splitted[0])-1
elif 0 < int(splitted[0]) < int(splitted[1]):
self.slide_start = int(splitted[0])-1
self.slide_end = int(splitted[1])-1
else:
raise InvalidArgumentException("Invalid data for --slide parameter.")
else:
raise InvalidArgumentException("Invalid data for --slide parameter.")
@contextmanager
def anonymous_copy(self):
"""Yield an anonymous, otherwise equally-configured copy of an Instaloader instance; Then copy its error log."""
new_loader = Instaloader(
sleep=self.context.sleep,
quiet=self.context.quiet,
user_agent=self.context.user_agent,
dirname_pattern=self.dirname_pattern,
filename_pattern=self.filename_pattern,
download_pictures=self.download_pictures,
download_videos=self.download_videos,
download_video_thumbnails=self.download_video_thumbnails,
download_geotags=self.download_geotags,
download_comments=self.download_comments,
save_metadata=self.save_metadata,
compress_json=self.compress_json,
post_metadata_txt_pattern=self.post_metadata_txt_pattern,
storyitem_metadata_txt_pattern=self.storyitem_metadata_txt_pattern,
max_connection_attempts=self.context.max_connection_attempts,
request_timeout=self.context.request_timeout,
resume_prefix=self.resume_prefix,
check_resume_bbd=self.check_resume_bbd,
slide=self.slide,
fatal_status_codes=self.context.fatal_status_codes,
iphone_support=self.context.iphone_support)
yield new_loader
self.context.error_log.extend(new_loader.context.error_log)
new_loader.context.error_log = [] # avoid double-printing of errors
new_loader.close()
def close(self):
"""Close associated session objects and repeat error log."""
self.context.close()
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
@_retry_on_connection_error
def download_pic(self, filename: str, url: str, mtime: datetime,
filename_suffix: Optional[str] = None, _attempt: int = 1) -> bool:
"""Downloads and saves picture with given url under given directory with given timestamp.
Returns true, if file was actually downloaded, i.e. updated."""
if filename_suffix is not None:
filename += '_' + filename_suffix
urlmatch = re.search('\\.[a-z0-9]*\\?', url)
file_extension = url[-3:] if urlmatch is None else urlmatch.group(0)[1:-1]
nominal_filename = filename + '.' + file_extension
if os.path.isfile(nominal_filename):
self.context.log(nominal_filename + ' exists', end=' ', flush=True)
return False
resp = self.context.get_raw(url)
if 'Content-Type' in resp.headers and resp.headers['Content-Type']:
header_extension = '.' + resp.headers['Content-Type'].split(';')[0].split('/')[-1]
header_extension = header_extension.lower().replace('jpeg', 'jpg')
filename += header_extension
else:
filename = nominal_filename
if filename != nominal_filename and os.path.isfile(filename):
self.context.log(filename + ' exists', end=' ', flush=True)
return False
self.context.write_raw(resp, filename)
os.utime(filename, (datetime.now().timestamp(), mtime.timestamp()))
return True
def save_metadata_json(self, filename: str, structure: JsonExportable) -> None:
"""Saves metadata JSON file of a structure."""
if self.compress_json:
filename += '.json.xz'
else:
filename += '.json'
os.makedirs(os.path.dirname(filename), exist_ok=True)
save_structure_to_file(structure, filename)
if isinstance(structure, (Post, StoryItem)):
# log 'json ' message when saving Post or StoryItem
self.context.log('json', end=' ', flush=True)
def update_comments(self, filename: str, post: Post) -> None:
def _postcommentanswer_asdict(comment):
return {'id': comment.id,
'created_at': int(comment.created_at_utc.replace(tzinfo=timezone.utc).timestamp()),
'text': comment.text,
'owner': comment.owner._asdict(),
'likes_count': comment.likes_count}
def _postcomment_asdict(comment):
return {**_postcommentanswer_asdict(comment),
'answers': sorted([_postcommentanswer_asdict(answer) for answer in comment.answers],
key=lambda t: int(t['id']),
reverse=True)}
def get_unique_comments(comments, combine_answers=False):
if not comments:
return list()
comments_list = sorted(sorted(list(comments), key=lambda t: int(t['id'])),
key=lambda t: int(t['created_at']), reverse=True)
unique_comments_list = [comments_list[0]]
for x, y in zip(comments_list[:-1], comments_list[1:]):
if x['id'] != y['id']:
unique_comments_list.append(y)
else:
unique_comments_list[-1]['likes_count'] = y.get('likes_count')
if combine_answers:
combined_answers = unique_comments_list[-1].get('answers') or list()
if 'answers' in y:
combined_answers.extend(y['answers'])
unique_comments_list[-1]['answers'] = get_unique_comments(combined_answers)
return unique_comments_list
def get_new_comments(new_comments, start):
for idx, comment in enumerate(new_comments, start=start+1):
if idx % 250 == 0:
self.context.log('{}'.format(idx), end='…', flush=True)
yield comment
def save_comments(extended_comments):
unique_comments = get_unique_comments(extended_comments, combine_answers=True)
answer_ids = set(int(answer['id']) for comment in unique_comments for answer in comment.get('answers', []))
with open(filename, 'w') as file:
file.write(json.dumps(list(filter(lambda t: int(t['id']) not in answer_ids, unique_comments)),
indent=4))
base_filename = filename
filename += '_comments.json'
try:
with open(filename) as fp:
comments = json.load(fp)
except (FileNotFoundError, json.decoder.JSONDecodeError):
comments = list()
comments_iterator = post.get_comments()
try:
with resumable_iteration(
context=self.context,
iterator=comments_iterator,
load=load_structure_from_file,
save=save_structure_to_file,
format_path=lambda magic: "{}_{}_{}.json.xz".format(base_filename, self.resume_prefix, magic),
check_bbd=self.check_resume_bbd,
enabled=self.resume_prefix is not None
) as (_is_resuming, start_index):
comments.extend(_postcomment_asdict(comment)
for comment in get_new_comments(comments_iterator, start_index))
except (KeyboardInterrupt, AbortDownloadException):
if comments:
save_comments(comments)
raise
if comments:
save_comments(comments)
self.context.log('comments', end=' ', flush=True)
def save_caption(self, filename: str, mtime: datetime, caption: str) -> None:
"""Updates picture caption / Post metadata info"""
def _elliptify(caption):
pcaption = caption.replace('\n', ' ').strip()
return '[' + ((pcaption[:29] + u"\u2026") if len(pcaption) > 31 else pcaption) + ']'
filename += '.txt'
caption += '\n'
pcaption = _elliptify(caption)
bcaption = caption.encode("UTF-8")
with suppress(FileNotFoundError):
with open(filename, 'rb') as file:
file_caption = file.read()
if file_caption.replace(b'\r\n', b'\n') == bcaption.replace(b'\r\n', b'\n'):
try:
self.context.log(pcaption + ' unchanged', end=' ', flush=True)
except UnicodeEncodeError:
self.context.log('txt unchanged', end=' ', flush=True)
return None
else:
def get_filename(index):
return filename if index == 0 else '{0}_old_{2:02}{1}'.format(*os.path.splitext(filename), index)
i = 0
while os.path.isfile(get_filename(i)):
i = i + 1
for index in range(i, 0, -1):
os.rename(get_filename(index - 1), get_filename(index))
try:
self.context.log(_elliptify(file_caption.decode("UTF-8")) + ' updated', end=' ', flush=True)
except UnicodeEncodeError:
self.context.log('txt updated', end=' ', flush=True)
try:
self.context.log(pcaption, end=' ', flush=True)
except UnicodeEncodeError:
self.context.log('txt', end=' ', flush=True)
with open(filename, 'wb') as text_file:
with BytesIO(bcaption) as bio:
shutil.copyfileobj(cast(IO, bio), text_file)
os.utime(filename, (datetime.now().timestamp(), mtime.timestamp()))
def save_location(self, filename: str, location: PostLocation, mtime: datetime) -> None:
"""Save post location name and Google Maps link."""
filename += '_location.txt'
if location.lat is not None and location.lng is not None:
location_string = (location.name + "\n" +
"https://maps.google.com/maps?q={0},{1}&ll={0},{1}\n".format(location.lat,
location.lng))
else:
location_string = location.name
with open(filename, 'wb') as text_file:
with BytesIO(location_string.encode()) as bio:
shutil.copyfileobj(cast(IO, bio), text_file)
os.utime(filename, (datetime.now().timestamp(), mtime.timestamp()))
self.context.log('geo', end=' ', flush=True)
def format_filename_within_target_path(self,
target: Union[str, Path],
owner_profile: Optional[Profile],
identifier: str,
name_suffix: str,
extension: str):
"""Returns a filename within the target path.
.. versionadded:: 4.5"""
if ((format_string_contains_key(self.dirname_pattern, 'profile') or
format_string_contains_key(self.dirname_pattern, 'target'))):
profile_str = owner_profile.username.lower() if owner_profile is not None else target
return os.path.join(self.dirname_pattern.format(profile=profile_str, target=target),
'{0}_{1}.{2}'.format(identifier, name_suffix, extension))
else:
return os.path.join(self.dirname_pattern.format(),
'{0}_{1}_{2}.{3}'.format(target, identifier, name_suffix, extension))
@_retry_on_connection_error
def download_title_pic(self, url: str, target: Union[str, Path], name_suffix: str, owner_profile: Optional[Profile],
_attempt: int = 1) -> None:
"""Downloads and saves a picture that does not have an association with a Post or StoryItem, such as a
Profile picture or a Highlight cover picture. Modification time is taken from the HTTP response headers.
.. versionadded:: 4.3"""
http_response = self.context.get_raw(url)
date_object = None # type: Optional[datetime]
if 'Last-Modified' in http_response.headers:
date_object = datetime.strptime(http_response.headers["Last-Modified"], '%a, %d %b %Y %H:%M:%S GMT')
date_object = date_object.replace(tzinfo=timezone.utc)
pic_bytes = None
else:
pic_bytes = http_response.content
ig_filename = url.split('/')[-1].split('?')[0]
pic_data = TitlePic(owner_profile, target, name_suffix, ig_filename, date_object)
dirname = _PostPathFormatter(pic_data).format(self.dirname_pattern, target=target)
filename_template = os.path.join(dirname,
_PostPathFormatter(pic_data).format(self.title_pattern, target=target))
filename = self.__prepare_filename(filename_template, lambda: url) + ".jpg"
content_length = http_response.headers.get('Content-Length', None)
if os.path.isfile(filename) and (not self.context.is_logged_in or
(content_length is not None and
os.path.getsize(filename) >= int(content_length))):
self.context.log(filename + ' already exists')
return
os.makedirs(os.path.dirname(filename), exist_ok=True)
self.context.write_raw(pic_bytes if pic_bytes else http_response, filename)
if date_object:
os.utime(filename, (datetime.now().timestamp(), date_object.timestamp()))
self.context.log('') # log output of _get_and_write_raw() does not produce \n
def download_profilepic_if_new(self, profile: Profile, latest_stamps: Optional[LatestStamps]) -> None:
"""
Downloads and saves profile pic if it has not been downloaded before.
:param latest_stamps: Database with the last downloaded data. If not present,
the profile pic is downloaded unless it already exists
.. versionadded:: 4.8
"""
if latest_stamps is None:
self.download_profilepic(profile)
return
profile_pic_basename = profile.profile_pic_url.split('/')[-1].split('?')[0]
saved_basename = latest_stamps.get_profile_pic(profile.username)
if saved_basename == profile_pic_basename:
return
self.download_profilepic(profile)
latest_stamps.set_profile_pic(profile.username, profile_pic_basename)
def download_profilepic(self, profile: Profile) -> None:
"""Downloads and saves profile pic."""
self.download_title_pic(profile.profile_pic_url, profile.username.lower(), 'profile_pic', profile)
def download_highlight_cover(self, highlight: Highlight, target: Union[str, Path]) -> None:
"""Downloads and saves Highlight cover picture.
.. versionadded:: 4.3"""
self.download_title_pic(highlight.cover_url, target, 'cover', highlight.owner_profile)
def download_hashtag_profilepic(self, hashtag: Hashtag) -> None:
"""Downloads and saves the profile picture of a Hashtag.
.. versionadded:: 4.4"""
self.download_title_pic(hashtag.profile_pic_url, '#' + hashtag.name, 'profile_pic', None)
@_requires_login
def save_session_to_file(self, filename: Optional[str] = None) -> None:
"""Saves internally stored :class:`requests.Session` object.
:param filename: Filename, or None to use default filename.
:raises LoginRequiredException: If called without being logged in.
"""
if filename is None:
assert self.context.username is not None
filename = get_default_session_filename(self.context.username)
dirname = os.path.dirname(filename)
if dirname != '' and not os.path.exists(dirname):
os.makedirs(dirname)
os.chmod(dirname, 0o700)
with open(filename, 'wb') as sessionfile:
os.chmod(filename, 0o600)
self.context.save_session_to_file(sessionfile)
self.context.log("Saved session to %s." % filename)
def load_session_from_file(self, username: str, filename: Optional[str] = None) -> None:
"""Internally stores :class:`requests.Session` object loaded from file.
If filename is None, the file with the default session path is loaded.
:raises FileNotFoundError: If the file does not exist.
"""
if filename is None:
filename = get_default_session_filename(username)
if not os.path.exists(filename):
filename = get_legacy_session_filename(username)
with open(filename, 'rb') as sessionfile:
self.context.load_session_from_file(username, sessionfile)
self.context.log("Loaded session from %s." % filename)
def test_login(self) -> Optional[str]:
"""Returns the Instagram username to which given :class:`requests.Session` object belongs, or None."""
return self.context.test_login()
def login(self, user: str, passwd: str) -> None:
"""Log in to instagram with given username and password and internally store session object.
:raises InvalidArgumentException: If the provided username does not exist.
:raises BadCredentialsException: If the provided password is wrong.
:raises ConnectionException: If connection to Instagram failed.
:raises TwoFactorAuthRequiredException: First step of 2FA login done, now call
:meth:`Instaloader.two_factor_login`."""
self.context.login(user, passwd)
def two_factor_login(self, two_factor_code) -> None:
"""Second step of login if 2FA is enabled.
Not meant to be used directly, use :meth:`Instaloader.two_factor_login`.
:raises InvalidArgumentException: No two-factor authentication pending.
:raises BadCredentialsException: 2FA verification code invalid.
.. versionadded:: 4.2"""
self.context.two_factor_login(two_factor_code)
@staticmethod
def __prepare_filename(filename_template: str, url: Callable[[], str]) -> str:
"""Replace filename token inside filename_template with url's filename and assure the directories exist.
.. versionadded:: 4.6"""
if "{filename}" in filename_template:
filename = filename_template.replace("{filename}",
os.path.splitext(os.path.basename(urlparse(url()).path))[0])
else:
filename = filename_template
os.makedirs(os.path.dirname(filename), exist_ok=True)
return filename
def format_filename(self, item: Union[Post, StoryItem, PostSidecarNode, TitlePic],
target: Optional[Union[str, Path]] = None):
"""Format filename of a :class:`Post` or :class:`StoryItem` according to ``filename-pattern`` parameter.
.. versionadded:: 4.1"""
return _PostPathFormatter(item).format(self.filename_pattern, target=target)
def download_post(self, post: Post, target: Union[str, Path]) -> bool:
"""
Download everything associated with one instagram post node, i.e. picture, caption and video.
:param post: Post to download.
:param target: Target name, i.e. profile name, #hashtag, :feed; for filename.
:return: True if something was downloaded, False otherwise, i.e. file was already there
"""
def _already_downloaded(path: str) -> bool:
if not os.path.isfile(path):
return False
else:
self.context.log(path + ' exists', end=' ', flush=True)
return True
def _all_already_downloaded(path_base, is_videos_enumerated) -> bool:
if '{filename}' in self.filename_pattern:
# full URL needed to evaluate actual filename, cannot determine at
# this point if all sidecar nodes were already downloaded.
return False
for idx, is_video in is_videos_enumerated:
if self.download_pictures and (not is_video or self.download_video_thumbnails):
if not _already_downloaded("{0}_{1}.jpg".format(path_base, idx)):
return False
if is_video and self.download_videos:
if not _already_downloaded("{0}_{1}.mp4".format(path_base, idx)):
return False
return True
dirname = _PostPathFormatter(post).format(self.dirname_pattern, target=target)
filename_template = os.path.join(dirname, self.format_filename(post, target=target))
filename = self.__prepare_filename(filename_template, lambda: post.url)
# Download the image(s) / video thumbnail and videos within sidecars if desired
downloaded = True
if post.typename == 'GraphSidecar':
if self.download_pictures or self.download_videos:
if not _all_already_downloaded(
filename_template, enumerate(
(post.get_is_videos()[i]
for i in range(self.slide_start % post.mediacount, self.slide_end % post.mediacount + 1)),
start=self.slide_start % post.mediacount + 1
)
):
for edge_number, sidecar_node in enumerate(
post.get_sidecar_nodes(self.slide_start, self.slide_end),
start=self.slide_start % post.mediacount + 1
):
suffix = str(edge_number) # type: Optional[str]
if '{filename}' in self.filename_pattern:
suffix = None
if self.download_pictures and (not sidecar_node.is_video or self.download_video_thumbnails):
# pylint:disable=cell-var-from-loop
sidecar_filename = self.__prepare_filename(filename_template,
lambda: sidecar_node.display_url)
# Download sidecar picture or video thumbnail (--no-pictures implies --no-video-thumbnails)
downloaded &= self.download_pic(filename=sidecar_filename, url=sidecar_node.display_url,
mtime=post.date_local, filename_suffix=suffix)
if sidecar_node.is_video and self.download_videos:
# pylint:disable=cell-var-from-loop
sidecar_filename = self.__prepare_filename(filename_template,
lambda: sidecar_node.video_url)
# Download sidecar video if desired
downloaded &= self.download_pic(filename=sidecar_filename, url=sidecar_node.video_url,
mtime=post.date_local, filename_suffix=suffix)
else:
downloaded = False
elif post.typename == 'GraphImage':
# Download picture
if self.download_pictures:
downloaded = (not _already_downloaded(filename + ".jpg") and
self.download_pic(filename=filename, url=post.url, mtime=post.date_local))
elif post.typename == 'GraphVideo':
# Download video thumbnail (--no-pictures implies --no-video-thumbnails)
if self.download_pictures and self.download_video_thumbnails:
with self.context.error_catcher("Video thumbnail of {}".format(post)):
downloaded = (not _already_downloaded(filename + ".jpg") and
self.download_pic(filename=filename, url=post.url, mtime=post.date_local))
else:
self.context.error("Warning: {0} has unknown typename: {1}".format(post, post.typename))
# Save caption if desired
metadata_string = _ArbitraryItemFormatter(post).format(self.post_metadata_txt_pattern).strip()
if metadata_string:
self.save_caption(filename=filename, mtime=post.date_local, caption=metadata_string)
# Download video if desired
if post.is_video and self.download_videos:
downloaded &= (not _already_downloaded(filename + ".mp4") and
self.download_pic(filename=filename, url=post.video_url, mtime=post.date_local))
# Download geotags if desired
if self.download_geotags and post.location:
self.save_location(filename, post.location, post.date_local)
# Update comments if desired
if self.download_comments:
self.update_comments(filename=filename, post=post)
# Save metadata as JSON if desired.
if self.save_metadata:
self.save_metadata_json(filename, post)
self.context.log()
return downloaded
@_requires_login
def get_stories(self, userids: Optional[List[int]] = None) -> Iterator[Story]:
"""Get available stories from followees or all stories of users whose ID are given.
Does not mark stories as seen.
To use this, one needs to be logged in
:param userids: List of user IDs to be processed in terms of downloading their stories, or None.
:raises LoginRequiredException: If called without being logged in.
"""
if not userids:
data = self.context.graphql_query("d15efd8c0c5b23f0ef71f18bf363c704",
{"only_stories": True})["data"]["user"]
if data is None:
raise BadResponseException('Bad stories reel JSON.')
userids = list(edge["node"]["id"] for edge in data["feed_reels_tray"]["edge_reels_tray_to_reel"]["edges"])
def _userid_chunks():
assert userids is not None
userids_per_query = 50
for i in range(0, len(userids), userids_per_query):
yield userids[i:i + userids_per_query]
for userid_chunk in _userid_chunks():
stories = self.context.graphql_query("303a4ae99711322310f25250d988f3b7",
{"reel_ids": userid_chunk, "precomposed_overlay": False})["data"]
yield from (Story(self.context, media) for media in stories['reels_media'])
@_requires_login
def download_stories(self,
userids: Optional[List[Union[int, Profile]]] = None,
fast_update: bool = False,
filename_target: Optional[str] = ':stories',
storyitem_filter: Optional[Callable[[StoryItem], bool]] = None,
latest_stamps: Optional[LatestStamps] = None) -> None:
"""
Download available stories from user followees or all stories of users whose ID are given.
Does not mark stories as seen.
To use this, one needs to be logged in
:param userids: List of user IDs or Profiles to be processed in terms of downloading their stories
:param fast_update: If true, abort when first already-downloaded picture is encountered
:param filename_target: Replacement for {target} in dirname_pattern and filename_pattern
or None if profile name should be used instead
:param storyitem_filter: function(storyitem), which returns True if given StoryItem should be downloaded
:param latest_stamps: Database with the last times each user was scraped
:raises LoginRequiredException: If called without being logged in.
.. versionchanged:: 4.8
Add `latest_stamps` parameter.
"""
if not userids:
self.context.log("Retrieving all visible stories...")
profile_count = None
else:
userids = [p if isinstance(p, int) else p.userid for p in userids]
profile_count = len(userids)
for i, user_story in enumerate(self.get_stories(userids), start=1):
name = user_story.owner_username
if profile_count is not None:
msg = "[{0:{w}d}/{1:{w}d}] Retrieving stories from profile {2}.".format(i, profile_count, name,
w=len(str(profile_count)))
else:
msg = "[{:3d}] Retrieving stories from profile {}.".format(i, name)
self.context.log(msg)
totalcount = user_story.itemcount
count = 1
if latest_stamps is not None:
# pylint:disable=cell-var-from-loop
last_scraped = latest_stamps.get_last_story_timestamp(name)
scraped_timestamp = datetime.now().astimezone()
for item in user_story.get_items():
if latest_stamps is not None and item.date_utc.replace(tzinfo=timezone.utc) <= last_scraped:
break
if storyitem_filter is not None and not storyitem_filter(item):
self.context.log("<{} skipped>".format(item), flush=True)
continue
self.context.log("[%3i/%3i] " % (count, totalcount), end="", flush=True)
count += 1
with self.context.error_catcher('Download story from user {}'.format(name)):
downloaded = self.download_storyitem(item, filename_target if filename_target else name)
if fast_update and not downloaded:
break
if latest_stamps is not None:
latest_stamps.set_last_story_timestamp(name, scraped_timestamp)
def download_storyitem(self, item: StoryItem, target: Union[str, Path]) -> bool:
"""Download one user story.
:param item: Story item, as in story['items'] for story in :meth:`get_stories`
:param target: Replacement for {target} in dirname_pattern and filename_pattern
:return: True if something was downloaded, False otherwise, i.e. file was already there
"""
def _already_downloaded(path: str) -> bool:
if not os.path.isfile(path):
return False
else:
self.context.log(path + ' exists', end=' ', flush=True)
return True
date_local = item.date_local
dirname = _PostPathFormatter(item).format(self.dirname_pattern, target=target)
filename_template = os.path.join(dirname, self.format_filename(item, target=target))
filename = self.__prepare_filename(filename_template, lambda: item.url)
downloaded = False
if not item.is_video or self.download_video_thumbnails is True:
downloaded = (not _already_downloaded(filename + ".jpg") and
self.download_pic(filename=filename, url=item.url, mtime=date_local))
if item.is_video and self.download_videos is True:
filename = self.__prepare_filename(filename_template, lambda: str(item.video_url))
downloaded |= (not _already_downloaded(filename + ".mp4") and
self.download_pic(filename=filename, url=item.video_url, mtime=date_local))
# Save caption if desired
metadata_string = _ArbitraryItemFormatter(item).format(self.storyitem_metadata_txt_pattern).strip()
if metadata_string:
self.save_caption(filename=filename, mtime=item.date_local, caption=metadata_string)
# Save metadata as JSON if desired.
if self.save_metadata is not False:
self.save_metadata_json(filename, item)
self.context.log()
return downloaded
@_requires_login
def get_highlights(self, user: Union[int, Profile]) -> Iterator[Highlight]:
"""Get all highlights from a user.
To use this, one needs to be logged in.
.. versionadded:: 4.1
:param user: ID or Profile of the user whose highlights should get fetched.
:raises LoginRequiredException: If called without being logged in.
"""
userid = user if isinstance(user, int) else user.userid
data = self.context.graphql_query("7c16654f22c819fb63d1183034a5162f",
{"user_id": userid, "include_chaining": False, "include_reel": False,
"include_suggested_users": False, "include_logged_out_extras": False,
"include_highlight_reels": True})["data"]["user"]['edge_highlight_reels']
if data is None:
raise BadResponseException('Bad highlights reel JSON.')
yield from (Highlight(self.context, edge['node'], user if isinstance(user, Profile) else None)
for edge in data['edges'])
@_requires_login
def download_highlights(self,
user: Union[int, Profile],
fast_update: bool = False,
filename_target: Optional[str] = None,
storyitem_filter: Optional[Callable[[StoryItem], bool]] = None) -> None:
"""
Download available highlights from a user whose ID is given.
To use this, one needs to be logged in.
.. versionadded:: 4.1
.. versionchanged:: 4.3
Also downloads and saves the Highlight's cover pictures.
:param user: ID or Profile of the user whose highlights should get downloaded.
:param fast_update: If true, abort when first already-downloaded picture is encountered
:param filename_target: Replacement for {target} in dirname_pattern and filename_pattern
or None if profile name and the highlights' titles should be used instead
:param storyitem_filter: function(storyitem), which returns True if given StoryItem should be downloaded
:raises LoginRequiredException: If called without being logged in.
"""
for user_highlight in self.get_highlights(user):
name = user_highlight.owner_username
highlight_target = (filename_target
if filename_target
else (Path(_PostPathFormatter.sanitize_path(name)) /
_PostPathFormatter.sanitize_path(user_highlight.title))) # type: Union[str, Path]
self.context.log("Retrieving highlights \"{}\" from profile {}".format(user_highlight.title, name))
self.download_highlight_cover(user_highlight, highlight_target)
totalcount = user_highlight.itemcount
count = 1
for item in user_highlight.get_items():
if storyitem_filter is not None and not storyitem_filter(item):
self.context.log("<{} skipped>".format(item), flush=True)
continue
self.context.log("[%3i/%3i] " % (count, totalcount), end="", flush=True)
count += 1
with self.context.error_catcher('Download highlights \"{}\" from user {}'.format(user_highlight.title,
name)):
downloaded = self.download_storyitem(item, highlight_target)
if fast_update and not downloaded:
break
def posts_download_loop(self,
posts: Iterator[Post],
target: Union[str, Path],
fast_update: bool = False,
post_filter: Optional[Callable[[Post], bool]] = None,
max_count: Optional[int] = None,
total_count: Optional[int] = None,
owner_profile: Optional[Profile] = None,
takewhile: Optional[Callable[[Post], bool]] = None) -> None:
"""
Download the Posts returned by given Post Iterator.
.. versionadded:: 4.4
.. versionchanged:: 4.5
Transparently resume an aborted operation if `posts` is a :class:`NodeIterator`.
.. versionchanged:: 4.8
Add `takewhile` parameter.
:param posts: Post Iterator to loop through.
:param target: Target name.
:param fast_update: :option:`--fast-update`.
:param post_filter: :option:`--post-filter`.
:param max_count: Maximum count of Posts to download (:option:`--count`).
:param total_count: Total number of posts returned by given iterator.
:param owner_profile: Associated profile, if any.
:param takewhile: Expression evaluated for each post. Once it returns false, downloading stops.
"""
displayed_count = (max_count if total_count is None or max_count is not None and max_count < total_count
else total_count)
sanitized_target = target
if isinstance(target, str):
sanitized_target = _PostPathFormatter.sanitize_path(target)
if takewhile is None:
takewhile = lambda _: True
with resumable_iteration(
context=self.context,
iterator=posts,
load=load_structure_from_file,
save=save_structure_to_file,
format_path=lambda magic: self.format_filename_within_target_path(
sanitized_target, owner_profile, self.resume_prefix or '', magic, 'json.xz'
),
check_bbd=self.check_resume_bbd,
enabled=self.resume_prefix is not None
) as (is_resuming, start_index):
for number, post in enumerate(posts, start=start_index + 1):
if (max_count is not None and number > max_count) or not takewhile(post):
break
if displayed_count is not None:
self.context.log("[{0:{w}d}/{1:{w}d}] ".format(number, displayed_count,
w=len(str(displayed_count))),
end="", flush=True)
else:
self.context.log("[{:3d}] ".format(number), end="", flush=True)
if post_filter is not None:
try:
if not post_filter(post):
self.context.log("{} skipped".format(post))
continue
except (InstaloaderException, KeyError, TypeError) as err:
self.context.error("{} skipped. Filter evaluation failed: {}".format(post, err))
continue
with self.context.error_catcher("Download {} of {}".format(post, target)):
# The PostChangedException gets raised if the Post's id/shortcode changed while obtaining
# additional metadata. This is most likely the case if a HTTP redirect takes place while
# resolving the shortcode URL.
# The `post_changed` variable keeps the fast-update functionality alive: A Post which is
# obained after a redirect has probably already been downloaded as a previous Post of the
# same Profile.
# Observed in issue #225: https://github.com/instaloader/instaloader/issues/225
post_changed = False
while True:
try:
downloaded = self.download_post(post, target=target)
break
except PostChangedException:
post_changed = True
continue
if fast_update and not downloaded and not post_changed:
# disengage fast_update for first post when resuming
if not is_resuming or number > 0:
break
@_requires_login
def get_feed_posts(self) -> Iterator[Post]:
"""Get Posts of the user's feed.
:return: Iterator over Posts of the user's feed.
:raises LoginRequiredException: If called without being logged in.
"""
data = self.context.graphql_query("d6f4427fbe92d846298cf93df0b937d3", {})["data"]
while True:
feed = data["user"]["edge_web_feed_timeline"]
for edge in feed["edges"]:
node = edge["node"]
if node.get("__typename") in Post.supported_graphql_types() and node.get("shortcode") is not None:
yield Post(self.context, node)
if not feed["page_info"]["has_next_page"]:
break
data = self.context.graphql_query("d6f4427fbe92d846298cf93df0b937d3",
{'fetch_media_item_count': 12,
'fetch_media_item_cursor': feed["page_info"]["end_cursor"],
'fetch_comment_count': 4,
'fetch_like': 10,
'has_stories': False})["data"]
@_requires_login
def download_feed_posts(self, max_count: int = None, fast_update: bool = False,
post_filter: Optional[Callable[[Post], bool]] = None) -> None:
"""
Download pictures from the user's feed.
Example to download up to the 20 pics the user last liked::
loader = Instaloader()
loader.load_session_from_file('USER')
loader.download_feed_posts(max_count=20, fast_update=True,
post_filter=lambda post: post.viewer_has_liked)
:param max_count: Maximum count of pictures to download
:param fast_update: If true, abort when first already-downloaded picture is encountered
:param post_filter: function(post), which returns True if given picture should be downloaded
:raises LoginRequiredException: If called without being logged in.
"""
self.context.log("Retrieving pictures from your feed...")
self.posts_download_loop(self.get_feed_posts(), ":feed", fast_update, post_filter, max_count=max_count)
@_requires_login
def download_saved_posts(self, max_count: int = None, fast_update: bool = False,
post_filter: Optional[Callable[[Post], bool]] = None) -> None:
"""Download user's saved pictures.
:param max_count: Maximum count of pictures to download
:param fast_update: If true, abort when first already-downloaded picture is encountered
:param post_filter: function(post), which returns True if given picture should be downloaded
:raises LoginRequiredException: If called without being logged in.
"""
self.context.log("Retrieving saved posts...")
assert self.context.username is not None # safe due to @_requires_login; required by typechecker
node_iterator = Profile.own_profile(self.context).get_saved_posts()
self.posts_download_loop(node_iterator, ":saved",
fast_update, post_filter,
max_count=max_count, total_count=node_iterator.count)
@_requires_login
def get_location_posts(self, location: str) -> Iterator[Post]:
"""Get Posts which are listed by Instagram for a given Location.
:return: Iterator over Posts of a location's posts
:raises LoginRequiredException: If called without being logged in.
.. versionadded:: 4.2
.. versionchanged:: 4.2.9
Require being logged in (as required by Instagram)
"""
has_next_page = True
end_cursor = None
while has_next_page:
if end_cursor:
params = {'__a': 1, 'max_id': end_cursor}
else:
params = {'__a': 1}
location_data = self.context.get_json('explore/locations/{0}/'.format(location),
params)['graphql']['location']['edge_location_to_media']
yield from (Post(self.context, edge['node']) for edge in location_data['edges'])
has_next_page = location_data['page_info']['has_next_page']
end_cursor = location_data['page_info']['end_cursor']
@_requires_login
def download_location(self, location: str,
max_count: Optional[int] = None,
post_filter: Optional[Callable[[Post], bool]] = None,
fast_update: bool = False) -> None:
"""Download pictures of one location.
To download the last 30 pictures with location 362629379, do::
loader = Instaloader()
loader.download_location(362629379, max_count=30)
:param location: Location to download, as Instagram numerical ID
:param max_count: Maximum count of pictures to download
:param post_filter: function(post), which returns True if given picture should be downloaded
:param fast_update: If true, abort when first already-downloaded picture is encountered
:raises LoginRequiredException: If called without being logged in.
.. versionadded:: 4.2
.. versionchanged:: 4.2.9
Require being logged in (as required by Instagram)
"""
self.context.log("Retrieving pictures for location {}...".format(location))
self.posts_download_loop(self.get_location_posts(location), "%" + location, fast_update, post_filter,
max_count=max_count)
@_requires_login
def get_explore_posts(self) -> NodeIterator[Post]:
"""Get Posts which are worthy of exploring suggested by Instagram.
:return: Iterator over Posts of the user's suggested posts.
:rtype: NodeIterator[Post]
:raises LoginRequiredException: If called without being logged in.
"""
return NodeIterator(
self.context,
'df0dcc250c2b18d9fd27c5581ef33c7c',
lambda d: d['data']['user']['edge_web_discover_media'],
lambda n: Post(self.context, n),
query_referer='https://www.instagram.com/explore/',
)
def get_hashtag_posts(self, hashtag: str) -> Iterator[Post]:
"""Get Posts associated with a #hashtag.
.. deprecated:: 4.4
Use :meth:`Hashtag.get_posts`."""
return Hashtag.from_name(self.context, hashtag).get_posts()
def download_hashtag(self, hashtag: Union[Hashtag, str],
max_count: Optional[int] = None,
post_filter: Optional[Callable[[Post], bool]] = None,
fast_update: bool = False,
profile_pic: bool = True,
posts: bool = True) -> None:
"""Download pictures of one hashtag.
To download the last 30 pictures with hashtag #cat, do::
loader = Instaloader()
loader.download_hashtag('cat', max_count=30)
:param hashtag: Hashtag to download, as instance of :class:`Hashtag`, or string without leading '#'
:param max_count: Maximum count of pictures to download
:param post_filter: function(post), which returns True if given picture should be downloaded
:param fast_update: If true, abort when first already-downloaded picture is encountered
:param profile_pic: not :option:`--no-profile-pic`.
:param posts: not :option:`--no-posts`.
.. versionchanged:: 4.4
Add parameters `profile_pic` and `posts`.
"""
if isinstance(hashtag, str):
with self.context.error_catcher("Get hashtag #{}".format(hashtag)):
hashtag = Hashtag.from_name(self.context, hashtag)
if not isinstance(hashtag, Hashtag):
return
target = "#" + hashtag.name
if profile_pic:
with self.context.error_catcher("Download profile picture of {}".format(target)):
self.download_hashtag_profilepic(hashtag)
if posts:
self.context.log("Retrieving pictures with hashtag #{}...".format(hashtag.name))
self.posts_download_loop(hashtag.get_all_posts(), target, fast_update, post_filter,
max_count=max_count)
if self.save_metadata:
json_filename = '{0}/{1}'.format(self.dirname_pattern.format(profile=target,
target=target),
target)
self.save_metadata_json(json_filename, hashtag)
def download_tagged(self, profile: Profile, fast_update: bool = False,
target: Optional[str] = None,
post_filter: Optional[Callable[[Post], bool]] = None,
latest_stamps: Optional[LatestStamps] = None) -> None:
"""Download all posts where a profile is tagged.
.. versionadded:: 4.1
.. versionchanged:: 4.8
Add `latest_stamps` parameter."""
self.context.log("Retrieving tagged posts for profile {}.".format(profile.username))
posts_takewhile: Optional[Callable[[Post], bool]] = None
if latest_stamps is not None:
last_scraped = latest_stamps.get_last_tagged_timestamp(profile.username)
posts_takewhile = lambda p: p.date_utc.replace(tzinfo=timezone.utc) > last_scraped
tagged_posts = profile.get_tagged_posts()
self.posts_download_loop(tagged_posts,
target if target
else (Path(_PostPathFormatter.sanitize_path(profile.username)) /
_PostPathFormatter.sanitize_path(':tagged')),
fast_update, post_filter, takewhile=posts_takewhile)
if latest_stamps is not None and tagged_posts.first_item is not None:
latest_stamps.set_last_tagged_timestamp(profile.username, tagged_posts.first_item.date_local.astimezone())
def download_igtv(self, profile: Profile, fast_update: bool = False,
post_filter: Optional[Callable[[Post], bool]] = None,
latest_stamps: Optional[LatestStamps] = None) -> None:
"""Download IGTV videos of a profile.
.. versionadded:: 4.3
.. versionchanged:: 4.8
Add `latest_stamps` parameter."""
self.context.log("Retrieving IGTV videos for profile {}.".format(profile.username))
posts_takewhile: Optional[Callable[[Post], bool]] = None
if latest_stamps is not None:
last_scraped = latest_stamps.get_last_igtv_timestamp(profile.username)
posts_takewhile = lambda p: p.date_utc.replace(tzinfo=timezone.utc) > last_scraped
igtv_posts = profile.get_igtv_posts()
self.posts_download_loop(igtv_posts, profile.username, fast_update, post_filter,
total_count=profile.igtvcount, owner_profile=profile, takewhile=posts_takewhile)
if latest_stamps is not None and igtv_posts.first_item is not None:
latest_stamps.set_last_igtv_timestamp(profile.username, igtv_posts.first_item.date_local.astimezone())
def _get_id_filename(self, profile_name: str) -> str:
if ((format_string_contains_key(self.dirname_pattern, 'profile') or
format_string_contains_key(self.dirname_pattern, 'target'))):
return os.path.join(self.dirname_pattern.format(profile=profile_name.lower(),
target=profile_name.lower()),
'id')
else:
return os.path.join(self.dirname_pattern.format(),
'{0}_id'.format(profile_name.lower()))
def load_profile_id(self, profile_name: str) -> Optional[int]:
"""
Load ID of profile from profile directory.
.. versionadded:: 4.8
"""
id_filename = self._get_id_filename(profile_name)
try:
with open(id_filename, 'rb') as id_file:
return int(id_file.read())
except (FileNotFoundError, ValueError):
return None
def save_profile_id(self, profile: Profile):
"""
Store ID of profile on profile directory.
.. versionadded:: 4.0.6
"""
os.makedirs(self.dirname_pattern.format(profile=profile.username,
target=profile.username), exist_ok=True)
with open(self._get_id_filename(profile.username), 'w') as text_file:
text_file.write(str(profile.userid) + "\n")
self.context.log("Stored ID {0} for profile {1}.".format(profile.userid, profile.username))
def check_profile_id(self, profile_name: str, latest_stamps: Optional[LatestStamps] = None) -> Profile:
"""
Consult locally stored ID of profile with given name, check whether ID matches and whether name
has changed and return current name of the profile, and store ID of profile.
:param profile_name: Profile name
:param latest_stamps: Database of downloaded data. If present, IDs are retrieved from it,
otherwise from the target directory
:return: Instance of current profile
.. versionchanged:: 4.8
Add `latest_stamps` parameter.
"""
profile = None
profile_name_not_exists_err = None
try:
profile = Profile.from_username(self.context, profile_name)
except ProfileNotExistsException as err:
profile_name_not_exists_err = err
if latest_stamps is None:
profile_id = self.load_profile_id(profile_name)
else:
profile_id = latest_stamps.get_profile_id(profile_name)
if profile_id is not None:
if (profile is None) or \
(profile_id != profile.userid):
if profile is not None:
self.context.log("Profile {0} does not match the stored unique ID {1}.".format(profile_name,
profile_id))
else:
self.context.log("Trying to find profile {0} using its unique ID {1}.".format(profile_name,
profile_id))
profile_from_id = Profile.from_id(self.context, profile_id)
newname = profile_from_id.username
self.context.error("Profile {0} has changed its name to {1}.".format(profile_name, newname))
if latest_stamps is None:
if ((format_string_contains_key(self.dirname_pattern, 'profile') or
format_string_contains_key(self.dirname_pattern, 'target'))):
os.rename(self.dirname_pattern.format(profile=profile_name.lower(),
target=profile_name.lower()),
self.dirname_pattern.format(profile=newname.lower(),
target=newname.lower()))
else:
os.rename('{0}/{1}_id'.format(self.dirname_pattern.format(), profile_name.lower()),
'{0}/{1}_id'.format(self.dirname_pattern.format(), newname.lower()))
else:
latest_stamps.rename_profile(profile_name, newname)
return profile_from_id
# profile exists and profile id matches saved id
return profile
if profile is not None:
if latest_stamps is None:
self.save_profile_id(profile)
else:
latest_stamps.save_profile_id(profile.username, profile.userid)
return profile
if profile_name_not_exists_err:
raise profile_name_not_exists_err
raise ProfileNotExistsException("Profile {0} does not exist.".format(profile_name))
def download_profiles(self, profiles: Set[Profile],
profile_pic: bool = True, posts: bool = True,
tagged: bool = False,
igtv: bool = False,
highlights: bool = False,
stories: bool = False,
fast_update: bool = False,
post_filter: Optional[Callable[[Post], bool]] = None,
storyitem_filter: Optional[Callable[[Post], bool]] = None,
raise_errors: bool = False,
latest_stamps: Optional[LatestStamps] = None):
"""High-level method to download set of profiles.
:param profiles: Set of profiles to download.
:param profile_pic: not :option:`--no-profile-pic`.
:param posts: not :option:`--no-posts`.
:param tagged: :option:`--tagged`.
:param igtv: :option:`--igtv`.
:param highlights: :option:`--highlights`.
:param stories: :option:`--stories`.
:param fast_update: :option:`--fast-update`.
:param post_filter: :option:`--post-filter`.
:param storyitem_filter: :option:`--post-filter`.
:param raise_errors:
Whether :exc:`LoginRequiredException` and :exc:`PrivateProfileNotFollowedException` should be raised or
catched and printed with :meth:`InstaloaderContext.error_catcher`.
:param latest_stamps: :option:`--latest-stamps`.
.. versionadded:: 4.1
.. versionchanged:: 4.3
Add `igtv` parameter.
.. versionchanged:: 4.8
Add `latest_stamps` parameter.
"""
@contextmanager
def _error_raiser(_str):
yield
# error_handler type is Callable[[Optional[str]], ContextManager[None]] (not supported with Python 3.5.0..3.5.3)
error_handler = _error_raiser if raise_errors else self.context.error_catcher
for i, profile in enumerate(profiles, start=1):
self.context.log("[{0:{w}d}/{1:{w}d}] Downloading profile {2}".format(i, len(profiles), profile.username,
w=len(str(len(profiles)))))
with error_handler(profile.username): # type: ignore # (ignore type for Python 3.5 support)
profile_name = profile.username
# Download profile picture
if profile_pic:
with self.context.error_catcher('Download profile picture of {}'.format(profile_name)):
self.download_profilepic_if_new(profile, latest_stamps)
# Save metadata as JSON if desired.
if self.save_metadata:
json_filename = os.path.join(self.dirname_pattern.format(profile=profile_name,
target=profile_name),
'{0}_{1}'.format(profile_name, profile.userid))
self.save_metadata_json(json_filename, profile)
# Catch some errors
if tagged or igtv or highlights or posts:
if (not self.context.is_logged_in and
profile.is_private):
raise LoginRequiredException("--login=USERNAME required.")
if (self.context.username != profile.username and
profile.is_private and
not profile.followed_by_viewer):
raise PrivateProfileNotFollowedException("Private but not followed.")
# Download tagged, if requested
if tagged:
with self.context.error_catcher('Download tagged of {}'.format(profile_name)):
self.download_tagged(profile, fast_update=fast_update, post_filter=post_filter,
latest_stamps=latest_stamps)
# Download IGTV, if requested
if igtv:
with self.context.error_catcher('Download IGTV of {}'.format(profile_name)):
self.download_igtv(profile, fast_update=fast_update, post_filter=post_filter,
latest_stamps=latest_stamps)
# Download highlights, if requested
if highlights:
with self.context.error_catcher('Download highlights of {}'.format(profile_name)):
self.download_highlights(profile, fast_update=fast_update, storyitem_filter=storyitem_filter)
# Iterate over pictures and download them
if posts:
self.context.log("Retrieving posts from profile {}.".format(profile_name))
posts_takewhile: Optional[Callable[[Post], bool]] = None
if latest_stamps is not None:
# pylint:disable=cell-var-from-loop
last_scraped = latest_stamps.get_last_post_timestamp(profile_name)
posts_takewhile = lambda p: p.date_utc.replace(tzinfo=timezone.utc) > last_scraped
posts_to_download = profile.get_posts()
self.posts_download_loop(posts_to_download, profile_name, fast_update, post_filter,
total_count=profile.mediacount, owner_profile=profile,
takewhile=posts_takewhile)
if latest_stamps is not None and posts_to_download.first_item is not None:
latest_stamps.set_last_post_timestamp(profile_name,
posts_to_download.first_item.date_local.astimezone())
if stories and profiles:
with self.context.error_catcher("Download stories"):
self.context.log("Downloading stories")
self.download_stories(userids=list(profiles), fast_update=fast_update, filename_target=None,
storyitem_filter=storyitem_filter, latest_stamps=latest_stamps)
def download_profile(self, profile_name: Union[str, Profile],
profile_pic: bool = True, profile_pic_only: bool = False,
fast_update: bool = False,
download_stories: bool = False, download_stories_only: bool = False,
download_tagged: bool = False, download_tagged_only: bool = False,
post_filter: Optional[Callable[[Post], bool]] = None,
storyitem_filter: Optional[Callable[[StoryItem], bool]] = None) -> None:
"""Download one profile
.. deprecated:: 4.1
Use :meth:`Instaloader.download_profiles`.
"""
# Get profile main page json
# check if profile does exist or name has changed since last download
# and update name and json data if necessary
if isinstance(profile_name, str):
profile = self.check_profile_id(profile_name.lower())
else:
profile = profile_name
profile_name = profile.username
# Save metadata as JSON if desired.
if self.save_metadata is not False:
json_filename = '{0}/{1}_{2}'.format(self.dirname_pattern.format(profile=profile_name, target=profile_name),
profile_name, profile.userid)
self.save_metadata_json(json_filename, profile)
if self.context.is_logged_in and profile.has_blocked_viewer and not profile.is_private:
# raising ProfileNotExistsException invokes "trying again anonymously" logic
raise ProfileNotExistsException("Profile {} has blocked you".format(profile_name))
# Download profile picture
if profile_pic or profile_pic_only:
with self.context.error_catcher('Download profile picture of {}'.format(profile_name)):
self.download_profilepic(profile)
if profile_pic_only:
return
# Catch some errors
if profile.is_private:
if not self.context.is_logged_in:
raise LoginRequiredException("profile %s requires login" % profile_name)
if not profile.followed_by_viewer and \
self.context.username != profile.username:
raise PrivateProfileNotFollowedException("Profile %s: private but not followed." % profile_name)
else:
if self.context.is_logged_in and not (download_stories or download_stories_only):
self.context.log("profile %s could also be downloaded anonymously." % profile_name)
# Download stories, if requested
if download_stories or download_stories_only:
if profile.has_viewable_story:
with self.context.error_catcher("Download stories of {}".format(profile_name)):
self.download_stories(userids=[profile.userid], filename_target=profile_name,
fast_update=fast_update, storyitem_filter=storyitem_filter)
else:
self.context.log("{} does not have any stories.".format(profile_name))
if download_stories_only:
return
# Download tagged, if requested
if download_tagged or download_tagged_only:
with self.context.error_catcher('Download tagged of {}'.format(profile_name)):
self.download_tagged(profile, fast_update=fast_update, post_filter=post_filter)
if download_tagged_only:
return
# Iterate over pictures and download them
self.context.log("Retrieving posts from profile {}.".format(profile_name))
self.posts_download_loop(profile.get_posts(), profile_name, fast_update, post_filter,
total_count=profile.mediacount, owner_profile=profile)
def interactive_login(self, username: str) -> None:
"""Logs in and internally stores session, asking user for password interactively.
:raises LoginRequiredException: when in quiet mode.
:raises InvalidArgumentException: If the provided username does not exist.
:raises ConnectionException: If connection to Instagram failed."""
if self.context.quiet:
raise LoginRequiredException("Quiet mode requires given password or valid session file.")
try:
password = None
while password is None:
password = getpass.getpass(prompt="Enter Instagram password for %s: " % username)
try:
self.login(username, password)
except BadCredentialsException as err:
print(err, file=sys.stderr)
password = None
except TwoFactorAuthRequiredException:
while True:
try:
code = input("Enter 2FA verification code: ")
self.two_factor_login(code)
break
except BadCredentialsException as err:
print(err, file=sys.stderr)
pass
| []
| []
| [
"XDG_CONFIG_HOME",
"LOCALAPPDATA"
]
| [] | ["XDG_CONFIG_HOME", "LOCALAPPDATA"] | python | 2 | 0 | |
examples/todo/main.go | package main
import (
"context"
"fmt"
"os"
"strconv"
"github.com/fgm/pgxer"
)
var conn pgxer.Conn
func main() {
var err error
conn, err = pgxer.Connect(context.Background(), os.Getenv("DATABASE_URL"))
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
os.Exit(1)
}
if len(os.Args) == 1 {
printHelp()
os.Exit(0)
}
switch os.Args[1] {
case "list":
err = listTasks()
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to list tasks: %v\n", err)
os.Exit(1)
}
case "add":
err = addTask(os.Args[2])
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to add task: %v\n", err)
os.Exit(1)
}
case "update":
n, err := strconv.ParseInt(os.Args[2], 10, 32)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable convert task_num into int32: %v\n", err)
os.Exit(1)
}
err = updateTask(int32(n), os.Args[3])
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to update task: %v\n", err)
os.Exit(1)
}
case "remove":
n, err := strconv.ParseInt(os.Args[2], 10, 32)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable convert task_num into int32: %v\n", err)
os.Exit(1)
}
err = removeTask(int32(n))
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to remove task: %v\n", err)
os.Exit(1)
}
default:
fmt.Fprintln(os.Stderr, "Invalid command")
printHelp()
os.Exit(1)
}
}
func listTasks() error {
rows, _ := conn.Query(context.Background(), "select * from tasks")
for rows.Next() {
var id int32
var description string
err := rows.Scan(&id, &description)
if err != nil {
return err
}
fmt.Printf("%d. %s\n", id, description)
}
return rows.Err()
}
func addTask(description string) error {
_, err := conn.Exec(context.Background(), "insert into tasks(description) values($1)", description)
return err
}
func updateTask(itemNum int32, description string) error {
_, err := conn.Exec(context.Background(), "update tasks set description=$1 where id=$2", description, itemNum)
return err
}
func removeTask(itemNum int32) error {
_, err := conn.Exec(context.Background(), "delete from tasks where id=$1", itemNum)
return err
}
func printHelp() {
fmt.Print(`Todo pgx demo
Usage:
todo list
todo add task
todo update task_num item
todo remove task_num
Example:
todo add 'Learn Go'
todo list
`)
}
| [
"\"DATABASE_URL\""
]
| []
| [
"DATABASE_URL"
]
| [] | ["DATABASE_URL"] | go | 1 | 0 | |
brick/ida/utils/diaphora_utils.py | import os
from pathlib import Path
import tempfile
import subprocess
import idaapi
import copy
from externals import get_external
from .brick_utils import temp_env, temp_patch, set_directory, execfile
from contextlib import contextmanager
import sqlite3
DIAPHORA_DIR = get_external('diaphora')
def _export_this_idb(export_filename: str, **diaphora_kwargs: dict):
with temp_env():
os.environ['DIAPHORA_AUTO'] = '1'
os.environ['DIAPHORA_EXPORT_FILE'] = export_filename
os.environ.update(diaphora_kwargs)
# Hook idaapi.qexit to avoid termination of the process.
with temp_patch(idaapi, 'qexit', lambda code: None):
with set_directory(DIAPHORA_DIR):
new_globals = copy.copy(globals())
new_globals['__file__'] = str(DIAPHORA_DIR / 'diaphora.py')
new_globals['__name__'] = '__main__'
execfile('diaphora.py', new_globals)
def export_this_idb(export_filename: str, use_decompiler=True, slow_heuristics=True):
diaphora_kwargs = {}
if use_decompiler:
diaphora_kwargs['DIAPHORA_USE_DECOMPILER'] = '1'
if slow_heuristics:
diaphora_kwargs['DIAPHORA_SLOW_HEURISTICS'] = '1'
_export_this_idb(export_filename, **diaphora_kwargs)
def calculate_diff(first: str, second: str, output_path: str=None) -> sqlite3.Connection:
if output_path is None:
(temp_fd, temp_name) = tempfile.mkstemp()
os.close(temp_fd)
output_path = temp_name
with set_directory(DIAPHORA_DIR):
args = ['python', 'diaphora.py', first, second, '-o', output_path]
# print('Executing {}'.format(' '.join(args)))
subprocess.check_call(args, creationflags=subprocess.CREATE_NO_WINDOW)
return sqlite3.connect(output_path)
| []
| []
| [
"DIAPHORA_EXPORT_FILE",
"DIAPHORA_AUTO"
]
| [] | ["DIAPHORA_EXPORT_FILE", "DIAPHORA_AUTO"] | python | 2 | 0 | |
shanshan-django/5/pingpp/util.py | import logging
import sys
import os
logger = logging.getLogger('pingpp')
__all__ = ['StringIO', 'parse_qsl', 'json', 'utf8']
try:
# When cStringIO is available
import cStringIO as StringIO
except ImportError:
import StringIO
try:
from urlparse import parse_qsl
except ImportError:
# Python < 2.6
from cgi import parse_qsl
try:
import json
except ImportError:
json = None
if not (json and hasattr(json, 'loads')):
try:
import simplejson as json
except ImportError:
if not json:
raise ImportError(
"Ping++ requires a JSON library, such as simplejson. "
"HINT: Try installing the "
"python simplejson library via 'pip install simplejson' or "
"'easy_install simplejson', or contact [email protected] "
"with questions.")
else:
raise ImportError(
"Ping++ requires a JSON library with the same interface as "
"the Python 2.6 'json' library. You appear to have a 'json' "
"library with a different interface. Please install "
"the simplejson library. HINT: Try installing the "
"python simplejson library via 'pip install simplejson' "
"or 'easy_install simplejson', or contact [email protected]"
"with questions.")
def utf8(value):
if isinstance(value, unicode) and sys.version_info < (3, 0):
return value.encode('utf-8')
else:
return value
def is_appengine_dev():
return ('APPENGINE_RUNTIME' in os.environ and
'Dev' in os.environ.get('SERVER_SOFTWARE', ''))
| []
| []
| [
"SERVER_SOFTWARE"
]
| [] | ["SERVER_SOFTWARE"] | python | 1 | 0 | |
pkg/object/azure.go | //go:build !noazure
// +build !noazure
/*
* JuiceFS, Copyright 2018 Juicedata, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package object
import (
"fmt"
"io"
"net"
"net/url"
"os"
"strings"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
type wasb struct {
DefaultObjectStorage
container *azblob.ContainerClient
cName string
marker string
}
func (b *wasb) String() string {
return fmt.Sprintf("wasb://%s/", b.cName)
}
func (b *wasb) Create() error {
_, err := b.container.Create(ctx, nil)
if err != nil && strings.Contains(err.Error(), string(azblob.StorageErrorCodeContainerAlreadyExists)) {
return nil
}
return err
}
func (b *wasb) Head(key string) (Object, error) {
properties, err := b.container.NewBlobClient(key).GetProperties(ctx, &azblob.GetBlobPropertiesOptions{})
if err != nil {
if strings.Contains(err.Error(), string(azblob.StorageErrorCodeBlobNotFound)) {
err = os.ErrNotExist
}
return nil, err
}
return &obj{
key,
*properties.ContentLength,
*properties.LastModified,
strings.HasSuffix(key, "/"),
}, nil
}
func (b *wasb) Get(key string, off, limit int64) (io.ReadCloser, error) {
download, err := b.container.NewBlockBlobClient(key).Download(ctx, &azblob.DownloadBlobOptions{Offset: &off, Count: &limit})
if err != nil {
return nil, err
}
return download.BlobDownloadResponse.RawResponse.Body, err
}
func (b *wasb) Put(key string, data io.Reader) error {
_, err := b.container.NewBlockBlobClient(key).UploadStreamToBlockBlob(ctx, data, azblob.UploadStreamToBlockBlobOptions{})
return err
}
func (b *wasb) Copy(dst, src string) error {
_, err := b.container.NewBlockBlobClient(dst).CopyFromURL(ctx, b.container.NewBlockBlobClient(src).URL(),
&azblob.CopyBlockBlobFromURLOptions{})
return err
}
func (b *wasb) Delete(key string) error {
_, err := b.container.NewBlockBlobClient(key).Delete(ctx, &azblob.DeleteBlobOptions{})
if err != nil && strings.Contains(err.Error(), string(azblob.StorageErrorCodeBlobNotFound)) {
err = nil
}
return err
}
func (b *wasb) List(prefix, marker string, limit int64) ([]Object, error) {
if marker != "" {
if b.marker == "" {
// last page
return nil, nil
}
marker = b.marker
}
limit32 := int32(limit)
pager := b.container.ListBlobsFlat(&azblob.ContainerListBlobFlatSegmentOptions{Prefix: &prefix, Marker: &marker, Maxresults: &(limit32)})
if pager.Err() != nil {
return nil, pager.Err()
}
if pager.NextPage(ctx) {
b.marker = *pager.PageResponse().NextMarker
} else {
b.marker = ""
}
var n int
if pager.PageResponse().Segment != nil {
n = len(pager.PageResponse().Segment.BlobItems)
}
objs := make([]Object, n)
for i := 0; i < n; i++ {
blob := pager.PageResponse().Segment.BlobItems[i]
mtime := blob.Properties.LastModified
objs[i] = &obj{
*blob.Name,
*blob.Properties.ContentLength,
*mtime,
strings.HasSuffix(*blob.Name, "/"),
}
}
return objs, nil
}
func autoWasbEndpoint(containerName, accountName, scheme string, credential *azblob.SharedKeyCredential) (string, error) {
baseURLs := []string{"blob.core.windows.net", "blob.core.chinacloudapi.cn"}
endpoint := ""
for _, baseURL := range baseURLs {
if _, err := net.LookupIP(fmt.Sprintf("%s.%s", accountName, baseURL)); err != nil {
logger.Debugf("Attempt to resolve domain name %s failed: %s", baseURL, err)
continue
}
client, err := azblob.NewContainerClientWithSharedKey(fmt.Sprintf("%s://%s.%s/%s", scheme, accountName, baseURL, containerName), credential, nil)
if err != nil {
return "", err
}
if _, err = client.GetProperties(ctx, nil); err != nil {
logger.Debugf("Try to get containers properties at %s failed: %s", baseURL, err)
continue
}
endpoint = baseURL
break
}
if endpoint == "" {
return "", fmt.Errorf("fail to get endpoint for container %s", containerName)
}
return endpoint, nil
}
func newWabs(endpoint, accountName, accountKey, token string) (ObjectStorage, error) {
if !strings.Contains(endpoint, "://") {
endpoint = fmt.Sprintf("https://%s", endpoint)
}
uri, err := url.ParseRequestURI(endpoint)
if err != nil {
return nil, fmt.Errorf("Invalid endpoint: %v, error: %v", endpoint, err)
}
hostParts := strings.SplitN(uri.Host, ".", 2)
containerName := hostParts[0]
// Connection string support: DefaultEndpointsProtocol=[http|https];AccountName=***;AccountKey=***;EndpointSuffix=[core.windows.net|core.chinacloudapi.cn]
if connString := os.Getenv("AZURE_STORAGE_CONNECTION_STRING"); connString != "" {
var client azblob.ContainerClient
if client, err = azblob.NewContainerClientFromConnectionString(connString, containerName, nil); err != nil {
return nil, err
}
return &wasb{container: &client, cName: containerName}, nil
}
credential, err := azblob.NewSharedKeyCredential(accountName, accountKey)
if err != nil {
return nil, err
}
var domain string
if len(hostParts) > 1 {
domain = hostParts[1]
if !strings.HasPrefix(hostParts[1], "blob") {
domain = fmt.Sprintf("blob.%s", hostParts[1])
}
} else if domain, err = autoWasbEndpoint(containerName, accountName, uri.Scheme, credential); err != nil {
return nil, fmt.Errorf("Unable to get endpoint of container %s: %s", containerName, err)
}
client, err := azblob.NewContainerClientWithSharedKey(fmt.Sprintf("%s://%s.%s/%s", uri.Scheme, accountName, domain, containerName), credential, nil)
if err != nil {
return nil, err
}
return &wasb{container: &client, cName: containerName}, nil
}
func init() {
Register("wasb", newWabs)
}
| [
"\"AZURE_STORAGE_CONNECTION_STRING\""
]
| []
| [
"AZURE_STORAGE_CONNECTION_STRING"
]
| [] | ["AZURE_STORAGE_CONNECTION_STRING"] | go | 1 | 0 | |
elastic/deploy-elastic.py | #!/bin/env python
import logging
import os
import random
import click
import delegator
import yaml
KEY_PATH = "gcloud_elastic_ansible"
KEYS_PATH = 'elastic-keys'
YAML_PATH = "vars/common.yml"
HOSTS_PATH = 'elastic-hosts'
class GCloudError(Exception):
def __init__(self, message):
super().__init__(message)
def create_key_pair(key_path):
if not os.path.isfile(key_path):
delegator.run('ssh-keygen -b 2048 -t rsa -f %s -q -N ""' % key_path)
def load_yml(path):
with open(path, 'r') as f:
data = yaml.safe_load(f)
return data
def load_key(path):
with open(path + ".pub", 'r') as f:
key = f.read()
return key
def write_users(yml, key, key_path):
with open(key_path, 'w') as f:
for user in yml.get('users', []) + [yml.get('deployer')]:
f.write(''.join([user, ':', key]))
def add_keys_to(instance_tag, key_path, zone):
# TODO This method could be optional
delegator.run(("gcloud compute instances add-metadata %s "
"--zone=%s --metadata-from-file sshKeys=%s") % (instance_tag, zone, key_path))
def get_ip_of(instance_tag):
# TODO This method could be optional
c = delegator.run(('gcloud --format="value(networkInterfaces[0].accessConfigs[0].natIP)" '
'compute instances list --filter="name=(%s)"') % instance_tag)
external_ip = c.out.strip()
if c.err:
raise GCloudError(c.err)
elif not external_ip:
raise GCloudError("No external ip found for instance {}"
.format(instance_tag))
print("external ip found for instance {}: {}"
.format(instance_tag, external_ip))
return external_ip
def zone_of(instance_tag):
c = delegator.run(('gcloud --format="value(zone)" '
'compute instances list %s') % instance_tag)
zone = c.out.strip()
return zone
def add_firewall_rules():
delegator.run("gcloud compute firewall-rules delete allow-elastic-training-ports ")
delegator.run(r"""gcloud compute firewall-rules create allow-elastic-training-ports \
--allow tcp:9200,tcp:5601,tcp:5000,tcp:10000 \
--source-ranges 37.17.221.89/32 \
--target-tags elastic-training-instance \
--description 'Allow access to Elasticsearch, Kibana, Logstash, Netcat and Jupyter'""")
def init_host_file(hosts_path):
with open(hosts_path, 'w') as f:
f.write('[elastic-instances]')
f.write('\n')
def write_ip_to(hosts_path, external_ip):
with open(hosts_path, 'a') as f:
f.write(external_ip)
f.write('\n')
def get_variables():
return (os.environ.get('KEY_PATH', KEY_PATH),
os.environ.get('KEYS_PATH', KEYS_PATH),
YAML_PATH,
HOSTS_PATH)
def get_random_id(N_sequence):
_id = ''
numbers = list(range(10))
for _ in range(N_sequence):
_id += str(random.choice(numbers))
return _id
def get_instance_name_prefix(name, N_sequence=10):
if name:
return f"elastic-{name}"
else:
return f"elastic-{get_random_id(N_sequence)}"
def create_machines(project_id, name_prefix, instances):
for instance in range(0,instances):
machine_name = f"{name_prefix}-{instance}"
to_run = f"""gcloud beta compute instances create {machine_name}
--subnet=default --zone=europe-west1-c
--machine-type=n1-standard-4
--tags elastic-training-instance
--boot-disk-size=20GB --boot-disk-type=pd-standard --boot-disk-device-name={machine_name}
"""
if project_id:
to_run += f" --project_id {project_id}"
c = delegator.run(to_run.replace('\n', ' '))
if c.err:
# don't raise, it's printing to standard error but it's not an error
logging.warning(c.err)
@click.command()
@click.option('--project', default=None, help="Google project")
@click.option('--instances', default=3, help="Number of instances")
@click.option('--name', default=None, help="Google instancename prefix")
def main(project, instances, name):
name_prefix = get_instance_name_prefix(name)
create_machines(project, name_prefix, instances)
add_firewall_rules()
key_path, keys_path, yaml_path, hosts_path = get_variables()
create_key_pair(key_path)
yml = load_yml(yaml_path)
key = load_key(key_path)
write_users(yml, key, keys_path)
init_host_file(hosts_path)
for instance in range(0, instances):
instance_tag = f"{name_prefix}-{instance}"
zone = zone_of(instance_tag)
add_keys_to(instance_tag, keys_path, zone)
external_ip = get_ip_of(instance_tag)
write_ip_to(hosts_path, external_ip)
if __name__ == "__main__":
main()
| []
| []
| [
"KEY_PATH",
"KEYS_PATH"
]
| [] | ["KEY_PATH", "KEYS_PATH"] | python | 2 | 0 | |
src/r/integration/integration_suite_test.go | package integration_test
import (
"encoding/json"
"flag"
"fmt"
"net/url"
"os"
"os/exec"
"path/filepath"
"time"
"github.com/blang/semver"
"github.com/cloudfoundry/libbuildpack/cutlass"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
var bpDir string
var buildpackVersion string
var packagedBuildpack cutlass.VersionedBuildpackPackage
var _ = func() bool {
testing.Init()
return true
}()
func init() {
flag.StringVar(&buildpackVersion, "version", "", "version to use (builds if empty)")
flag.BoolVar(&cutlass.Cached, "cached", true, "cached buildpack")
flag.StringVar(&cutlass.DefaultMemory, "memory", "128M", "default memory for pushed apps")
flag.StringVar(&cutlass.DefaultDisk, "disk", "384M", "default disk for pushed apps")
flag.Parse()
}
var _ = SynchronizedBeforeSuite(func() []byte {
// Run once
if buildpackVersion == "" {
packagedBuildpack, err := cutlass.PackageUniquelyVersionedBuildpack(os.Getenv("CF_STACK"), ApiHasStackAssociation())
Expect(err).NotTo(HaveOccurred())
// It is very typical of CF installations to have a limit of 1G
// for Cloud Controller max file upload size
fileInfo, err := os.Stat(packagedBuildpack.File)
Expect(err).NotTo(HaveOccurred())
Expect(fileInfo.Size()).
Should(BeNumerically("<", (int64)(1024*1024*1024)),
"Packaged buildpack exceeds the 1GB limit")
data, err := json.Marshal(packagedBuildpack)
Expect(err).NotTo(HaveOccurred())
return data
}
return []byte{}
}, func(data []byte) {
// Run on all nodes
var err error
if len(data) > 0 {
err = json.Unmarshal(data, &packagedBuildpack)
Expect(err).NotTo(HaveOccurred())
buildpackVersion = packagedBuildpack.Version
}
bpDir, err = cutlass.FindRoot()
Expect(err).NotTo(HaveOccurred())
Expect(cutlass.CopyCfHome()).To(Succeed())
cutlass.SeedRandom()
cutlass.DefaultStdoutStderr = GinkgoWriter
})
var _ = SynchronizedAfterSuite(func() {
// Run on all nodes
}, func() {
// Run once
Expect(cutlass.RemovePackagedBuildpack(packagedBuildpack)).To(Succeed())
Expect(cutlass.DeleteOrphanedRoutes()).To(Succeed())
})
func TestIntegration(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Integration Suite")
}
func PushAppAndConfirm(app *cutlass.App) {
Expect(app.Push()).To(Succeed())
Eventually(func() ([]string, error) { return app.InstanceStates() }, 20*time.Second).Should(Equal([]string{"RUNNING"}))
Expect(app.ConfirmBuildpack(buildpackVersion)).To(Succeed())
}
func Restart(app *cutlass.App) {
Expect(app.Restart()).To(Succeed())
Eventually(func() ([]string, error) { return app.InstanceStates() }, 20*time.Second).Should(Equal([]string{"RUNNING"}))
}
func ApiGreaterThan(version string) bool {
apiVersionString, err := cutlass.ApiVersion()
Expect(err).To(BeNil())
apiVersion, err := semver.Make(apiVersionString)
Expect(err).To(BeNil())
reqVersion, err := semver.ParseRange(">= " + version)
Expect(err).To(BeNil())
return reqVersion(apiVersion)
}
func ApiHasTask() bool {
supported, err := cutlass.ApiGreaterThan("2.75.0")
Expect(err).NotTo(HaveOccurred())
return supported
}
func ApiHasMultiBuildpack() bool {
supported, err := cutlass.ApiGreaterThan("2.90.0")
Expect(err).NotTo(HaveOccurred())
return supported
}
func ApiHasStackAssociation() bool {
supported, err := cutlass.ApiGreaterThan("2.113.0")
Expect(err).NotTo(HaveOccurred())
return supported
}
func AssertUsesProxyDuringStagingIfPresent(fixtureName string) {
Context("with an uncached buildpack", func() {
BeforeEach(func() {
if cutlass.Cached {
Skip("Running cached tests")
}
})
It("uses a proxy during staging if present", func() {
proxy, err := cutlass.NewProxy()
Expect(err).To(BeNil())
defer proxy.Close()
bpFile := filepath.Join(bpDir, buildpackVersion+"tmp")
cmd := exec.Command("cp", packagedBuildpack.File, bpFile)
err = cmd.Run()
Expect(err).To(BeNil())
defer os.Remove(bpFile)
traffic, built, _, err := cutlass.InternetTraffic(
filepath.Join("fixtures", fixtureName),
bpFile,
[]string{"HTTP_PROXY=" + proxy.URL, "HTTPS_PROXY=" + proxy.URL},
)
Expect(err).To(BeNil())
Expect(built).To(BeTrue())
destUrl, err := url.Parse(proxy.URL)
Expect(err).To(BeNil())
Expect(cutlass.UniqueDestination(
traffic, fmt.Sprintf("%s.%s", destUrl.Hostname(), destUrl.Port()),
)).To(BeNil())
})
})
}
func AssertNoInternetTraffic(fixtureName string) {
It("has no traffic", func() {
if !cutlass.Cached {
Skip("Running uncached tests")
}
bpFile := filepath.Join(bpDir, buildpackVersion+"tmp")
cmd := exec.Command("cp", packagedBuildpack.File, bpFile)
err := cmd.Run()
Expect(err).To(BeNil())
defer os.Remove(bpFile)
traffic, built, _, err := cutlass.InternetTraffic(
filepath.Join("fixtures", fixtureName),
bpFile,
[]string{},
)
Expect(err).To(BeNil())
Expect(built).To(BeTrue())
Expect(traffic).To(BeEmpty())
})
}
func RunCF(args ...string) error {
command := exec.Command("cf", args...)
command.Stdout = GinkgoWriter
command.Stderr = GinkgoWriter
return command.Run()
}
| [
"\"CF_STACK\""
]
| []
| [
"CF_STACK"
]
| [] | ["CF_STACK"] | go | 1 | 0 | |
src/test/java/com/amadeus/AmadeusTest.java | package com.amadeus;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
public class AmadeusTest {
/**
* Amadeus Test.
*/
@Test public void testBuilder() {
Amadeus.builder("id", "secret");
assertTrue(true,
"should return a Configuration");
}
@Test public void testBuilderWithNullClientId() {
assertThrows(NullPointerException.class, () -> Amadeus.builder(null, "secret").build());
}
@Test public void testBuilderWithNullClientSecret() {
assertThrows(NullPointerException.class, () -> Amadeus.builder("client", null).build());
}
@Test public void testBuilderWithEnvironment() {
Map<String,String> environment = new HashMap<String,String>() {
{
put("AMADEUS_CLIENT_ID", "123");
put("AMADEUS_CLIENT_SECRET", "234");
put("AMADEUS_LOG_LEVEL", "debug");
put("AMADEUS_PORT", "123");
put("AMADEUS_HOST", "my.custom.host.com");
}
};
Amadeus.builder(environment);
assertTrue(true, "should return a Configuration");
Amadeus amadeus = Amadeus.builder(environment).build();
assertEquals(amadeus.getConfiguration().getLogLevel(), "debug");
assertEquals(amadeus.getConfiguration().getPort(), 123);
assertEquals(amadeus.getConfiguration().getHost(), "my.custom.host.com");
}
@Test
public void testBuilderWithInvalidEnvironment() {
//Given
Map<String,String> environment = new HashMap<>(); //System.getenv();
environment.put("AMADEUS_CLIENT_ID", "MY_CLIENT_ID");
environment.put("AMADEUS_CLIENT_SECRET", "MY_CLIENT_SECRET");
//When
boolean result = Amadeus.builder(environment).build() instanceof Amadeus;
//Then
assertTrue(result, "should return a Configuration");
}
@Test public void testVersion() {
assertEquals(Amadeus.VERSION, "5.9.0", "should have a version number");
}
}
| []
| []
| []
| [] | [] | java | 0 | 0 | |
internal/goph/hosts.go | // Copyright 2020 Mohammed El Bahja. All rights reserved.
// Use of this source code is governed by a MIT license.
package goph
import (
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/knownhosts"
"os"
"strings"
)
// Use default known hosts files to verify host public key.
func DefaultKnownHosts() (ssh.HostKeyCallback, error) {
return KnownHosts(strings.Join([]string{os.Getenv("HOME"), ".ssh", "known_hosts"}, "/"))
}
// Get known hosts callback from a custom path.
func KnownHosts(kh string) (ssh.HostKeyCallback, error) {
return knownhosts.New(kh)
}
| [
"\"HOME\""
]
| []
| [
"HOME"
]
| [] | ["HOME"] | go | 1 | 0 | |
src/aws.py | import os
import boto3
from dotenv import load_dotenv
load_dotenv()
ACCESS_KEY = os.getenv('AMAZON_ACCESS_KEY')
SECRET_KEY = os.getenv('AMAZON_SECRET_KEY')
BUCKET = 'rpreview-images'
def upload_to_aws(fp, s3_file_name):
s3 = boto3.client('s3', aws_access_key_id=ACCESS_KEY,
aws_secret_access_key=SECRET_KEY)
try:
s3.upload_file(fp, BUCKET, s3_file_name)
print('Upload Successful')
return True
except Exception as e:
print(e)
return False
| []
| []
| [
"AMAZON_ACCESS_KEY",
"AMAZON_SECRET_KEY"
]
| [] | ["AMAZON_ACCESS_KEY", "AMAZON_SECRET_KEY"] | python | 2 | 0 | |
library/test_ceph_volume.py | from . import ceph_volume
from ansible.compat.tests.mock import MagicMock
import mock
import os
@mock.patch.dict(os.environ, {'CEPH_CONTAINER_BINARY': 'docker'})
class TestCephVolumeModule(object):
def test_data_no_vg(self):
result = ceph_volume.get_data("/dev/sda", None)
assert result == "/dev/sda"
def test_data_with_vg(self):
result = ceph_volume.get_data("data-lv", "data-vg")
assert result == "data-vg/data-lv"
def test_journal_no_vg(self):
result = ceph_volume.get_journal("/dev/sda1", None)
assert result == "/dev/sda1"
def test_journal_with_vg(self):
result = ceph_volume.get_journal("journal-lv", "journal-vg")
assert result == "journal-vg/journal-lv"
def test_db_no_vg(self):
result = ceph_volume.get_db("/dev/sda1", None)
assert result == "/dev/sda1"
def test_db_with_vg(self):
result = ceph_volume.get_db("db-lv", "db-vg")
assert result == "db-vg/db-lv"
def test_wal_no_vg(self):
result = ceph_volume.get_wal("/dev/sda1", None)
assert result == "/dev/sda1"
def test_wal_with_vg(self):
result = ceph_volume.get_wal("wal-lv", "wal-vg")
assert result == "wal-vg/wal-lv"
def test_container_exec(self):
fake_binary = "ceph-volume"
fake_container_image = "docker.io/ceph/daemon:latest-luminous"
expected_command_list = ['docker', 'run', '--rm', '--privileged', '--net=host', # noqa E501
'-v', '/run/lock/lvm:/run/lock/lvm:z',
'-v', '/var/run/udev/:/var/run/udev/:z',
'-v', '/dev:/dev', '-v', '/etc/ceph:/etc/ceph:z', # noqa E501
'-v', '/run/lvm/lvmetad.socket:/run/lvm/lvmetad.socket', # noqa E501
'-v', '/var/lib/ceph/:/var/lib/ceph/:z',
'-v', '/var/log/ceph/:/var/log/ceph/:z',
'--entrypoint=ceph-volume',
'docker.io/ceph/daemon:latest-luminous']
result = ceph_volume.container_exec(fake_binary, fake_container_image)
assert result == expected_command_list
def test_zap_osd_container(self):
fake_module = MagicMock()
fake_module.params = {'data': '/dev/sda'}
fake_container_image = "docker.io/ceph/daemon:latest-luminous"
expected_command_list = ['docker', 'run', '--rm', '--privileged', '--net=host', # noqa E501
'-v', '/run/lock/lvm:/run/lock/lvm:z',
'-v', '/var/run/udev/:/var/run/udev/:z',
'-v', '/dev:/dev', '-v', '/etc/ceph:/etc/ceph:z', # noqa E501
'-v', '/run/lvm/lvmetad.socket:/run/lvm/lvmetad.socket', # noqa E501
'-v', '/var/lib/ceph/:/var/lib/ceph/:z',
'-v', '/var/log/ceph/:/var/log/ceph/:z',
'--entrypoint=ceph-volume',
'docker.io/ceph/daemon:latest-luminous',
'lvm',
'zap',
'--destroy',
'/dev/sda']
result = ceph_volume.zap_devices(fake_module, fake_container_image)
assert result == expected_command_list
def test_zap_osd(self):
fake_module = MagicMock()
fake_module.params = {'data': '/dev/sda'}
fake_container_image = None
expected_command_list = ['ceph-volume',
'lvm',
'zap',
'--destroy',
'/dev/sda']
result = ceph_volume.zap_devices(fake_module, fake_container_image)
assert result == expected_command_list
def test_activate_osd(self):
expected_command_list = ['ceph-volume',
'lvm',
'activate',
'--all']
result = ceph_volume.activate_osd()
assert result == expected_command_list
def test_list_osd(self):
fake_module = MagicMock()
fake_module.params = {'cluster': 'ceph', 'data': '/dev/sda'}
fake_container_image = None
expected_command_list = ['ceph-volume',
'--cluster',
'ceph',
'lvm',
'list',
'/dev/sda',
'--format=json',
]
result = ceph_volume.list_osd(fake_module, fake_container_image)
assert result == expected_command_list
def test_list_osd_container(self):
fake_module = MagicMock()
fake_module.params = {'cluster': 'ceph', 'data': '/dev/sda'}
fake_container_image = "docker.io/ceph/daemon:latest-luminous"
expected_command_list = ['docker', 'run', '--rm', '--privileged', '--net=host', # noqa E501
'-v', '/run/lock/lvm:/run/lock/lvm:z',
'-v', '/var/run/udev/:/var/run/udev/:z',
'-v', '/dev:/dev', '-v', '/etc/ceph:/etc/ceph:z', # noqa E501
'-v', '/run/lvm/lvmetad.socket:/run/lvm/lvmetad.socket', # noqa E501
'-v', '/var/lib/ceph/:/var/lib/ceph/:z',
'-v', '/var/log/ceph/:/var/log/ceph/:z',
'--entrypoint=ceph-volume',
'docker.io/ceph/daemon:latest-luminous',
'--cluster',
'ceph',
'lvm',
'list',
'/dev/sda',
'--format=json',
]
result = ceph_volume.list_osd(fake_module, fake_container_image)
assert result == expected_command_list
def test_list_storage_inventory(self):
fake_module = MagicMock()
fake_container_image = None
expected_command_list = ['ceph-volume',
'inventory',
'--format=json',
]
result = ceph_volume.list_storage_inventory(fake_module, fake_container_image)
assert result == expected_command_list
def test_list_storage_inventory_container(self):
fake_module = MagicMock()
fake_container_image = "docker.io/ceph/daemon:latest-luminous"
expected_command_list = ['docker', 'run', '--rm', '--privileged', '--net=host', # noqa E501
'-v', '/run/lock/lvm:/run/lock/lvm:z',
'-v', '/var/run/udev/:/var/run/udev/:z',
'-v', '/dev:/dev', '-v', '/etc/ceph:/etc/ceph:z', # noqa E501
'-v', '/run/lvm/lvmetad.socket:/run/lvm/lvmetad.socket', # noqa E501
'-v', '/var/lib/ceph/:/var/lib/ceph/:z',
'-v', '/var/log/ceph/:/var/log/ceph/:z',
'--entrypoint=ceph-volume',
'docker.io/ceph/daemon:latest-luminous',
'inventory',
'--format=json',
]
result = ceph_volume.list_storage_inventory(fake_module, fake_container_image)
assert result == expected_command_list
def test_create_osd_container(self):
fake_module = MagicMock()
fake_module.params = {'data': '/dev/sda',
'objectstore': 'filestore',
'cluster': 'ceph', }
fake_action = "create"
fake_container_image = "docker.io/ceph/daemon:latest-luminous"
expected_command_list = ['docker', 'run', '--rm', '--privileged', '--net=host', # noqa E501
'-v', '/run/lock/lvm:/run/lock/lvm:z',
'-v', '/var/run/udev/:/var/run/udev/:z',
'-v', '/dev:/dev', '-v', '/etc/ceph:/etc/ceph:z', # noqa E501
'-v', '/run/lvm/lvmetad.socket:/run/lvm/lvmetad.socket', # noqa E501
'-v', '/var/lib/ceph/:/var/lib/ceph/:z',
'-v', '/var/log/ceph/:/var/log/ceph/:z',
'--entrypoint=ceph-volume',
'docker.io/ceph/daemon:latest-luminous',
'--cluster',
'ceph',
'lvm',
'create',
'--filestore',
'--data',
'/dev/sda']
result = ceph_volume.prepare_or_create_osd(
fake_module, fake_action, fake_container_image)
assert result == expected_command_list
def test_create_osd(self):
fake_module = MagicMock()
fake_module.params = {'data': '/dev/sda',
'objectstore': 'filestore',
'cluster': 'ceph', }
fake_container_image = None
fake_action = "create"
expected_command_list = ['ceph-volume',
'--cluster',
'ceph',
'lvm',
'create',
'--filestore',
'--data',
'/dev/sda']
result = ceph_volume.prepare_or_create_osd(
fake_module, fake_action, fake_container_image)
assert result == expected_command_list
def test_prepare_osd_container(self):
fake_module = MagicMock()
fake_module.params = {'data': '/dev/sda',
'objectstore': 'filestore',
'cluster': 'ceph', }
fake_action = "prepare"
fake_container_image = "docker.io/ceph/daemon:latest-luminous"
expected_command_list = ['docker', 'run', '--rm', '--privileged', '--net=host', # noqa E501
'-v', '/run/lock/lvm:/run/lock/lvm:z',
'-v', '/var/run/udev/:/var/run/udev/:z',
'-v', '/dev:/dev', '-v', '/etc/ceph:/etc/ceph:z', # noqa E501
'-v', '/run/lvm/lvmetad.socket:/run/lvm/lvmetad.socket', # noqa E501
'-v', '/var/lib/ceph/:/var/lib/ceph/:z',
'-v', '/var/log/ceph/:/var/log/ceph/:z',
'--entrypoint=ceph-volume',
'docker.io/ceph/daemon:latest-luminous',
'--cluster',
'ceph',
'lvm',
'prepare',
'--filestore',
'--data',
'/dev/sda']
result = ceph_volume.prepare_or_create_osd(
fake_module, fake_action, fake_container_image)
assert result == expected_command_list
def test_prepare_osd(self):
fake_module = MagicMock()
fake_module.params = {'data': '/dev/sda',
'objectstore': 'filestore',
'cluster': 'ceph', }
fake_container_image = None
fake_action = "prepare"
expected_command_list = ['ceph-volume',
'--cluster',
'ceph',
'lvm',
'prepare',
'--filestore',
'--data',
'/dev/sda']
result = ceph_volume.prepare_or_create_osd(
fake_module, fake_action, fake_container_image)
assert result == expected_command_list
def test_batch_osd_container(self):
fake_module = MagicMock()
fake_module.params = {'data': '/dev/sda',
'objectstore': 'filestore',
'journal_size': '100',
'cluster': 'ceph',
'batch_devices': ["/dev/sda", "/dev/sdb"]}
fake_container_image = "docker.io/ceph/daemon:latest-luminous"
expected_command_list = ['docker', 'run', '--rm', '--privileged', '--net=host', # noqa E501
'-v', '/run/lock/lvm:/run/lock/lvm:z',
'-v', '/var/run/udev/:/var/run/udev/:z',
'-v', '/dev:/dev', '-v', '/etc/ceph:/etc/ceph:z', # noqa E501
'-v', '/run/lvm/lvmetad.socket:/run/lvm/lvmetad.socket', # noqa E501
'-v', '/var/lib/ceph/:/var/lib/ceph/:z',
'-v', '/var/log/ceph/:/var/log/ceph/:z',
'--entrypoint=ceph-volume',
'docker.io/ceph/daemon:latest-luminous',
'--cluster',
'ceph',
'lvm',
'batch',
'--filestore',
'--yes',
'--prepare',
'--journal-size',
'100',
'/dev/sda',
'/dev/sdb']
result = ceph_volume.batch(
fake_module, fake_container_image)
assert result == expected_command_list
def test_batch_osd(self):
fake_module = MagicMock()
fake_module.params = {'data': '/dev/sda',
'objectstore': 'filestore',
'journal_size': '100',
'cluster': 'ceph',
'batch_devices': ["/dev/sda", "/dev/sdb"]}
fake_container_image = None
expected_command_list = ['ceph-volume',
'--cluster',
'ceph',
'lvm',
'batch',
'--filestore',
'--yes',
'--journal-size',
'100',
'/dev/sda',
'/dev/sdb']
result = ceph_volume.batch(
fake_module, fake_container_image)
assert result == expected_command_list
| []
| []
| []
| [] | [] | python | 0 | 0 | |
tests/e2e/etcd_spawn_cov.go | // Copyright 2017 The etcd Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// +build cov
package e2e
import (
"fmt"
"os"
"path/filepath"
"strings"
"syscall"
"time"
"github.com/templexxx/etcd/pkg/expect"
"github.com/templexxx/etcd/pkg/fileutil"
"github.com/templexxx/etcd/pkg/flags"
)
const noOutputLineCount = 2 // cov-enabled binaries emit PASS and coverage count lines
func spawnCmd(args []string) (*expect.ExpectProcess, error) {
if args[0] == binPath {
return spawnEtcd(args)
}
if args[0] == ctlBinPath || args[0] == ctlBinPath+"3" {
// avoid test flag conflicts in coverage enabled etcdctl by putting flags in ETCDCTL_ARGS
env := []string{
// was \xff, but that's used for testing boundary conditions; 0xe7cd should be safe
"ETCDCTL_ARGS=" + strings.Join(args, "\xe7\xcd"),
}
if args[0] == ctlBinPath+"3" {
env = append(env, "ETCDCTL_API=3")
}
covArgs, err := getCovArgs()
if err != nil {
return nil, err
}
// when withFlagByEnv() is used in testCtl(), env variables for ctl is set to os.env.
// they must be included in ctl_cov_env.
env = append(env, os.Environ()...)
ep, err := expect.NewExpectWithEnv(binDir+"/etcdctl_test", covArgs, env)
if err != nil {
return nil, err
}
ep.StopSignal = syscall.SIGTERM
return ep, nil
}
return expect.NewExpect(args[0], args[1:]...)
}
func spawnEtcd(args []string) (*expect.ExpectProcess, error) {
covArgs, err := getCovArgs()
if err != nil {
return nil, err
}
var env []string
if args[1] == "grpc-proxy" {
// avoid test flag conflicts in coverage enabled etcd by putting flags in ETCDCOV_ARGS
env = append(os.Environ(), "ETCDCOV_ARGS="+strings.Join(args, "\xe7\xcd"))
} else {
env = args2env(args[1:])
}
ep, err := expect.NewExpectWithEnv(binDir+"/etcd_test", covArgs, env)
if err != nil {
return nil, err
}
// ep sends SIGTERM to etcd_test process on ep.close()
// allowing the process to exit gracefully in order to generate a coverage report.
// note: go runtime ignores SIGINT but not SIGTERM
// if e2e test is run as a background process.
ep.StopSignal = syscall.SIGTERM
return ep, nil
}
func getCovArgs() ([]string, error) {
coverPath := os.Getenv("COVERDIR")
if !filepath.IsAbs(coverPath) {
// COVERDIR is relative to etcd root but e2e test has its path set to be relative to the e2e folder.
// adding ".." in front of COVERDIR ensures that e2e saves coverage reports to the correct location.
coverPath = filepath.Join("../..", coverPath)
}
if !fileutil.Exist(coverPath) {
return nil, fmt.Errorf("could not find coverage folder")
}
covArgs := []string{
fmt.Sprintf("-test.coverprofile=e2e.%v.coverprofile", time.Now().UnixNano()),
"-test.outputdir=" + coverPath,
}
return covArgs, nil
}
func args2env(args []string) []string {
var covEnvs []string
for i := range args {
if !strings.HasPrefix(args[i], "--") {
continue
}
flag := strings.Split(args[i], "--")[1]
val := "true"
// split the flag that has "="
// e.g --auto-tls=true" => flag=auto-tls and val=true
if strings.Contains(args[i], "=") {
split := strings.Split(flag, "=")
flag = split[0]
val = split[1]
}
if i+1 < len(args) {
if !strings.HasPrefix(args[i+1], "--") {
val = args[i+1]
}
}
covEnvs = append(covEnvs, flags.FlagToEnv("ETCD", flag)+"="+val)
}
return covEnvs
}
| [
"\"COVERDIR\""
]
| []
| [
"COVERDIR"
]
| [] | ["COVERDIR"] | go | 1 | 0 | |
main.py | import os
import hashlib
import random
import string
from datetime import datetime
import pytz
import logging
from flask import Flask, render_template, request, session, Markup, redirect, url_for
from boto.s3.connection import S3Connection
from google.appengine.api import memcache
from google.appengine.ext.appstats import recording
PASSWORD = os.environ.get('PASSWORD')
SECRET_KEY = os.environ['SECRET_KEY']
CACHE_TTL = int(os.environ['CACHE_TTL'])
S3_LINK_TTL = int(os.environ['S3_LINK_TTL'])
BUCKET = os.environ['BUCKET']
ACCESS_KEY = os.environ['ACCESS_KEY']
SECRET_ACCESS_KEY = os.environ['SECRET_ACCESS_KEY']
def format_fsize(fsize):
formats = {
0: "{:03.1f} {}",
1: "{:03.1f} {}",
2: "{: 3.0f} {}",
# For zero-padding instead of space padding
# 2: "{:03.0f} {}",
3: "{:03.0f} {}",
}
prefixes = ["B", "K", "M", "G", "T", "P", "E"]
incr = 0
while len(str(int(round(fsize)))) > 3:
fsize = fsize / 1024.0
incr += 1
if incr >= len(prefixes) - 1:
raise RuntimeError
out_string = formats[len(str(int(round(fsize))))].format(fsize, prefixes[incr])
return Markup(out_string.replace(" ", " "))
def format_timestring(dt_string):
dt_unaware = datetime.strptime(dt_string, "%Y-%m-%dT%H:%M:%S.000Z")
dt_aware = dt_unaware.replace(tzinfo=pytz.UTC)
return dt_aware.strftime("%a %d-%b-%y %H:%M:%S %z")
class Config(object):
DEBUG = False
TESTING = False
CSRF_ENABLED = True
SECRET_KEY = SECRET_KEY
class Entity(object):
def __init__(self, name):
self.name = name
class File(Entity):
def __init__(self, name, last_modified, size, url):
self.name = name
self.last_modified = last_modified
self.size = format_fsize(size)
self.url = url
self.ext = os.path.splitext(name)[1].replace(".", "")
self.dir = False
class Folder(Entity):
def __init__(self, name):
self.name = name
self.url = u"./{}".format(name)
self.dir = True
def login():
if not PASSWORD:
# Password is not set, or is empty
# So we skip authentication
return True
secret_key = memcache.get('secret_key')
if not secret_key:
secret_key = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(10))
memcache.add('secret_key', secret_key)
if request.form.get('password') == PASSWORD:
session['secret_key'] = secret_key
if session.get('secret_key') == secret_key:
return True
return False
app = Flask(__name__)
app.wsgi_app = recording.appstats_wsgi_middleware(app.wsgi_app)
app.config.from_object(Config)
@app.route('/', methods=['GET', 'POST'])
def home():
return redirect(url_for("index", path=""))
@app.route('/bucket/', methods=['GET', 'POST'])
def catch_urls():
"""
Alias for the index function at the root,
Flask won't let us catch the root dir with the <path> variable
"""
return index("")
@app.route('/bucket/<path:path>', methods=['GET', 'POST'])
def index(path):
if not login():
return render_template("login.html")
refresh_cache = request.args.get('flush')
page_id = hashlib.md5(path.encode('ascii', errors='ignore')).hexdigest()
page = memcache.get(page_id)
if page is None or refresh_cache:
conn = S3Connection(ACCESS_KEY, SECRET_ACCESS_KEY)
bucket = conn.get_bucket(BUCKET)
contents = bucket.list(
prefix=path,
delimiter="/")
entities = []
for key in list(contents):
try:
entity = File(
name=key.name[len(path):],
last_modified=format_timestring(key.last_modified),
size=key.size,
url=key.generate_url(S3_LINK_TTL))
except AttributeError:
entity = Folder(
name=key.name[len(path):])
entities.append(entity)
page = render_template(
"index.html",
path=u"/{}".format(path),
flush_url=u"{}?flush=1".format(request.url) if not refresh_cache else request.url,
entities=entities)
if not memcache.set(page_id, page, CACHE_TTL):
logging.warning("Failed to update memcache.")
return page
# if __name__ == '__main__':
# app.run(host="0.0.0.0", debug=True, threaded=True)
| []
| []
| [
"PASSWORD",
"ACCESS_KEY",
"BUCKET",
"CACHE_TTL",
"SECRET_ACCESS_KEY",
"SECRET_KEY",
"S3_LINK_TTL"
]
| [] | ["PASSWORD", "ACCESS_KEY", "BUCKET", "CACHE_TTL", "SECRET_ACCESS_KEY", "SECRET_KEY", "S3_LINK_TTL"] | python | 7 | 0 | |
pkg/template/generated/internalclientset/fake/register.go | package fake
import (
template "github.com/openshift/origin/pkg/template/api/install"
announced "k8s.io/apimachinery/pkg/apimachinery/announced"
registered "k8s.io/apimachinery/pkg/apimachinery/registered"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
schema "k8s.io/apimachinery/pkg/runtime/schema"
serializer "k8s.io/apimachinery/pkg/runtime/serializer"
os "os"
)
var scheme = runtime.NewScheme()
var codecs = serializer.NewCodecFactory(scheme)
var parameterCodec = runtime.NewParameterCodec(scheme)
var registry = registered.NewOrDie(os.Getenv("KUBE_API_VERSIONS"))
var groupFactoryRegistry = make(announced.APIGroupFactoryRegistry)
func init() {
v1.AddToGroupVersion(scheme, schema.GroupVersion{Version: "v1"})
Install(groupFactoryRegistry, registry, scheme)
}
// Install registers the API group and adds types to a scheme
func Install(groupFactoryRegistry announced.APIGroupFactoryRegistry, registry *registered.APIRegistrationManager, scheme *runtime.Scheme) {
template.Install(groupFactoryRegistry, registry, scheme)
}
| [
"\"KUBE_API_VERSIONS\""
]
| []
| [
"KUBE_API_VERSIONS"
]
| [] | ["KUBE_API_VERSIONS"] | go | 1 | 0 | |
golangerr/album_test.go | package album
import (
"bytes"
"encoding/json"
"os"
"reflect"
"testing"
"time"
)
func createAlbum() *Album {
return &Album{
ID: 0,
Name: "Nature",
Photos: []Photo{
{
ID: 0,
Name: "Acacia",
DateTime: time.Date(2021, 5, 4, 12, 0, 0, 0, time.UTC),
},
{
ID: 1,
Name: "Begonia",
DateTime: time.Date(2021, 5, 30, 12, 0, 0, 0, time.UTC),
},
{
ID: 2,
Name: "Camellia",
DateTime: time.Date(2021, 6, 12, 14, 0, 0, 0, time.UTC),
},
{
ID: 3,
Name: "Daisy",
DateTime: time.Date(2021, 6, 14, 14, 0, 0, 0, time.UTC),
},
{
ID: 4,
Name: "Eustoma",
DateTime: time.Date(2021, 8, 11, 14, 0, 0, 0, time.UTC),
},
{
ID: 5,
Name: "Forget Me Not",
DateTime: time.Date(2021, 8, 11, 14, 0, 0, 0, time.UTC),
},
{
ID: 6,
Name: "Snow",
DateTime: time.Date(2021, 12, 11, 14, 0, 0, 0, time.UTC),
},
{
ID: 7,
Name: "More snow",
DateTime: time.Date(2021, 12, 15, 14, 0, 0, 0, time.UTC),
},
{
ID: 8,
Name: "Moon",
DateTime: time.Date(2022, 1, 1, 14, 0, 0, 0, time.UTC),
},
{
ID: 9,
Name: "More moon",
DateTime: time.Date(2022, 6, 1, 14, 0, 0, 0, time.UTC),
},
{
ID: 10,
Name: "Snow",
DateTime: time.Date(2022, 12, 1, 14, 0, 0, 0, time.UTC),
},
},
}
}
func TestGetPhotos(t *testing.T) {
a := createAlbum()
got := a.GetPhotos(time.Date(2021, 6, 13, 12, 0, 0, 0, time.UTC), time.Date(2021, 9, 1, 0, 0, 0, 0, time.UTC))
want := []Photo{
{
ID: 3,
Name: "Daisy",
DateTime: time.Date(2021, 6, 14, 14, 0, 0, 0, time.UTC),
},
{
ID: 4,
Name: "Eustoma",
DateTime: time.Date(2021, 8, 11, 14, 0, 0, 0, time.UTC),
},
{
ID: 5,
Name: "Forget Me Not",
DateTime: time.Date(2021, 8, 11, 14, 0, 0, 0, time.UTC),
},
}
if !reflect.DeepEqual(got, want) {
t.Errorf("Got = %v, want %v", got, want)
}
}
func TestGetHolidayPhotos(t *testing.T) {
a := createAlbum()
got := GetHolidayPhotos(a, 2021)
want := []Photo{
{
ID: 2,
Name: "Camellia",
DateTime: time.Date(2021, 6, 12, 14, 0, 0, 0, time.UTC),
},
{
ID: 3,
Name: "Daisy",
DateTime: time.Date(2021, 6, 14, 14, 0, 0, 0, time.UTC),
},
{
ID: 6,
Name: "Snow",
DateTime: time.Date(2021, 12, 11, 14, 0, 0, 0, time.UTC),
},
{
ID: 7,
Name: "More snow",
DateTime: time.Date(2021, 12, 15, 14, 0, 0, 0, time.UTC),
},
}
if !reflect.DeepEqual(got, want) {
t.Errorf("Got = %v, want %v", got, want)
}
}
func TestGetHolidayPhotosNotMutatingInput(t *testing.T) {
if os.Getenv("MUTATION_TEST") == "" {
t.Skip("Skipping mutation test")
}
album := createAlbum()
serializedAlbum, err := json.Marshal(album)
if err != nil {
t.Fatalf("Got error %v", err)
}
GetHolidayPhotos(album, 2021)
postmortemSerializedAlbum, err := json.Marshal(album)
if err != nil {
t.Fatalf("Got error %v", err)
}
if !bytes.Equal(postmortemSerializedAlbum, serializedAlbum) {
t.Errorf(
"Got postmortemSerializedAlbum = %v, want serializedAlbum = %v",
string(postmortemSerializedAlbum[:]),
string(serializedAlbum[:]),
)
}
}
| [
"\"MUTATION_TEST\""
]
| []
| [
"MUTATION_TEST"
]
| [] | ["MUTATION_TEST"] | go | 1 | 0 | |
scripts/run_mypy_checks.py | # coding: utf-8
#
# Copyright 2021 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""MyPy test runner script."""
from __future__ import annotations
import argparse
import os
import site
import subprocess
import sys
from scripts import common
from scripts import install_third_party_libs
# List of directories whose files won't be type-annotated ever.
EXCLUDED_DIRECTORIES = [
'proto_files/',
'scripts/linters/test_files/',
'third_party/',
'venv/'
]
# List of files who should be type-annotated but are not.
NOT_FULLY_COVERED_FILES = [
'core/controllers/',
'core/domain/auth_services.py',
'core/domain/auth_services_test.py',
'core/domain/blog_services.py',
'core/domain/blog_services_test.py',
'core/domain/change_domain.py',
'core/domain/classifier_services.py',
'core/domain/classifier_services_test.py',
'core/domain/classroom_services.py',
'core/domain/classroom_services_test.py',
'core/domain/collection_domain.py',
'core/domain/collection_domain_test.py',
'core/domain/collection_services.py',
'core/domain/collection_services_test.py',
'core/domain/cron_services.py',
'core/domain/customization_args_util.py',
'core/domain/customization_args_util_test.py',
'core/domain/draft_upgrade_services.py',
'core/domain/draft_upgrade_services_test.py',
'core/domain/email_manager.py',
'core/domain/email_manager_test.py',
'core/domain/email_services.py',
'core/domain/email_services_test.py',
'core/domain/email_subscription_services.py',
'core/domain/email_subscription_services_test.py',
'core/domain/event_services.py',
'core/domain/event_services_test.py',
'core/domain/exp_domain.py',
'core/domain/exp_domain_test.py',
'core/domain/exp_fetchers.py',
'core/domain/exp_fetchers_test.py',
'core/domain/exp_services.py',
'core/domain/exp_services_test.py',
'core/domain/expression_parser.py',
'core/domain/expression_parser_test.py',
'core/domain/feedback_services.py',
'core/domain/feedback_services_test.py',
'core/domain/fs_domain.py',
'core/domain/fs_domain_test.py',
'core/domain/fs_services.py',
'core/domain/fs_services_test.py',
'core/domain/html_cleaner.py',
'core/domain/html_cleaner_test.py',
'core/domain/html_validation_service.py',
'core/domain/html_validation_service_test.py',
'core/domain/image_validation_services.py',
'core/domain/image_validation_services_test.py',
'core/domain/improvements_services.py',
'core/domain/improvements_services_test.py',
'core/domain/interaction_registry.py',
'core/domain/interaction_registry_test.py',
'core/domain/learner_goals_services.py',
'core/domain/learner_goals_services_test.py',
'core/domain/learner_playlist_services.py',
'core/domain/learner_playlist_services_test.py',
'core/domain/learner_progress_services.py',
'core/domain/learner_progress_services_test.py',
'core/domain/moderator_services.py',
'core/domain/moderator_services_test.py',
'core/domain/object_registry.py',
'core/domain/object_registry_test.py',
'core/domain/opportunity_services.py',
'core/domain/opportunity_services_test.py',
'core/domain/param_domain.py',
'core/domain/param_domain_test.py',
'core/domain/platform_feature_services.py',
'core/domain/platform_feature_services_test.py',
'core/domain/platform_parameter_domain.py',
'core/domain/platform_parameter_domain_test.py',
'core/domain/platform_parameter_list.py',
'core/domain/platform_parameter_list_test.py',
'core/domain/platform_parameter_registry.py',
'core/domain/platform_parameter_registry_test.py',
'core/domain/playthrough_issue_registry.py',
'core/domain/playthrough_issue_registry_test.py',
'core/domain/question_domain.py',
'core/domain/question_domain_test.py',
'core/domain/question_fetchers.py',
'core/domain/question_fetchers_test.py',
'core/domain/question_services.py',
'core/domain/question_services_test.py',
'core/domain/rating_services.py',
'core/domain/rating_services_test.py',
'core/domain/recommendations_services.py',
'core/domain/recommendations_services_test.py',
'core/domain/rights_manager.py',
'core/domain/rights_manager_test.py',
'core/domain/role_services.py',
'core/domain/role_services_test.py',
'core/domain/rte_component_registry.py',
'core/domain/rte_component_registry_test.py',
'core/domain/rules_registry.py',
'core/domain/rules_registry_test.py',
'core/domain/search_services.py',
'core/domain/search_services_test.py',
'core/domain/skill_domain.py',
'core/domain/skill_domain_test.py',
'core/domain/skill_fetchers.py',
'core/domain/skill_fetchers_test.py',
'core/domain/skill_services.py',
'core/domain/skill_services_test.py',
'core/domain/state_domain.py',
'core/domain/state_domain_test.py',
'core/domain/stats_domain.py',
'core/domain/stats_domain_test.py',
'core/domain/stats_services.py',
'core/domain/stats_services_test.py',
'core/domain/story_domain.py',
'core/domain/story_domain_test.py',
'core/domain/story_fetchers.py',
'core/domain/story_fetchers_test.py',
'core/domain/story_services.py',
'core/domain/story_services_test.py',
'core/domain/subscription_services.py',
'core/domain/subscription_services_test.py',
'core/domain/subtopic_page_domain.py',
'core/domain/subtopic_page_domain_test.py',
'core/domain/subtopic_page_services.py',
'core/domain/subtopic_page_services_test.py',
'core/domain/suggestion_registry.py',
'core/domain/suggestion_registry_test.py',
'core/domain/suggestion_services.py',
'core/domain/suggestion_services_test.py',
'core/domain/summary_services.py',
'core/domain/summary_services_test.py',
'core/domain/takeout_service.py',
'core/domain/takeout_service_test.py',
'core/domain/taskqueue_services.py',
'core/domain/taskqueue_services_test.py',
'core/domain/topic_fetchers.py',
'core/domain/topic_fetchers_test.py',
'core/domain/topic_services.py',
'core/domain/topic_services_test.py',
'core/domain/translatable_object_registry.py',
'core/domain/translatable_object_registry_test.py',
'core/domain/translation_fetchers.py',
'core/domain/translation_fetchers_test.py',
'core/domain/translation_services.py',
'core/domain/translation_services_test.py',
'core/domain/user_domain.py',
'core/domain/user_domain_test.py',
'core/domain/user_query_services.py',
'core/domain/user_query_services_test.py',
'core/domain/user_services.py',
'core/domain/user_services_test.py',
'core/domain/visualization_registry.py',
'core/domain/visualization_registry_test.py',
'core/domain/voiceover_services.py',
'core/domain/voiceover_services_test.py',
'core/domain/wipeout_service.py',
'core/domain/wipeout_service_test.py',
'core/platform/storage/cloud_storage_emulator.py',
'core/platform/storage/cloud_storage_emulator_test.py',
'core/platform_feature_list.py',
'core/platform_feature_list_test.py',
'core/storage/beam_job/gae_models.py',
'core/storage/beam_job/gae_models_test.py',
'core/storage/blog/gae_models.py',
'core/storage/blog/gae_models_test.py',
'core/storage/storage_models_test.py',
'core/tests/build_sources/extensions/CodeRepl.py',
'core/tests/build_sources/extensions/DragAndDropSortInput.py',
'core/tests/build_sources/extensions/base.py',
'core/tests/build_sources/extensions/base_test.py',
'core/tests/build_sources/extensions/models_test.py',
'core/tests/data/failing_tests.py',
'core/tests/data/image_constants.py',
'core/tests/data/unicode_and_str_handler.py',
'core/tests/gae_suite.py',
'core/tests/gae_suite_test.py',
'core/tests/load_tests/feedback_thread_summaries_test.py',
'core/tests/test_utils.py',
'core/tests/test_utils_test.py',
'core/jobs',
'core/python_utils.py',
'core/python_utils_test.py',
'extensions/',
'scripts/build.py',
'scripts/build_test.py',
'scripts/check_e2e_tests_are_captured_in_ci.py',
'scripts/check_e2e_tests_are_captured_in_ci_test.py',
'scripts/check_frontend_test_coverage.py',
'scripts/check_frontend_test_coverage_test.py',
'scripts/check_if_pr_is_low_risk.py',
'scripts/check_if_pr_is_low_risk_test.py',
'scripts/clean.py',
'scripts/clean_test.py',
'scripts/common.py',
'scripts/common_test.py',
'scripts/concurrent_task_utils.py',
'scripts/concurrent_task_utils_test.py',
'scripts/create_expression_parser.py',
'scripts/create_topological_sort_of_all_services.py',
'scripts/create_topological_sort_of_all_services_test.py',
'scripts/docstrings_checker.py',
'scripts/docstrings_checker_test.py',
'scripts/extend_index_yaml.py',
'scripts/extend_index_yaml_test.py',
'scripts/flake_checker.py',
'scripts/flake_checker_test.py',
'scripts/install_backend_python_libs.py',
'scripts/install_backend_python_libs_test.py',
'scripts/install_chrome_for_ci.py',
'scripts/install_chrome_for_ci_test.py',
'scripts/install_third_party_libs.py',
'scripts/install_third_party_libs_test.py',
'scripts/install_third_party.py',
'scripts/install_third_party_test.py',
'scripts/pre_commit_hook.py',
'scripts/pre_commit_hook_test.py',
'scripts/pre_push_hook.py',
'scripts/pre_push_hook_test.py',
'scripts/regenerate_requirements.py',
'scripts/regenerate_requirements_test.py',
'scripts/rtl_css.py',
'scripts/rtl_css_test.py',
'scripts/run_backend_tests.py',
'scripts/run_custom_eslint_tests.py',
'scripts/run_e2e_tests.py',
'scripts/run_e2e_tests_test.py',
'scripts/run_frontend_tests.py',
'scripts/run_lighthouse_tests.py',
'scripts/run_mypy_checks.py',
'scripts/run_mypy_checks_test.py',
'scripts/run_portserver.py',
'scripts/run_presubmit_checks.py',
'scripts/run_tests.py',
'scripts/script_import_test.py',
'scripts/scripts_test_utils.py',
'scripts/scripts_test_utils_test.py',
'scripts/servers.py',
'scripts/servers_test.py',
'scripts/setup.py',
'scripts/setup_test.py',
'scripts/typescript_checks.py',
'scripts/typescript_checks_test.py',
'scripts/linters/',
'scripts/release_scripts/'
]
CONFIG_FILE_PATH = os.path.join('.', 'mypy.ini')
MYPY_REQUIREMENTS_FILE_PATH = os.path.join('.', 'mypy_requirements.txt')
MYPY_TOOLS_DIR = os.path.join(os.getcwd(), 'third_party', 'python3_libs')
PYTHON3_CMD = 'python3'
_PATHS_TO_INSERT = [MYPY_TOOLS_DIR, ]
_PARSER = argparse.ArgumentParser(
description='Python type checking using mypy script.'
)
_PARSER.add_argument(
'--skip-install',
help='If passed, skips installing dependencies.'
' By default, they are installed.',
action='store_true')
_PARSER.add_argument(
'--install-globally',
help='optional; if specified, installs mypy and its requirements globally.'
' By default, they are installed to %s' % MYPY_TOOLS_DIR,
action='store_true')
_PARSER.add_argument(
'--files',
help='Files to type-check',
action='store',
nargs='+'
)
def install_third_party_libraries(skip_install: bool) -> None:
"""Run the installation script.
Args:
skip_install: bool. Whether to skip running the installation script.
"""
if not skip_install:
install_third_party_libs.main()
def get_mypy_cmd(files, mypy_exec_path, using_global_mypy):
"""Return the appropriate command to be run.
Args:
files: list(list(str)). List having first element as list of string.
mypy_exec_path: str. Path of mypy executable.
using_global_mypy: bool. Whether generated command should run using
global mypy.
Returns:
list(str). List of command line arguments.
"""
if using_global_mypy:
mypy_cmd = 'mypy'
else:
mypy_cmd = mypy_exec_path
if files:
cmd = [mypy_cmd, '--config-file', CONFIG_FILE_PATH] + files
else:
excluded_files_regex = (
'|'.join(NOT_FULLY_COVERED_FILES + EXCLUDED_DIRECTORIES))
cmd = [
mypy_cmd, '--exclude', excluded_files_regex,
'--config-file', CONFIG_FILE_PATH, '.'
]
return cmd
def install_mypy_prerequisites(install_globally):
"""Install mypy and type stubs from mypy_requirements.txt.
Args:
install_globally: bool. Whether mypy and its requirements are to be
installed globally.
Returns:
tuple(int, str). The return code from installing prerequisites and the
path of the mypy executable.
"""
# TODO(#13398): Change MyPy installation after Python3 migration. Now, we
# install packages globally for CI. In CI, pip installation is not in a way
# we expect.
if install_globally:
cmd = [
PYTHON3_CMD, '-m', 'pip', 'install', '-r',
MYPY_REQUIREMENTS_FILE_PATH
]
else:
cmd = [
PYTHON3_CMD, '-m', 'pip', 'install', '-r',
MYPY_REQUIREMENTS_FILE_PATH, '--target', MYPY_TOOLS_DIR,
'--upgrade'
]
process = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = process.communicate()
if b'can\'t combine user with prefix' in output[1]:
uextention_text = ['--user', '--prefix=', '--system']
new_process = subprocess.Popen(
cmd + uextention_text, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
new_process.communicate()
_PATHS_TO_INSERT.append(os.path.join(site.USER_BASE, 'bin'))
mypy_exec_path = os.path.join(site.USER_BASE, 'bin', 'mypy')
return (new_process.returncode, mypy_exec_path)
else:
_PATHS_TO_INSERT.append(os.path.join(MYPY_TOOLS_DIR, 'bin'))
mypy_exec_path = os.path.join(MYPY_TOOLS_DIR, 'bin', 'mypy')
return (process.returncode, mypy_exec_path)
def main(args=None):
"""Runs the MyPy type checks."""
parsed_args = _PARSER.parse_args(args=args)
for directory in common.DIRS_TO_ADD_TO_SYS_PATH:
# The directories should only be inserted starting at index 1. See
# https://stackoverflow.com/a/10095099 and
# https://stackoverflow.com/q/10095037 for more details.
sys.path.insert(1, directory)
install_third_party_libraries(parsed_args.skip_install)
common.fix_third_party_imports()
print('Installing Mypy and stubs for third party libraries.')
return_code, mypy_exec_path = install_mypy_prerequisites(
parsed_args.install_globally)
if return_code != 0:
print('Cannot install Mypy and stubs for third party libraries.')
sys.exit(1)
print('Installed Mypy and stubs for third party libraries.')
print('Starting Mypy type checks.')
cmd = get_mypy_cmd(
parsed_args.files, mypy_exec_path, parsed_args.install_globally)
env = os.environ.copy()
for path in _PATHS_TO_INSERT:
env['PATH'] = '%s%s' % (path, os.pathsep) + env['PATH']
env['PYTHONPATH'] = MYPY_TOOLS_DIR
process = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
stdout, stderr = process.communicate()
# Standard and error output is in bytes, we need to decode the line to
# print it.
print(stdout.decode('utf-8'))
print(stderr.decode('utf-8'))
if process.returncode == 0:
print('Mypy type checks successful.')
else:
print(
'Mypy type checks unsuccessful. Please fix the errors. '
'For more information, visit: '
'https://github.com/oppia/oppia/wiki/Backend-Type-Annotations')
sys.exit(2)
return process.returncode
if __name__ == '__main__': # pragma: no cover
main()
| []
| []
| []
| [] | [] | python | 0 | 0 | |
A02/utils/data_acq/runacq.py | #!/usr/bin/env python3
#
# (C) 2019-* Emanuele Ballarin <[email protected]>
# Distribution: MIT License.
# IMPORTS:
import os
import subprocess as proc
from subprocess import PIPE
import time
import numpy as np
###################################################################################################
def esf(speedup_pass, nthreads_pass):
"""Empirical Serial Fraction, given parallel speedup and number of threads
(after [Tornatore, 2019])"""
return ((1.0 / float(speedup_pass)) - (1.0 / float(nthreads_pass))) / (
1.0 - (1.0 / float(nthreads_pass))
)
###################################################################################################
def runacq_touchfirst(bin_name, nthreads, vector_len, isserial=False):
bin_path = "../../src/touch_by/"
call_env = os.environ.copy()
call_env["OMP_NUM_THREADS"] = str(nthreads)
execlist = [str(bin_path + bin_name), str(vector_len)]
ranproc = proc.run(execlist, stdout=PIPE, stderr=PIPE, check=True, env=call_env)
ranproc_stout = str(ranproc.stdout.decode())
ranproc_linesout = list(filter(None, ranproc_stout.split("\n")))
print(ranproc_linesout)
clean_linesout = [ranproc_linesout[-3], ranproc_linesout[-2], ranproc_linesout[-1]]
timesout = [
float(clean_linesout[0]), # Wall clock time
float(clean_linesout[1]), # Average single thread time
float(clean_linesout[2]), # Minimum single thread time
]
if isserial:
timesout = [
timesout[0]
] # Thread times are undefined and thus contain garbage values!
time.sleep(1)
return timesout # LIST: [walltime, threadavg, threadmin]
###################################################################################################
def runacq_touchbyall(bin_name, nthreads, vector_len, isserial=None):
bin_path = "../../src/touch_by/"
call_env = os.environ.copy()
call_env["OMP_NUM_THREADS"] = str(nthreads)
execlist = [str(bin_path + bin_name), str(vector_len)]
ranproc = proc.run(execlist, stdout=PIPE, stderr=PIPE, check=True, env=call_env)
ranproc_stout = str(ranproc.stdout.decode())
ranproc_linesout = list(filter(None, ranproc_stout.split("\n")))
print(ranproc_linesout)
clean_linesout = [ranproc_linesout[-1]]
timesout = [
float(clean_linesout[0]), # Wall clock time
]
time.sleep(1)
return timesout # LIST: [walltime]
###################################################################################################
def runacq_prefixsum(bin_name, nthreads, vector_len, isserial=None):
bin_path = "../../src/prefix_sum/"
call_env = os.environ.copy()
call_env["OMP_NUM_THREADS"] = str(nthreads)
execlist = [str(bin_path + bin_name), str(vector_len)]
ranproc = proc.run(execlist, stdout=PIPE, stderr=PIPE, check=True, env=call_env)
ranproc_stout = str(ranproc.stdout.decode())
ranproc_linesout = list(filter(None, ranproc_stout.split("\n")))
print(ranproc_linesout)
clean_linesout = [ranproc_linesout[-2], ranproc_linesout[-1]]
timesout = [
float(clean_linesout[0]), # Serial runtime - in nanoseconds
float(clean_linesout[1]), # Parallel runtime - in nanoseconds
float(0.0), # Speedup (still to be computed)
]
timesout = [
timesout[0] / 10e9, # Serial runtime - in seconds
timesout[1] / 10e9, # Parallel runtime - in seconds
timesout[0] / timesout[1], # Speedup
# Empirical serial fraction
]
timesout = [
timesout[0], # Serial runtime - in seconds
timesout[1], # Parallel runtime - in seconds
timesout[2], # Speedup
(
esf(timesout[2], nthreads) # Empirical serial fraction
# ((1.0 / float(timesout[2])) - (1.0 / float(nthreads)))
# / (1.0 - (1.0 / float(nthreads)))
),
]
time.sleep(1)
return timesout # LIST: [serialtime, paralleltime, speedup]
###################################################################################################
def acqavg(nrtimes, funcname, bin_name, nthreads, vector_len, isserial_pass=None):
"""Iterate the acquisition of data and average the results"""
if (funcname == "runacq_touchfirst") and (isserial_pass is None):
raise Exception(
"acqavg: function 'runacq_touchfirst' called with invalid 'isserial=None' argument!"
)
# First, out-of-loop call
ret_result = funcname(bin_name, nthreads, vector_len, isserial=isserial_pass)
accumulator_vector = np.asarray(ret_result, float)
for i in range(nrtimes - 1):
ret_result = funcname(bin_name, nthreads, vector_len, isserial=isserial_pass)
accumulator_vector += np.asarray(ret_result)
mean = accumulator_vector / nrtimes
return list(mean)
###################################################################################################
| []
| []
| []
| [] | [] | python | 0 | 0 | |
src/main/java/com/p6spy/engine/spy/option/EnvironmentVariables.java | /*
* #%L
* P6Spy
* %%
* Copyright (C) 2013 P6Spy
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.p6spy.engine.spy.option;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import com.p6spy.engine.spy.P6ModuleManager;
public class EnvironmentVariables implements P6OptionsSource {
@Override
public Map<String, String> getOptions() {
final Map<String, String> result = new HashMap<String, String>();
for (Entry<String, String> entry : System.getenv().entrySet()) {
final String key = entry.getKey();
if (key.startsWith(SystemProperties.P6SPY_PREFIX)) {
result.put(key.substring(SystemProperties.P6SPY_PREFIX.length()), (String) entry.getValue());
}
}
return result;
}
@Override
public void postInit(P6ModuleManager p6moduleManager) {
}
@Override
public void preDestroy(P6ModuleManager p6moduleManager) {
}
}
| []
| []
| []
| [] | [] | java | 0 | 0 | |
google/ads/googleads/v10/services/services/feed_service/client.py | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from collections import OrderedDict
import os
import re
from typing import Dict, Optional, Sequence, Tuple, Type, Union
import pkg_resources
from google.api_core import client_options as client_options_lib
from google.api_core import gapic_v1
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport import mtls # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.exceptions import MutualTLSChannelError # type: ignore
from google.oauth2 import service_account # type: ignore
try:
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]
except AttributeError: # pragma: NO COVER
OptionalRetry = Union[retries.Retry, object] # type: ignore
from google.ads.googleads.v10.services.types import feed_service
from google.rpc import status_pb2 # type: ignore
from .transports.base import FeedServiceTransport, DEFAULT_CLIENT_INFO
from .transports.grpc import FeedServiceGrpcTransport
class FeedServiceClientMeta(type):
"""Metaclass for the FeedService client.
This provides class-level methods for building and retrieving
support objects (e.g. transport) without polluting the client instance
objects.
"""
_transport_registry = (
OrderedDict()
) # type: Dict[str, Type[FeedServiceTransport]]
_transport_registry["grpc"] = FeedServiceGrpcTransport
def get_transport_class(
cls, label: str = None,
) -> Type[FeedServiceTransport]:
"""Returns an appropriate transport class.
Args:
label: The name of the desired transport. If none is
provided, then the first transport in the registry is used.
Returns:
The transport class to use.
"""
# If a specific transport is requested, return that one.
if label:
return cls._transport_registry[label]
# No transport is requested; return the default (that is, the first one
# in the dictionary).
return next(iter(cls._transport_registry.values()))
class FeedServiceClient(metaclass=FeedServiceClientMeta):
"""Service to manage feeds."""
@staticmethod
def _get_default_mtls_endpoint(api_endpoint):
"""Converts api endpoint to mTLS endpoint.
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
Args:
api_endpoint (Optional[str]): the api endpoint to convert.
Returns:
str: converted mTLS api endpoint.
"""
if not api_endpoint:
return api_endpoint
mtls_endpoint_re = re.compile(
r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
)
m = mtls_endpoint_re.match(api_endpoint)
name, mtls, sandbox, googledomain = m.groups()
if mtls or not googledomain:
return api_endpoint
if sandbox:
return api_endpoint.replace(
"sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
)
return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
DEFAULT_ENDPOINT = "googleads.googleapis.com"
DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore
DEFAULT_ENDPOINT
)
@classmethod
def from_service_account_info(cls, info: dict, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
info.
Args:
info (dict): The service account private key info.
args: Additional arguments to pass to the constructor.
kwargs: Additional arguments to pass to the constructor.
Returns:
FeedServiceClient: The constructed client.
"""
credentials = service_account.Credentials.from_service_account_info(
info
)
kwargs["credentials"] = credentials
return cls(*args, **kwargs)
@classmethod
def from_service_account_file(cls, filename: str, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
file.
Args:
filename (str): The path to the service account private key json
file.
args: Additional arguments to pass to the constructor.
kwargs: Additional arguments to pass to the constructor.
Returns:
FeedServiceClient: The constructed client.
"""
credentials = service_account.Credentials.from_service_account_file(
filename
)
kwargs["credentials"] = credentials
return cls(*args, **kwargs)
from_service_account_json = from_service_account_file
@property
def transport(self) -> FeedServiceTransport:
"""Returns the transport used by the client instance.
Returns:
FeedServiceTransport: The transport used by the client
instance.
"""
return self._transport
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
"""Releases underlying transport's resources.
.. warning::
ONLY use as a context manager if the transport is NOT shared
with other clients! Exiting the with block will CLOSE the transport
and may cause errors in other clients!
"""
self.transport.close()
@staticmethod
def feed_path(customer_id: str, feed_id: str,) -> str:
"""Returns a fully-qualified feed string."""
return "customers/{customer_id}/feeds/{feed_id}".format(
customer_id=customer_id, feed_id=feed_id,
)
@staticmethod
def parse_feed_path(path: str) -> Dict[str, str]:
"""Parses a feed path into its component segments."""
m = re.match(
r"^customers/(?P<customer_id>.+?)/feeds/(?P<feed_id>.+?)$", path
)
return m.groupdict() if m else {}
@staticmethod
def common_billing_account_path(billing_account: str,) -> str:
"""Returns a fully-qualified billing_account string."""
return "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@staticmethod
def parse_common_billing_account_path(path: str) -> Dict[str, str]:
"""Parse a billing_account path into its component segments."""
m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def common_folder_path(folder: str,) -> str:
"""Returns a fully-qualified folder string."""
return "folders/{folder}".format(folder=folder,)
@staticmethod
def parse_common_folder_path(path: str) -> Dict[str, str]:
"""Parse a folder path into its component segments."""
m = re.match(r"^folders/(?P<folder>.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def common_organization_path(organization: str,) -> str:
"""Returns a fully-qualified organization string."""
return "organizations/{organization}".format(organization=organization,)
@staticmethod
def parse_common_organization_path(path: str) -> Dict[str, str]:
"""Parse a organization path into its component segments."""
m = re.match(r"^organizations/(?P<organization>.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def common_project_path(project: str,) -> str:
"""Returns a fully-qualified project string."""
return "projects/{project}".format(project=project,)
@staticmethod
def parse_common_project_path(path: str) -> Dict[str, str]:
"""Parse a project path into its component segments."""
m = re.match(r"^projects/(?P<project>.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def common_location_path(project: str, location: str,) -> str:
"""Returns a fully-qualified location string."""
return "projects/{project}/locations/{location}".format(
project=project, location=location,
)
@staticmethod
def parse_common_location_path(path: str) -> Dict[str, str]:
"""Parse a location path into its component segments."""
m = re.match(
r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path
)
return m.groupdict() if m else {}
def __init__(
self,
*,
credentials: Optional[ga_credentials.Credentials] = None,
transport: Union[str, FeedServiceTransport, None] = None,
client_options: Optional[client_options_lib.ClientOptions] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
"""Instantiates the feed service client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
transport (Union[str, FeedServiceTransport]): The
transport to use. If set to None, a transport is chosen
automatically.
client_options (google.api_core.client_options.ClientOptions): Custom options for the
client. It won't take effect if a ``transport`` instance is provided.
(1) The ``api_endpoint`` property can be used to override the
default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
environment variable can also be used to override the endpoint:
"always" (always use the default mTLS endpoint), "never" (always
use the default regular endpoint) and "auto" (auto switch to the
default mTLS endpoint if client certificate is present, this is
the default value). However, the ``api_endpoint`` property takes
precedence if provided.
(2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
is "true", then the ``client_cert_source`` property can be used
to provide client certificate for mutual TLS transport. If
not provided, the default SSL client certificate will be used if
present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
set, no client certificate will be used.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
creation failed for any reason.
"""
if isinstance(client_options, dict):
client_options = client_options_lib.from_dict(client_options)
if client_options is None:
client_options = client_options_lib.ClientOptions()
# Create SSL credentials for mutual TLS if needed.
if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in (
"true",
"false",
):
raise ValueError(
"Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
)
use_client_cert = (
os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true"
)
client_cert_source_func = None
is_mtls = False
if use_client_cert:
if client_options.client_cert_source:
is_mtls = True
client_cert_source_func = client_options.client_cert_source
else:
is_mtls = mtls.has_default_client_cert_source()
if is_mtls:
client_cert_source_func = mtls.default_client_cert_source()
else:
client_cert_source_func = None
# Figure out which api endpoint to use.
if client_options.api_endpoint is not None:
api_endpoint = client_options.api_endpoint
else:
use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
if use_mtls_env == "never":
api_endpoint = self.DEFAULT_ENDPOINT
elif use_mtls_env == "always":
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
elif use_mtls_env == "auto":
api_endpoint = (
self.DEFAULT_MTLS_ENDPOINT
if is_mtls
else self.DEFAULT_ENDPOINT
)
else:
raise MutualTLSChannelError(
"Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted "
"values: never, auto, always"
)
# Save or instantiate the transport.
# Ordinarily, we provide the transport, but allowing a custom transport
# instance provides an extensibility point for unusual situations.
if isinstance(transport, FeedServiceTransport):
# transport is a FeedServiceTransport instance.
if credentials or client_options.credentials_file:
raise ValueError(
"When providing a transport instance, "
"provide its credentials directly."
)
if client_options.scopes:
raise ValueError(
"When providing a transport instance, provide its scopes "
"directly."
)
self._transport = transport
else:
Transport = type(self).get_transport_class(transport)
self._transport = Transport(
credentials=credentials,
credentials_file=client_options.credentials_file,
host=api_endpoint,
scopes=client_options.scopes,
client_cert_source_for_mtls=client_cert_source_func,
quota_project_id=client_options.quota_project_id,
client_info=client_info,
always_use_jwt_access=True,
)
def mutate_feeds(
self,
request: Union[feed_service.MutateFeedsRequest, dict] = None,
*,
customer_id: str = None,
operations: Sequence[feed_service.FeedOperation] = None,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> feed_service.MutateFeedsResponse:
r"""Creates, updates, or removes feeds. Operation statuses are
returned.
List of thrown errors: `AuthenticationError <>`__
`AuthorizationError <>`__ `CollectionSizeError <>`__
`DatabaseError <>`__ `DistinctError <>`__ `FeedError <>`__
`FieldError <>`__ `FieldMaskError <>`__ `HeaderError <>`__
`IdError <>`__ `InternalError <>`__ `ListOperationError <>`__
`MutateError <>`__ `NewResourceCreationError <>`__
`NotEmptyError <>`__ `NullError <>`__ `OperatorError <>`__
`QuotaError <>`__ `RangeError <>`__ `RequestError <>`__
`ResourceCountLimitExceededError <>`__ `SizeLimitError <>`__
`StringFormatError <>`__ `StringLengthError <>`__
Args:
request (Union[google.ads.googleads.v10.services.types.MutateFeedsRequest, dict]):
The request object. Request message for
[FeedService.MutateFeeds][google.ads.googleads.v10.services.FeedService.MutateFeeds].
customer_id (str):
Required. The ID of the customer
whose feeds are being modified.
This corresponds to the ``customer_id`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
operations (Sequence[google.ads.googleads.v10.services.types.FeedOperation]):
Required. The list of operations to
perform on individual feeds.
This corresponds to the ``operations`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.ads.googleads.v10.services.types.MutateFeedsResponse:
Response message for an feed mutate.
"""
# Create or coerce a protobuf request object.
# Quick check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([customer_id, operations])
if request is not None and has_flattened_params:
raise ValueError(
"If the `request` argument is set, then none of "
"the individual field arguments should be set."
)
# Minor optimization to avoid making a copy if the user passes
# in a feed_service.MutateFeedsRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, feed_service.MutateFeedsRequest):
request = feed_service.MutateFeedsRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if customer_id is not None:
request.customer_id = customer_id
if operations is not None:
request.operations = operations
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.mutate_feeds]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata(
(("customer_id", request.customer_id),)
),
)
# Send the request.
response = rpc(
request, retry=retry, timeout=timeout, metadata=metadata,
)
# Done; return the response.
return response
try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=pkg_resources.get_distribution("google-ads",).version,
)
except pkg_resources.DistributionNotFound:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
__all__ = ("FeedServiceClient",)
| []
| []
| [
"GOOGLE_API_USE_MTLS_ENDPOINT",
"GOOGLE_API_USE_CLIENT_CERTIFICATE"
]
| [] | ["GOOGLE_API_USE_MTLS_ENDPOINT", "GOOGLE_API_USE_CLIENT_CERTIFICATE"] | python | 2 | 0 | |
ansible/roles/dspace/molecule/default/tests/test_dspace.py | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_for_dspace_download(host):
f = host.file('/opt/dspace-6.3-release/dspace')
assert f.exists
assert f.is_directory
assert f.user == 'deploy'
assert f.group == 'deploy'
| []
| []
| [
"MOLECULE_INVENTORY_FILE"
]
| [] | ["MOLECULE_INVENTORY_FILE"] | python | 1 | 0 | |
DjangoProject1/pop_app.py | # -*- coding: utf-8 -*-
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoProject1.settings')
import django
django.setup()
## FAKE POP SCRIP
import random
from first_app.models import *
from faker import Faker
faker = Faker()
TOPICS = ['Search', 'Social', 'Marketplace', 'News', 'Games']
def add_topic():
t = Topic.objects.get_or_create(name=random.choice(TOPICS))[0]
t.save()
return t
def populate(N=5):
for entry in range(N):
top = add_topic()
fake_url = faker.url()
fake_name = faker.company()
webpage = WebPage.objects.get_or_create(topic=top, name=fake_name, url=fake_url)[0]
fake_date = faker.date()
record = AccessRecord.objects.get_or_create(webpage=webpage, date=fake_date)[0]
if __name__ == '__main__':
import sys
#print sys.argv
#for arg in sys.argv:
#print type(arg)
x, y = [int(i) for i in sys.argv[1:]]
populate(random.randint(x, y))
#for i in range(random.randint(x, y)):
#print i
| []
| []
| []
| [] | [] | python | 0 | 0 | |
vendor/github.com/elastic/beats/libbeat/outputs/elasticsearch/client_proxy_test.go | // Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
// This file contains tests to confirm that elasticsearch.Client uses proxy
// settings following the intended precedence.
package elasticsearch
import (
"bytes"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"os"
"os/exec"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/elastic/beats/libbeat/common/atomic"
"github.com/elastic/beats/libbeat/outputs/outil"
)
// These constants are inserted into client http request headers and confirmed
// by the server listeners.
const (
headerTestField = "X-Test-Value"
headerTestValue = "client_proxy_test test value"
)
// TestClientPing is a placeholder test that does nothing on a standard run,
// but starts up a client and sends a ping when the environment variable
// TEST_START_CLIENT is set to 1 as in execClient).
func TestClientPing(t *testing.T) {
// If this is the child process, start up the client, otherwise do nothing.
if os.Getenv("TEST_START_CLIENT") == "1" {
doClientPing(t)
return
}
}
// TestBaseline makes sure we can have a client process ping the server that
// we start, with no changes to the proxy settings. (This is really a
// meta-test for the helpers that create the servers / client.)
func TestBaseline(t *testing.T) {
servers, teardown := startServers(t)
defer teardown()
// Start a bare client with no proxy settings, pointed at the main server.
execClient(t, "TEST_SERVER_URL="+servers.serverURL)
// We expect one server request and 0 proxy requests
assert.Equal(t, 1, servers.serverRequestCount())
assert.Equal(t, 0, servers.proxyRequestCount())
}
// TestClientSettingsProxy confirms that we can control the proxy of a client
// by setting its ClientSettings.Proxy value on creation. (The child process
// uses the TEST_PROXY_URL environment variable to initialize the flag.)
func TestClientSettingsProxy(t *testing.T) {
servers, teardown := startServers(t)
defer teardown()
// Start a client with ClientSettings.Proxy set to the proxy listener.
execClient(t,
"TEST_SERVER_URL="+servers.serverURL,
"TEST_PROXY_URL="+servers.proxyURL)
// We expect one proxy request and 0 server requests
assert.Equal(t, 0, servers.serverRequestCount())
assert.Equal(t, 1, servers.proxyRequestCount())
}
// TestEnvironmentProxy confirms that we can control the proxy of a client by
// setting the HTTP_PROXY environment variable (see
// https://golang.org/pkg/net/http/#ProxyFromEnvironment).
func TestEnvironmentProxy(t *testing.T) {
servers, teardown := startServers(t)
defer teardown()
// Start a client with HTTP_PROXY set to the proxy listener.
// The server is set to a nonexistent URL because ProxyFromEnvironment
// always returns a nil proxy for local destination URLs.
execClient(t,
"TEST_SERVER_URL=http://fakeurl.fake.not-real",
"HTTP_PROXY="+servers.proxyURL)
// We expect one proxy request and 0 server requests
assert.Equal(t, 0, servers.serverRequestCount())
assert.Equal(t, 1, servers.proxyRequestCount())
}
// TestClientSettingsOverrideEnvironmentProxy confirms that when both
// ClientSettings.Proxy and HTTP_PROXY are set, ClientSettings takes precedence.
func TestClientSettingsOverrideEnvironmentProxy(t *testing.T) {
servers, teardown := startServers(t)
defer teardown()
// Start a client with ClientSettings.Proxy set to the proxy listener and
// HTTP_PROXY set to the server listener. We expect that the former will
// override the latter and thus we will only see a ping to the proxy.
// As above, the fake URL is needed to ensure ProxyFromEnvironment gives a
// non-nil result.
execClient(t,
"TEST_SERVER_URL=http://fakeurl.fake.not-real",
"TEST_PROXY_URL="+servers.proxyURL,
"HTTP_PROXY="+servers.serverURL)
// We expect one proxy request and 0 server requests
assert.Equal(t, 0, servers.serverRequestCount())
assert.Equal(t, 1, servers.proxyRequestCount())
}
// runClientTest executes the current test binary as a child process,
// running only the TestClientPing, and calling it with the environment variable
// TEST_START_CLIENT=1 (so the test can recognize that it is the child process),
// and any additional environment settings specified in env.
// This is helpful for testing proxy settings, since we need to have both a
// proxy / server-side listener and a client that communicates with the server
// using various proxy settings.
func execClient(t *testing.T, env ...string) {
// The child process always runs only the TestClientPing test, which pings
// the server at TEST_SERVER_URL and then terminates.
cmd := exec.Command(os.Args[0], "-test.run=TestClientPing")
cmd.Env = append(append(os.Environ(),
"TEST_START_CLIENT=1"),
env...)
cmdOutput := new(bytes.Buffer)
cmd.Stderr = cmdOutput
cmd.Stdout = cmdOutput
err := cmd.Run()
if err != nil {
t.Error("Error executing client:\n" + cmdOutput.String())
}
}
func doClientPing(t *testing.T) {
serverURL := os.Getenv("TEST_SERVER_URL")
require.NotEqual(t, serverURL, "")
proxy := os.Getenv("TEST_PROXY_URL")
clientSettings := ClientSettings{
URL: serverURL,
Index: outil.MakeSelector(outil.ConstSelectorExpr("test")),
Headers: map[string]string{headerTestField: headerTestValue},
}
if proxy != "" {
proxyURL, err := url.Parse(proxy)
require.NoError(t, err)
clientSettings.Proxy = proxyURL
}
client, err := NewClient(clientSettings, nil)
require.NoError(t, err)
// This ping won't succeed; we aren't testing end-to-end communication
// (which would require a lot more setup work), we just want to make sure
// the client is pointed at the right server or proxy.
client.Ping()
}
// serverState contains the state of the http listeners for proxy tests,
// including the endpoint URLs and the observed request count for each one.
type serverState struct {
serverURL string
proxyURL string
_serverRequestCount atomic.Int // Requests directly to the server
_proxyRequestCount atomic.Int // Requests via the proxy
}
// Convenience functions to unwrap the atomic primitives
func (s serverState) serverRequestCount() int {
return s._serverRequestCount.Load()
}
func (s serverState) proxyRequestCount() int {
return s._proxyRequestCount.Load()
}
// startServers starts endpoints representing a backend server and a proxy,
// and returns the corresponding serverState and a teardown function that
// should be called to shut them down at the end of the test.
func startServers(t *testing.T) (*serverState, func()) {
state := serverState{}
server := httptest.NewServer(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, headerTestValue, r.Header.Get(headerTestField))
fmt.Fprintln(w, "Hello, client")
state._serverRequestCount.Inc()
}))
proxy := httptest.NewServer(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, headerTestValue, r.Header.Get(headerTestField))
fmt.Fprintln(w, "Hello, client")
state._proxyRequestCount.Inc()
}))
state.serverURL = server.URL
state.proxyURL = proxy.URL
return &state, func() {
server.Close()
proxy.Close()
}
}
| [
"\"TEST_START_CLIENT\"",
"\"TEST_SERVER_URL\"",
"\"TEST_PROXY_URL\""
]
| []
| [
"TEST_PROXY_URL",
"TEST_START_CLIENT",
"TEST_SERVER_URL"
]
| [] | ["TEST_PROXY_URL", "TEST_START_CLIENT", "TEST_SERVER_URL"] | go | 3 | 0 | |
lib/python/fidasim/utils.py | #!/bin/sh
"exec" "$FIDASIM_DIR/deps/python" "$0" "$@"
# -*- coding: utf-8 -*-
#+#FIDASIM Utilities
#+This file contains useful FIDASIM utilities
#+***
from __future__ import print_function
import os
from os.path import dirname
import subprocess
import platform
import numpy as np
import copy
import h5py
import efit
from scipy.io import netcdf
from scipy.interpolate import interp1d, interp2d, NearestNDInterpolator
from scipy.spatial import Delaunay
import matplotlib.pyplot as plt
def get_fidasim_dir():
"""
#+#get_fidasim_dir
#+ Gets FIDASIM install directory
#+***
#+##Output Arguments
#+ **directory**: FIDASIM install directory.
#+##Example Usage
#+```python
#+>>> fida_dir = get_fidasim_dir()
#+```
"""
directory = dirname(dirname(dirname(dirname(os.path.abspath(__file__)))))
return directory
def get_version(fidasim_dir):
"""
#+#get_version
#+ Gets FIDASIM version number from git.
#+ Falls back to reading VERSION file when git is not available
#+***
#+##Input Arguments
#+ **fidasim_dir**: FIDASIM install directory
#+
#+##Output Arguments
#+ **version**: FIDAIM version number.
#+
#+##Example Usage
#+```python
#+>>> version = get_version(get_fidasim_dir())
#+```
"""
version = ''
alt = False
if platform.system() == 'Windows':
alt = True
else:
# Location of .git folder
git_dir = r'{}{}.git'.format(fidasim_dir, os.path.sep)
# git is installed if git_file is a file
proc = subprocess.Popen('command -v git', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
git_file = proc.communicate()[0].decode('utf-8')
git_file = git_file.replace('\n', '')
# Check that .git folder is present and git is installed
if os.path.isfile(git_file) and os.path.isdir(git_dir):
try:
version = subprocess.check_output(['git', '--git-dir={}'.format(git_dir), 'describe', '--tags', '--always', '--dirty'])
version = version.replace('\n', '')
except:
alt = True
else:
alt = True
# If above didn't work, read version file
if alt:
# Git 'version' filepath
ver_file = '{}{}VERSION'.format(fidasim_dir, os.path.sep)
if os.path.isfile(ver_file):
with open(ver_file) as f:
version = f.read()
return version
def aabb_intersect(rc, dr, r0, d0):
"""
#+#aabb_intersect
#+Calculates intersection length of a ray and an axis aligned bounding box (AABB)
#+***
#+##Input Arguments
#+ **rc**: Center of AABB
#+
#+ **dr**: [length, width, height] of AABB
#+
#+ **r0**: starting point of ray
#+
#+ **d0**: direction of ray
#+
#+##Output Arguments
#+ **intersect**: Intersection length of ray and AABB
#+
#+ **ri**: Optional, ray enterence point
#+
#+ **rf**: Optional, ray exit point
#+
#+##Example Usage
#+```python
#+>>> intersect, r_enter, r_exit = aabb_intersect([0,0,0], [1,1,1], [-1,0,0], [1,0,0])
#+>>> print(intersect)
#+ 1.0
#+>>> print(r_enter)
#+ -0.5 0.0 0.0
#+>>> print(r_exit)
#+ 0.5 0.0 0.0
#+```
"""
v0 = d0 / np.sqrt(np.sum(d0 ** 2.))
# There are 6 sides to a cube/grid
side_inter = np.zeros(6)
# Intersection points of ray with planes defined by grid
ipnts = np.zeros((3, 6))
# Find whether ray intersects each side
for i in range(6):
j = int(np.floor(i / 2))
ind = np.arange(3, dtype=int)
ind = ind[ind != j]
if np.abs(v0[j]) > 0.: # just v0[j] != 0 right?
# Intersection point with plane
ipnts[:, i] = r0 + v0 * (((rc[j] + (np.mod(i, 2) - 0.5) * dr[j]) - r0[j]) / v0[j])
# Check if point on plane is within grid side
if (np.abs(ipnts[ind[0], i] - rc[ind[0]]) <= 0.5 * dr[ind[0]]) and \
(np.abs(ipnts[ind[1], i] - rc[ind[1]]) <= 0.5 * dr[ind[1]]):
side_inter[i] = 1
intersect = 0.0
r_enter = copy.deepcopy(r0)
r_exit = copy.deepcopy(r0)
ind = np.arange(side_inter.size)
ind = ind[side_inter != 0]
nw = side_inter[ind].size
if nw >= 2:
#Find two unique intersection points
nunique = 0
for i in range(nw - 1):
if np.sum(ipnts[:, ind[0]] == ipnts[:, ind[i + 1]]) != 3:
ind = [ind[0], ind[i + 1]]
nunique = 2
break
if nunique == 2:
vi = ipnts[:, ind[1]] - ipnts[:, ind[0]]
vi = vi / np.sqrt(np.sum(vi ** 2.))
dot_prod = np.sum(v0 * vi)
if dot_prod > 0.0:
r_enter = ipnts[:, ind[0]]
r_exit = ipnts[:, ind[1]]
else:
r_enter = ipnts[:, ind[1]]
r_exit = ipnts[:, ind[0]]
# Calculate intersection length
intersect = np.sqrt(np.sum((r_exit - r_enter) ** 2.))
return intersect, r_enter, r_exit
def tb_zyx(alpha, beta, gamma):
"""
#+#tb_zyx
#+Calculates Tait-Bryan z-y'-x" active rotation matrix given rotation angles `alpha`,`beta`,`gamma` in radians
#+***
#+##Arguments
#+ **alpha**: rotation angle about z [radians]
#+
#+ **beta**: rotation angle about y' [radians]
#+
#+ **gamma**: rotation angle about x" [radians]
#+
#+##Return Value
#+ Rotation Matrix [prefida](|url|/sourcefile/prefida.pro.html)
#+
#+##Example Usage
#+```python
#+ >>> rot_mat = tb_zyx(np.pi/2, 0.0, np.pi/3)
#+```
"""
sa = np.sin(alpha)
ca = np.cos(alpha)
sb = np.sin(beta)
cb = np.cos(beta)
sg = np.sin(gamma)
cg = np.cos(gamma)
r = np.zeros((3, 3))
r[0, 0] = ca * cb
r[0, 1] = ca * sb * sg - cg * sa
r[0, 2] = sa * sg + ca * cg * sb
r[1, 0] = cb * sa
r[1, 1] = ca * cg + sa * sb * sg
r[1, 2] = cg * sa * sb - ca * sg
r[2, 0] = -sb
r[2, 1] = cb * sg
r[2, 2] = cb * cg
return r
def uvw_to_xyz(alpha, beta, gamma, uvw, origin=np.zeros(3)):
"""
#+#uvw_to_xyz
#+ Express non-rotated coordinate `uvw` in rotated `xyz` coordinates
#+***
#+##Arguments
#+ **alpha**: Rotation angle about z [radians]
#+
#+ **beta**: Rotation angle about y' [radians]
#+
#+ **gamma**: Rotation angle about x" [radians]
#+
#+ **uvw**: Point in rotated coordinate system, (3, n)
#+
#+##Keyword Arguments
#+ **origin**: Origin of rotated coordinate system in non-rotated (uvw) coordinates, (3)
#+
#+##Output Arguments
#+ **xyz**: 'uvw' in 'xyz' coordinates
#+
#+##Example Usage
#+```python
#+>>> xyz = uvw_to_xyz(np.pi/2., 0.0, np.pi/3., uvw, origin=[.1, .2, 0.])
#+```
"""
# Make np arrays
uvw = np.array(uvw, dtype=float)
origin = np.array(origin, dtype=float)
# Do checks as this code does not allow multiple points to be entered (yet)
if uvw.ndim == 2:
s = uvw.shape
if s[0] != 3:
raise ValueError('uvw must be (3, n), but it has shape {}'.format(uvw.shape))
n = s[1]
elif uvw.ndim == 1:
if uvw.size != 3:
raise ValueError('uvw must have length 3, but it has length {}'.format(uvw.size))
n = 1
else:
raise ValueError('uvw must be (3) or (3, n)')
if origin.ndim != 1:
raise ValueError('origin must be 1D, but it has shape {}'.format(origin.shape))
if origin.size != 3:
raise ValueError('origin must have length 3, but it has length {}'.format(origin.size))
# Shift origin
uvw_shifted = uvw - np.squeeze(np.tile(origin, (n, 1)).T)
# Get rotation matrix
r = tb_zyx(alpha, beta, gamma)
# Apply rotation matrix
xyz = np.dot(r.T, uvw_shifted)
return xyz
def xyz_to_uvw(alpha, beta, gamma, xyz, origin = np.zeros(3)):
"""
#+##`xyz_to_uvw(alpha, beta, gamma, xyz, origin=[0,0,0])`
#+Express rotated coordinate `xyz` in non-rotated `uvw` coordinates
#+###Arguments
#+ **alpha**: Rotation angle about z [radians]
#+
#+ **beta**: Rotation angle about y' [radians]
#+
#+ **gamma**: Rotation angle about x" [radians]
#+
#+ **xyz**: Point in rotated coordinate system
#+
#+###Keyword Arguments
#+ **origin**: Origin of rotated coordinate system in non-rotated (uvw) coordinates.
#+
#+###Example Usage
#+```python
#+>>> uvw = xyz_to_uvw(np.pi/2,0.0,np.pi/3,xyz)
#+```
"""
xyz = np.array(xyz)
# Do checks as this code does not allow multiple points to be entered (yet)
if xyz.ndim == 2:
s = xyz.shape
if s[0] != 3:
raise ValueError('xyz must be (3, n), but it has shape {}'.format(xyz.shape))
n = s[1]
elif xyz.ndim == 1:
if xyz.size != 3:
raise ValueError('xyz must have length 3, but it has length {}'.format(xyz.size))
n = 1
else:
raise ValueError('xyz must be (3) or (3, n)')
if origin.ndim != 1:
raise ValueError('origin must be 1D, but it has shape {}'.format(origin.shape))
if origin.size != 3:
raise ValueError('origin must have length 3, but it has length {}'.format(origin.size))
R = tb_zyx(alpha,beta,gamma)
uvw = np.dot(R, xyz)
return uvw + np.squeeze(np.tile(origin, (n, 1)).T)
def line_basis(r0, v0):
"""
#+#line_basis
#+Calculates basis from a line with +x in the direction of line
#+***
#+##Arguments
#+ **r0**: Starting point of line [cm]
#+
#+ **v0**: Direction of line
#+
#+##Example Usage
#+```python
#+>>> basis = line_basis([0,0,0],[0,-1,0])
#+>>> x = np.dot(basis,np.array([1,1,0])) ;Transforms a point in line-space ([1,1,0]) to real space
#+>>> x
#+ [1, -1, 0]
#+```
"""
r0 = np.array(r0)
v0 = np.array(v0)
rf = r0 + v0
dis = np.sqrt(np.sum(v0**2))
beta = np.arcsin((r0[2] - rf[2])/dis)
alpha = np.arctan2((rf[1] - r0[1]),(rf[0]-r0[0]))
R = tb_zyx(alpha,beta,0.0)
return R
def rz_grid(rmin, rmax, nr, zmin, zmax, nz, phimin=0.0, phimax=0.0, nphi=1):
"""
#+#rz_grid
#+Creates interpolation grid
#+***
#+##Arguments
#+ **rmin**: Minimum radius [cm]
#+
#+ **rmax**: Maximum radius [cm]
#+
#+ **nr**: Number of radii
#+
#+ **zmin**: Minimum Z value [cm]
#+
#+ **zmax**: Maximum Z value [cm]
#+
#+ **nz**: Number of Z values
#+
#+ **phimin**: Minimum Phi value [rad]
#+
#+ **phimax**: Maximum Phi value [rad]
#+
#+ **nphi**: Number of Phi values
#+
#+##Return Value
#+Interpolation grid dictionary
#+
#+##Example Usage
#+```python
#+>>> grid = rz_grid(0,200.0,200,-100,100,200,phimin=4*np.pi/3,phimax=5*np.pi/3,nphi=5)
#+```
"""
dr = (rmax - rmin) / nr
dz = (zmax - zmin) / nz
dphi = (phimax - phimin) / nphi
r = rmin + dr * np.arange(nr, dtype=np.float64)
z = zmin + dz * np.arange(nz, dtype=np.float64)
phi = phimin + dphi * np.arange(nphi, dtype=np.float64)
r2d = np.tile(r, (nz, 1)).T
z2d = np.tile(z, (nr, 1))
grid = {'r2d': r2d,
'z2d': z2d,
'r': r,
'z': z,
'phi': phi,
'nr': nr,
'nz': nz,
'nphi': nphi}
return grid
def colored(text, color): #, on_color=None, attrs=None):
"""
#+#colored
#+ Return text string formatting for color in terminal
#+***
#+##Input Arguments
#+ **text**: String to be colored
#+
#+ **color**: Desired color of string. Red, green, yellow, blue, magenta, cyan, or white.
#+
#+##Output Arguments
#+ **text**: Text formated to have "color" in terminal.
#+##Example Usage
#+```python
#+>>> text = colored("Text to be red", 'red')
#+>>> print(text)
#+```
"""
# Copyright (c) 2008-2011 Volvox Development Team
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# Author: Konstantin Lepa <[email protected]>
COLORS = dict(list(zip(['grey',
'red',
'green',
'yellow',
'blue',
'magenta',
'cyan',
'white',],
list(range(30, 38)))))
RESET = '\033[0m'
if os.getenv('ANSI_COLORS_DISABLED') is None:
fmt_str = '\033[%dm%s'
text = fmt_str % (COLORS[color], text)
text += RESET
return text
def info(string):
"""
#+#info
#+Print a informational message
#+***
#+##Arguments
#+ **str**: message
#+
#+##Example Usage
#+```python
#+>>> info("This is an informative message")
#+```
"""
print(colored('INFO: ' + string, 'cyan'))
def warn(string):
"""
#+#warn
#+Print a warning message
#+***
#+##Arguments
#+ **string**: message
#+
#+##Example Usage
#+```python
#+>>> warn("This may be a problem")
#+```
"""
print(colored('WARNING: ' + string, 'magenta'))
def error(string, halt=False):
"""
#+#error
#+Print a error message
#+***
#+##Arguments
#+ **string**: message
#+
#+##Keyword Arguments
#+ **halt**: Halt program execution
#+
#+##Example Usage
#+```python
#+>>> error("Error message")
#+```
"""
print(colored('ERROR: {}'.format(string), 'red'))
if halt:
raise Exception()
def success(string):
"""
#+#success
#+Print a success message
#+***
#+##Arguments
#+ **string**: message
#+
#+##Example Usage
#+```python
#+>>> success("Yay!!!")
#+```
"""
print(colored('SUCCESS: ' + string, 'green'))
def beam_grid(nbi, rstart,
nx=None, ny=None, nz=None, dv=8.0,
length=100.0, width=80.0, height=80.0):
"""
#+#beam_grid
#+ Calculates settings for a grid that aligns with the neutral beam.
#+***
#+##Arguments
#+ **nbi**: [Neutral beam geometry structure](|url|/page/03_technical/01_prefida_inputs.html#neutral-beam-geometry-structure)
#+
#+ **rstart**: Radial start position of beam grid [cm]
#+
#+##Keyword Arguments
#+ **dV**: Cell volume [\(cm^3\)]: Defaults to 8.0
#+
#+ **nx**: Number of cells in length: Default determined by `dV`
#+
#+ **ny**: Number of cells in width: Default determined by `dV`
#+
#+ **nz**: Number of cells in height: Default determined by `dV`
#+
#+ **length**: Length of grid along beam sightline. [cm]: Defaults to 100 cm
#+
#+ **width**: Width of grid [cm]: Defaults to 100 cm
#+
#+ **height**: Height of grid [cm]: Defaults 80 cm
#+
#+##Return Value
#+ Structure containing beam grid settings suitable for the Namelist File
#+
#+##Example Usage
#+```python
#+>>> grid = beam_grid(nbi,200.0,nx=100,ny=50,nz=50,length=100,width=50,height=50)
#+```
"""
if width < nbi['widy']:
warn("Grid width is smaller then the source width")
print("width: {}".format(width))
print("source width: {}".format(nbi['widy']))
if height < nbi['widz']:
warn("Grid height is smaller then the source height")
print("height: {}".format(height))
print("source height: {}".format(nbi['widz']))
dv3 = dv ** (1. / 3.)
if nx is None:
nx = round(length / dv3)
if ny is None:
ny = round(width / dv3)
if nz is None:
nz = round(height / dv3)
xmin = 0.
xmax = length
ymin = -width / 2.
ymax = width / 2.
zmin = -height / 2.
zmax = height / 2.
src = nbi['src']
axis = nbi['axis'] / np.sqrt(np.sum(nbi['axis'] ** 2))
pos = src + 100. * axis
if np.sqrt(src[0] ** 2 + src[1] ** 2) < rstart:
error("Source radius cannot be less then rstart", halt=True)
dis = np.sqrt(np.sum((src - pos) ** 2.0))
beta = np.arcsin((src[2] - pos[2]) / dis)
alpha = np.arctan2((pos[1] - src[1]), (pos[0] - src[0]))
gamma = 0.
a = axis[0] ** 2 + axis[1] ** 2
b = 2. * (src[0] * axis[0] + src[1] * axis[1])
c = src[0] ** 2 + src[1] ** 2 - rstart ** 2
t = (-b - np.sqrt(b ** 2 - 4. * a * c)) / (2. * a)
origin = src + t * axis
beam_grid = {'nx': nx,
'ny': ny,
'nz': nz,
'xmin': xmin,
'xmax': xmax,
'ymin': ymin,
'ymax': ymax,
'zmin': zmin,
'zmax': zmax,
'alpha': alpha,
'beta': beta,
'gamma': gamma,
'origin': origin}
return beam_grid
def write_data(h5_obj, dic, desc=dict(), units=dict(), name=''):
"""
#+#write_data
#+ Write h5 datasets with attributes 'description' and 'units'
#+***
#+##Arguments
#+ **h5_obj**: An h5 file or group object from h5py
#+
#+ **dic**: Dict of data to save as h5 datasets
#+
#+##Keyword Arguments
#+ **name**: Name/description of dic for clarity in raising errors
#+
#+ **desc**: Dict with same keys as dic describing each item in dic
#+
#+ **units**: Dict with same keys as dic providing units of data in dic, doesn't have to be all keys of dic.
#+
#+##Example Usage
#+```python
#+>>> write_data(h5_obj, dic, desc, units)
#+```
"""
for key in dic:
if isinstance(dic[key], dict):
h5_grp = h5_obj.create_group(key)
write_data(h5_grp, dic[key])
continue
# Transpose data to match expected by Fortran and historically provided by IDL
if isinstance(dic[key], np.ndarray):
if dic[key].ndim >= 2:
dic[key] = dic[key].T
# Make strings of fixed length as required by Fortran.
# See http://docs.h5py.org/en/latest/strings.html#fixed-length-ascii
if isinstance(dic[key], str):
dic[key] = np.string_(dic[key])
# Create dataset
ds = h5_obj.create_dataset(key, data = dic[key])
# Add descrption attribute
if key in desc:
ds.attrs['description'] = desc[key]
# Add units attribute (if present)
if key in units:
ds.attrs['units'] = units[key]
def read_geqdsk(filename, grid, poloidal=False):
"""
#+#read_geqdsk
#+Reads an EFIT GEQDSK file
#+***
#+##Arguments
#+ **filename**: GEQDSK file
#+
#+ **grid**: Interpolation grid
#+
#+##Keyword Arguments
#+ **poloidal**: Return rho_p (sqrt(normalized poloidal flux)) instead of rho (sqrt(normalized toroidal flux))
#+
#+##Return Value
#+Electronmagnetic fields structure, rho, btipsign
#+
#+##Example Usage
#+```python
#+>>> fields, rho, btipsign = read_geqdsk("./g133223.00200",grid)
#+```
"""
dims = grid['r2d'].shape
r_pts = grid['r2d'].flatten()/100
z_pts = grid['z2d'].flatten()/100
g = efit.readg(filename)
btipsign = np.sign(g["current"]*g["bcentr"])
fpol = g["fpol"]
psiaxis = g["ssimag"]
psiwall = g["ssibry"]
r = g["r"]
z = g["z"]
psi_arr = np.linspace(psiaxis, psiwall, len(fpol))
fpol_itp = interp1d(psi_arr, fpol, 'cubic', fill_value=fpol[-1],bounds_error=False)
psirz_itp = interp2d(r, z, g["psirz"], 'cubic')
if poloidal:
rhogrid = np.array([psirz_itp(rr,zz) for (rr,zz) in zip(r_pts,z_pts)]).reshape(dims)
rhogrid = np.sqrt((rhogrid - g["ssimag"])/(g["ssibry"] - g["ssimag"]))
else:
rhogrid=efit.rho_rz(g,r_pts,z_pts,norm=True).reshape(dims)
br = np.array([psirz_itp(rr,zz,dy=1)/rr for (rr,zz) in zip(r_pts,z_pts)]).reshape(dims)
bz = np.array([-psirz_itp(rr,zz,dx=1)/rr for (rr,zz) in zip(r_pts,z_pts)]).reshape(dims)
bt = np.array([fpol_itp(psirz_itp(rr,zz))/rr for (rr,zz) in zip(r_pts,z_pts)]).reshape(dims)
er = br*0
ez = bz*0
et = bt*0
mask = np.ones(dims,dtype=np.int32)
equil = {"time":0.0,"data_source":os.path.abspath(filename), "mask":mask,
"br":br,"bt":bt,"bz":bz,"er":er,"et":et,"ez":ez}
return equil, rhogrid, btipsign
def read_ncdf(filename, vars=None):
'''
#+#read_ncdf
#+Reads a flat NetCDF file
#+***
#+##Arguments
#+ **filename**: NetCDF file
#+
#+##Keyword Arguments
#+ **vars**: List of variables to read
#+
#+##Return Value
#+Structure containing NetCDF variables
#+
#+##Example Usage
#+```python
#+>>> a = read_ncdf("./123324H01_fi_1.cdf")
#+```
'''
d = dict()
d['err'] = 1
if os.path.isfile(filename):
d['err'] = 0
f = netcdf.netcdf_file(filename, 'r', mmap=False)
variables = f.variables
if vars != None:
for k in vars:
# need to check case sensitibity
if k in variables.keys():
v = variables[k]
if tuple() == v.shape:
d[k] = v.getValue()
else:
d[k] = v[:]
else:
for k,v in variables.items():
if tuple() == v.shape:
d[k] = v.getValue()
else:
d[k] = v[:]
f.close()
else:
error('FILE DOES NOT EXIST: '+filename)
return d
def extract_transp_plasma(filename, intime, grid, rhogrid,
dn0out=None, scrapeoff=None,rho_scrapeoff=0.1):
'''
#+#extract_transp_plasma
#+Extracts `plasma` structure from a TRANSP run
#+***
#+##Arguments
#+ **filename**: TRANSP output file e.g. [TRANSP_RUNID].CDF
#+
#+ **intime**: Time of interest [s]
#+
#+ **grid**: Interpolation grid
#+
#+ **rhogrid**: sqrt(normalized torodial flux) mapped onto the interpolation grid
#+
#+##Keyword Arguments
#+ **dn0out**: Wall Neutral density value `dn0out` variable in transp namelist
#+
#+ **scrapeoff**: scrapeoff decay length
#+
#+ **rho_scrapeoff**: scrapeoff length, default = 0.1
#+
#+##Example Usage
#+```python
#+>>> plasma = extract_transp_plasma("./142332H01.CDF", 1.2, grid, rho)
#+```
'''
var_list = ["X","TRFLX","TFLUX","TIME","NE","NH","ND","NT","NIMP","TE","TI","ZEFFI","OMEGA","DN0WD","XZIMP"]
zz = read_ncdf(filename, vars=var_list)
t = zz['TIME']
idx = np.argmin(abs(t-intime))
time = t[idx].astype('float64')
print(' * Selecting profiles at :', time, ' s') #pick the closest timeslice to TOI
impurity_charge = np.max(zz["XZIMP"]).astype("int16")
transp_ne = zz['NE'][idx,:] #cm^-3
transp_nimp = zz['NIMP'][idx,:] #cm^-3
transp_nn = zz['DN0WD'][idx,:] #cm^-3
if 'NH' in zz:
transp_nh = zz['NH'][idx,:] #cm^-3
else:
transp_nh = 0*transp_ne
if 'ND' in zz:
transp_nd = zz['ND'][idx,:] #cm^-3
else:
transp_nd = 0*transp_ne
if 'NT' in zz:
transp_nt = zz['NT'][idx,:] #cm^-3
else:
transp_nt = 0*transp_ne
transp_te = zz['TE'][idx,:]*1.e-3 # kev
transp_ti = zz['TI'][idx,:]*1.e-3 # kev
transp_zeff = zz['ZEFFI'][idx,:]
rho_cb = np.sqrt(zz['TRFLX'][idx,:]/zz['TFLUX'][idx])
# center each rho b/c toroidal flux is at cell boundary
rho = 0.e0*rho_cb
rho[0] = 0.5*rho_cb[0]
for i in range(len(rho_cb)-1):
rho[i+1] = rho_cb[i+1] - 0.5*(rho_cb[i+1] - rho_cb[i])
if 'OMEGA' not in zz.keys():
error('OMEGA not found in TRANSP file. Assuming no plasma rotation')
transp_omega=0.0*transp_te
else:
transp_omega = zz['OMEGA'][idx,:] # rad/s
if dn0out == None:
dn0out = transp_nn[-1]
if scrapeoff == None:
scrapeoff = 0.0
if scrapeoff > 0.0:
drho = abs(rho[-1] - rho[-2])
rho_sc = rho[-1] + drho*(range(np.ceil(rho_scrapeoff/drho)) + 1)
sc = np.exp(-(rho_sc - rho[-1])/scrapeoff)
transp_ne = np.append(transp_ne,transp_ne[-1]*sc)
transp_nimp = np.append(transp_nimp,transp_nimp[-1]*sc)
transp_nh = np.append(transp_nh,transp_nh[-1]*sc)
transp_nd = np.append(transp_nd,transp_nd[-1]*sc)
transp_nt = np.append(transp_nt,transp_nt[-1]*sc)
transp_te = np.append(transp_te,transp_te[-1]*sc)
transp_ti = np.append(transp_ti,transp_ti[-1]*sc)
transp_nn = np.append(transp_nn,0*sc + dn0out)
transp_zeff = np.append(transp_zeff, (transp_zeff[-1]-1)*sc + 1)
transp_omega = np.append(transp_omega,transp_omega[-1]*sc)
rho = np.append(rho, rho_sc)
profiles = {"rho":rho,
"dene":np.where(transp_ne > 0, transp_ne, 0.0),
"denimp":np.where(transp_nimp > 0, transp_nimp, 0.0),
"denn":np.where(transp_nn > 0, transp_nn, 0.0),
"te":np.where(transp_te > 0, transp_te, 0.0),
"ti":np.where(transp_ti > 0, transp_ti, 0.0),
"zeff":np.where(transp_zeff > 1.0, transp_zeff, 1.0),
"omega":transp_omega}
if 'NH' in zz:
profiles['denh'] = np.where(transp_nh > 0, transp_nh, 0.0)
if 'ND' in zz:
profiles['dend'] = np.where(transp_nd > 0, transp_nd, 0.0)
if 'NT' in zz:
profiles['dent'] = np.where(transp_nt > 0, transp_nt, 0.0)
# Interpolate onto r-z grid
dims = rhogrid.shape
f_dene = interp1d(rho,transp_ne,fill_value='extrapolate')
dene = f_dene(rhogrid)
dene = np.where(dene > 0.0, dene, 0.0).astype('float64')
f_denimp = interp1d(rho,transp_nimp,fill_value='extrapolate')
denimp = f_denimp(rhogrid)
denimp = np.where(denimp > 0.0, denimp, 0.0).astype('float64')
f_denh = interp1d(rho,transp_nh,fill_value='extrapolate')
denh = f_denh(rhogrid)
denh = np.where(denh > 0.0, denh, 0.0).astype('float64')
f_dend = interp1d(rho,transp_nd,fill_value='extrapolate')
dend = f_dend(rhogrid)
dend = np.where(dend > 0.0, dend, 0.0).astype('float64')
f_dent = interp1d(rho,transp_nt,fill_value='extrapolate')
dent = f_dent(rhogrid)
dent = np.where(dent > 0.0, dent, 0.0).astype('float64')
f_denn = interp1d(rho,np.log(transp_nn),fill_value=np.nan,bounds_error=False)
log_denn = f_denn(rhogrid)
denn = np.where(~np.isnan(log_denn), np.exp(log_denn), 0.0).astype('float64')
f_te = interp1d(rho,transp_te,fill_value='extrapolate')
te = f_te(rhogrid)
te = np.where(te > 0, te, 0.0).astype('float64')
f_ti = interp1d(rho,transp_ti,fill_value='extrapolate')
ti = f_ti(rhogrid)
ti = np.where(ti > 0, ti, 0.0).astype('float64')
f_zeff = interp1d(rho,transp_zeff, fill_value=1.0, bounds_error=False)
zeff = f_zeff(rhogrid)
zeff = np.where(zeff > 1, zeff, 1.0).astype('float64')
f_omega = interp1d(rho,transp_omega,fill_value='extrapolate')
vt = grid['r2d']*f_omega(rhogrid).astype('float64')
vr = np.zeros(dims,dtype='float64')
vz = np.zeros(dims,dtype='float64')
max_rho = max(abs(rho))
mask = np.zeros(dims,dtype='int')
w = np.where(rhogrid <= max_rho) #where we have profiles
mask[w] = 1
deni = np.concatenate((denh.reshape(1,dims[0],dims[1]),
dend.reshape(1,dims[0],dims[1]),
dent.reshape(1,dims[0],dims[1])),axis=0)
ai = np.array([1.007276466879e0, 2.013553212745e0,3.01550071632e0])
w_ai = [a in zz for a in ['NH','ND','NT']]
# SAVE IN PROFILES STRUCTURE
plasma={"data_source":os.path.abspath(filename),"time":time,"impurity_charge":int(impurity_charge),
"nthermal":int(np.sum(w_ai)), "species_mass":ai[w_ai], "deni":deni[w_ai,:,:],"profiles":profiles,
"mask":mask,"dene":dene,"denimp":denimp,"denn":denn,"te":te,"ti":ti,
"vr":vr,"vt":vt,"vz":vz,"zeff":zeff}
return plasma
def read_nubeam(filename, grid, e_range=(), p_range=(), btipsign=-1, species=1):
"""
#+#read_nubeam
#+Reads NUBEAM fast-ion distribution function
#+***
#+##Arguments
#+ **filename**: NUBEAM guiding center fast-ion distribution function file e.g. 159245H01_fi_1.cdf
#+
#+ **grid**: Interpolation grid
#+
#+##Keyword Arguments
#+ **btipsign**: Sign of the dot product of the magnetic field and plasma current
#+
#+ **e_range**: Energy range to consider
#+
#+ **p_range**: Pitch range to consider
#+
#+ **species**: Fast-ion species number. Defaults to 1
#+
#+##Return Value
#+Distribution structure
#+
#+##Example Usage
#+```python
#+>>> dist = read_nubeam("./159245H02_fi_1.cdf",grid,btipsign=-1)
#+```
"""
species_var = "SPECIES_{}".format(species)
sstr = read_ncdf(filename,vars=[species_var])[species_var].tostring().decode('UTF-8')
print("Species: "+sstr)
var = read_ncdf(filename, vars=["TIME","R2D","Z2D","E_"+sstr,"A_"+sstr,"F_"+sstr,"RSURF","ZSURF","BMVOL"])
ngrid = len(var["R2D"])
try:
time = var["TIME"][0]
except:
time = var["TIME"]
r2d = var["R2D"]
z2d = var["Z2D"]
rsurf = var["RSURF"].T
zsurf = var["ZSURF"].T
bmvol = var["BMVOL"]
pitch = var["A_"+sstr]
energy = var["E_"+sstr]*1e-3
fbm = var["F_"+sstr].T*1e3
fbm = np.where(fbm > 0.0, 0.5*fbm, 0.0) #0.5 to convert to pitch instead of solid angle d_omega/4pi
if btipsign < 0:
fbm = fbm[:,::-1,:] #reverse pitch elements
if not e_range:
e_range = (np.min(energy), np.max(energy))
if not p_range:
p_range = (np.min(pitch), np.max(pitch))
# Trim distribution according to e/p_range
we = np.logical_and(energy >= e_range[0], energy <= e_range[1])
wp = np.logical_and(pitch >= p_range[0], pitch <= p_range[1])
energy = energy[we]
nenergy = len(energy)
pitch = pitch[wp]
npitch = len(pitch)
fbm = fbm[we,:,:]
fbm = fbm[:,wp,:]
dE = np.abs(energy[1] - energy[0])
dp = np.abs(pitch[1] - pitch[0])
emin, emax = np.maximum(np.min(energy) - 0.5*dE, 0.0), np.max(energy) + 0.5*dE
pmin, pmax = np.maximum(np.min(pitch) - 0.5*dp, -1.0), np.minimum(np.max(pitch)+0.5*dp, 1.0)
print('Energy min/max: ', emin, emax)
print('Pitch min/max: ',pmin, pmax)
nr = grid["nr"]
nz = grid["nz"]
r = grid["r"]
z = grid["z"]
rgrid = grid["r2d"]
zgrid = grid["z2d"]
dr = np.abs(r[1] - r[0])
dz = np.abs(z[1] - z[0])
fdens = np.sum(fbm,axis=(0,1))*dE*dp
ntot = np.sum(fdens*bmvol)
print('Ntotal in phase space: ',ntot)
tri = Delaunay(np.vstack((r2d,z2d)).T) # Triangulation for barycentric interpolation
pts = np.array([xx for xx in zip(r2d,z2d)])
itp = NearestNDInterpolator(pts,np.arange(ngrid)) #to find indices outside simplices
points = np.array([xx for xx in zip(rgrid.flatten(),zgrid.flatten())])
t = tri.find_simplex(points)
denf = np.zeros((nr,nz))
fbm_grid = np.zeros((nenergy,npitch,nr,nz))
for (ind,tt) in enumerate(t):
i,j = np.unravel_index(ind,(nr,nz))
if tt == -1:
ii = int(itp(r[i],z[j]))
denf[i,j] = fdens[ii]
fbm_grid[:,:,i,j] = fbm[:,:,ii]
else:
b = tri.transform[tt,:2].dot(np.transpose(points[ind] - tri.transform[tt,2]))
s = tri.simplices[tt,:]
#perform barycentric linear interpolation
denf[i,j] = b[0]*fdens[s[0]] + b[1]*fdens[s[1]] + (1 - np.sum(b))*fdens[s[2]]
fbm_grid[:,:,i,j] = b[0]*fbm[:,:,s[0]] + b[1]*fbm[:,:,s[1]] + (1-np.sum(b))*fbm[:,:,s[2]]
denf[denf < 0] = 0
# Correct for points outside of seperatrix
rmaxis = np.mean(rsurf[:,0])
zmaxis = np.mean(zsurf[:,0])
r_sep = rsurf[:,-1]
z_sep = zsurf[:,-1]
#plt.triplot(r2d,z2d,tri.simplices.copy())
#plt.plot(r2d,z2d,'o')
#plt.plot(r_sep,z_sep)
#plt.show()
x_bdry = r_sep - rmaxis
y_bdry = z_sep - zmaxis
r_bdry = np.sqrt(x_bdry**2 + y_bdry**2)
theta_bdry = np.arctan2(y_bdry,x_bdry)
theta_bdry = np.where(theta_bdry < 0.0, theta_bdry + 2*np.pi, theta_bdry) #[0,2pi]
w = np.argsort(theta_bdry)
theta_bdry = theta_bdry[w]
r_bdry = r_bdry[w]
theta_bdry, w = np.unique(theta_bdry,return_index=True)
r_bdry = r_bdry[w]
itp = interp1d(theta_bdry,r_bdry,'cubic',fill_value='extrapolate')
x_pts = grid["r2d"] - rmaxis
y_pts = grid["z2d"] - zmaxis
r_pts = np.sqrt(x_pts**2 + y_pts**2)
theta_pts = np.arctan2(y_pts,x_pts)
theta_pts = np.where(theta_pts < 0.0, theta_pts + 2*np.pi, theta_pts) #[0,2pi]
r_bdry_itp = itp(theta_pts)
w = r_pts >= r_bdry_itp + 2
denf[w] = 0.0
fbm_grid[:,:,w] = 0.0
# enforce correct normalization
ntot_denf = 2*np.pi*dr*dz*np.sum(r*np.sum(denf,axis=1))
denf = denf*(ntot/ntot_denf)
ntot_fbm = (2*np.pi*dE*dp*dr*dz)*np.sum(r*np.sum(fbm_grid,axis=(0,1,3)))
fbm_grid = fbm_grid*(ntot/ntot_denf)
fbm_dict={"type":1,"time":time,"nenergy":nenergy,"energy":energy,"npitch":npitch,
"pitch":pitch,"f":fbm_grid,"denf":denf,"data_source":os.path.abspath(filename)}
return fbm_dict
def nubeam_geometry(nubeam, angle=0.0, verbose=False):
"""
#+#nubeam_geometry
#+Calculates the FIDASIM beam geometry from the beam geometry variables in the TRANSP/NUBEAM namelist
#+***
#+##Arguments
#+ **NUBEAM**: Dictionary containing the following
#+
#+ **NUBEAM["NAME"]**: Ion source name
#+
#+ **NUBEAM["NBSHAP"]**: Ion source shape 1=rectangular, 2=circular
#+
#+ **NUBEAM["FOCLZ"]**: Vertical focal length [cm]
#+
#+ **NUBEAM["FOCLR"]**: Horizontal focal length [cm]
#+
#+ **NUBEAM["DIVZ"]**: Vertical divergence [rad]
#+
#+ **NUBEAM["DIVR"]**: Horizontal divergence [rad]
#+
#+ **NUBEAM["BMWIDZ"]**: Ion source half height [cm]
#+
#+ **NUBEAM["BMWIDR"]**: Ion source half width [cm]
#+
#+ **NUBEAM["RTCENA"]**: Radius of tangency point [cm]
#+
#+ **NUBEAM["XLBTNA"]**: Distance from center of beam source grid to tangency point [cm]
#+
#+ **NUBEAM["XBZETA"]**: Torodial angle [deg] Positive angles defined to be in the counter-clockwise direction
#+
#+ **NUBEAM["XYBSCA"]**: Elevation above/below vacuum vessel midplane of center of beam source grid [cm]
#+
#+ **NUBEAM["NLJCCW"]**: Orientation of Ip. 1 for True/Counter-clockwise current, 0 or -1 for False/Clock-wise current
#+
#+ **NUBEAM["NLCO"]**: 1 for Co-beam, 0 or -1 for Counter-beam
#+
#+ **NUBEAM["NBAPSHA"]**: Vector of aperture shapes 1=rectangular, 2=circular
#+
#+ **NUBEAM["XLBAPA"]**: Vector of distances from center of beam source grid to the aperture plane [cm]
#+
#+ **NUBEAM["XYBAPA"]**: Vector of elevation above/below vacuum vessel midplane of beam centerline at aperture [cm]
#+
#+ **NUBEAM["RAPEDGA"]**: Vector of aperture half-widths [cm]
#+
#+ **NUBEAM["XZPEDGA"]**: Vector of aperture half-heights [cm]
#+
#+ **NUBEAM["XRAPOFFA"]**: Vector of horizontal (y) offsets relative to the +x aligned beam centerline [cm]
#+
#+ **NUBEAM["XZAPOFFA"]**: Vector of vertical (z) offsets relative to the +x aligned beam centerline [cm]
#+
#+##Keyword Arguments
#+ **angle**: Angle to add to XBZETA to rotate the beams into correct coordinates [deg]
#+
#+ **verbose**: Print out positions
#+
#+##Return Value
#+ Neutral beam structure
#+
#+##Example Usage
#+```python
#+>>> nbi = nubeam_geometry(nubeam)
#+```
"""
if nubeam["NLCO"] == 0:
nubeam["NLCO"] = -1
if "NLJCCW" in nubeam:
if nubeam["NLJCCW"] == 0:
nubeam["NLJCCW"] = -1
else:
warn("Current orientation not specified. Assuming Counter-clockwise.")
nubeam["NLJCCW"] = 1
phi_s = (nubeam["XBZETA"] + angle)*np.pi/180.0
zs = nubeam["XYBSCA"]
za = nubeam["XYBAPA"][0]
alpha = np.arcsin((zs-za)/nubeam["XLBAPA"][0])
pdst = nubeam["XLBTNA"]*np.cos(alpha)
rs = np.sqrt(nubeam["RTCENA"]**2 + pdst**2)
dat = nubeam["XLBTNA"] - nubeam["XLBAPA"][0]
pdat = dat*np.cos(alpha)
ra = np.sqrt(nubeam["RTCENA"]**2 + pdat**2.0)
beta_s = np.arccos(nubeam["RTCENA"]/rs)
beta_a = np.arccos(nubeam["RTCENA"]/ra)
phi_a = phi_s + nubeam["NLJCCW"]*nubeam["NLCO"]*(beta_s-beta_a)
src = np.array([rs*np.cos(phi_s), rs*np.sin(phi_s),zs])
aper_src = np.array([ra*np.cos(phi_a), ra*np.sin(phi_a),za])
axis = (aper_src - src)
axis = axis/np.sqrt(np.sum(axis**2))
pos = src + axis*nubeam["XLBTNA"]
if verbose:
print('Source position: ',src)
print('1st Aperture position: ',aper_src)
print('Tangency position: ', pos)
nbi = {"data_source":"TRANSP/NUBEAM namelist","name":nubeam["NAME"],
"shape":nubeam["NBSHAP"],"src":src,"axis":axis,
"focy":nubeam["FOCLR"],"focz":nubeam["FOCLZ"],
"divy":np.repeat(nubeam["DIVR"],3),
"divz":np.repeat(nubeam["DIVZ"],3),
"widy":nubeam["BMWIDR"], "widz":nubeam["BMWIDZ"],
"naperture":len(nubeam["NBAPSHA"]),"ashape":nubeam["NBAPSHA"],
"awidy":nubeam["RAPEDGA"],"awidz":nubeam["XZPEDGA"],
"aoffy":nubeam["XRAPOFFA"],"aoffz":nubeam["XZAPOFFA"],
"adist":nubeam["XLBAPA"] }
return nbi
| []
| []
| [
"ANSI_COLORS_DISABLED"
]
| [] | ["ANSI_COLORS_DISABLED"] | python | 1 | 0 | |
v3/cpu/cpu_linux_test.go | package cpu
import (
"os"
"os/exec"
"strconv"
"strings"
"testing"
)
func TestTimesEmpty(t *testing.T) {
orig := os.Getenv("HOST_PROC")
os.Setenv("HOST_PROC", "testdata/linux/times_empty")
_, err := Times(true)
if err != nil {
t.Error("Times(true) failed")
}
_, err = Times(false)
if err != nil {
t.Error("Times(false) failed")
}
os.Setenv("HOST_PROC", orig)
}
func TestCPUparseStatLine_424(t *testing.T) {
orig := os.Getenv("HOST_PROC")
os.Setenv("HOST_PROC", "testdata/linux/424/proc")
{
l, err := Times(true)
if err != nil || len(l) == 0 {
t.Error("Times(true) failed")
}
t.Logf("Times(true): %#v", l)
}
{
l, err := Times(false)
if err != nil || len(l) == 0 {
t.Error("Times(false) failed")
}
t.Logf("Times(false): %#v", l)
}
os.Setenv("HOST_PROC", orig)
}
func TestCPUCountsAgainstLscpu(t *testing.T) {
lscpu, err := exec.LookPath("lscpu")
if err != nil {
t.Skip("no lscpu to compare with")
}
cmd := exec.Command(lscpu)
cmd.Env = []string{"LC_ALL=C"}
out, err := cmd.Output()
if err != nil {
t.Errorf("error executing lscpu: %v", err)
}
var threadsPerCore, coresPerSocket, sockets int
lines := strings.Split(string(out), "\n")
for _, line := range lines {
fields := strings.Split(line, ":")
if len(fields) < 2 {
continue
}
switch fields[0] {
case "Thread(s) per core":
threadsPerCore, _ = strconv.Atoi(strings.TrimSpace(fields[1]))
case "Core(s) per socket":
coresPerSocket, _ = strconv.Atoi(strings.TrimSpace(fields[1]))
case "Socket(s)":
sockets, _ = strconv.Atoi(strings.TrimSpace(fields[1]))
}
}
if threadsPerCore == 0 || coresPerSocket == 0 || sockets == 0 {
t.Errorf("missing info from lscpu: threadsPerCore=%d coresPerSocket=%d sockets=%d", threadsPerCore, coresPerSocket, sockets)
}
expectedPhysical := coresPerSocket * sockets
expectedLogical := expectedPhysical * threadsPerCore
physical, err := Counts(false)
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
logical, err := Counts(true)
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
if expectedPhysical != physical {
t.Errorf("expected %v, got %v", expectedPhysical, physical)
}
if expectedLogical != logical {
t.Errorf("expected %v, got %v", expectedLogical, logical)
}
}
func TestCPUCountsLogicalAndroid_1037(t *testing.T) { // https://github.com/lribeiro/gopsutil/issues/1037
orig := os.Getenv("HOST_PROC")
os.Setenv("HOST_PROC", "testdata/linux/1037/proc")
defer os.Setenv("HOST_PROC", orig)
count, err := Counts(true)
if err != nil {
t.Errorf("error %v", err)
}
expected := 8
if count != expected {
t.Errorf("expected %v, got %v", expected, count)
}
}
| [
"\"HOST_PROC\"",
"\"HOST_PROC\"",
"\"HOST_PROC\""
]
| []
| [
"HOST_PROC"
]
| [] | ["HOST_PROC"] | go | 1 | 0 | |
internal/app/controller/client_test.go | // Copyright 2018 Clivern. All rights reserved.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
package controller
import (
"fmt"
"github.com/clivern/beaver/internal/app/api"
"github.com/gin-gonic/gin"
"github.com/nbio/st"
"github.com/spf13/viper"
"net/http"
"net/http/httptest"
"os"
"strconv"
"strings"
"testing"
"time"
)
// init setup stuff
func init() {
basePath := fmt.Sprintf("%s/src/github.com/clivern/beaver", os.Getenv("GOPATH"))
configFile := fmt.Sprintf("%s/%s", basePath, "config.test.yml")
viper.SetConfigFile(configFile)
err := viper.ReadInConfig()
if err != nil {
panic(fmt.Sprintf(
"Error while loading config file [%s]: %s",
configFile,
err.Error(),
))
}
os.Setenv("BeaverBasePath", fmt.Sprintf("%s/", basePath))
os.Setenv("PORT", strconv.Itoa(viper.GetInt("app.port")))
}
// TestGetClient1 test case
func TestGetClient1(t *testing.T) {
// Clean Before
clientID := "c6da288b-9024-4578-a3c2-d23795fa1067"
clientAPI := api.Client{}
st.Expect(t, clientAPI.Init(), true)
clientAPI.DeleteClientByID(clientID)
router := gin.Default()
router.GET("/api/client/:id", GetClientByID)
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", fmt.Sprintf("/api/client/%s", clientID), nil)
router.ServeHTTP(w, req)
st.Expect(t, http.StatusNotFound, w.Code)
}
// TestGetClient2 test case
func TestGetClient2(t *testing.T) {
clientAPI := api.Client{}
st.Expect(t, clientAPI.Init(), true)
// Clean Before
createdAt := time.Now().Unix()
updatedAt := time.Now().Unix()
clientResult := api.ClientResult{
ID: "c6da288b-9024-4578-a3c2-d23795fa1067",
Token: "eyJhbGciOiJIUzI1NiIs",
Channels: []string{"chat1"},
CreatedAt: createdAt,
UpdatedAt: updatedAt,
}
incomingClientResult := api.ClientResult{}
clientAPI.DeleteClientByID(clientResult.ID)
clientAPI.CreateClient(clientResult)
router := gin.Default()
router.GET("/api/client/:id", GetClientByID)
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", fmt.Sprintf("/api/client/%s", clientResult.ID), nil)
router.ServeHTTP(w, req)
incomingClientResult.LoadFromJSON([]byte(w.Body.String()))
st.Expect(t, http.StatusOK, w.Code)
st.Expect(t, incomingClientResult.ID, clientResult.ID)
st.Expect(t, incomingClientResult.Token, clientResult.Token)
st.Expect(t, incomingClientResult.Channels, clientResult.Channels)
st.Expect(t, incomingClientResult.CreatedAt, clientResult.CreatedAt)
st.Expect(t, incomingClientResult.UpdatedAt, clientResult.UpdatedAt)
// Clean After
clientAPI.DeleteClientByID(clientResult.ID)
}
// TestDeleteClient1 test case
func TestDeleteClient1(t *testing.T) {
// Clean Before
clientID := "c6da288b-9024-4578-a3c2-d23795fa1067"
clientAPI := api.Client{}
st.Expect(t, clientAPI.Init(), true)
clientAPI.DeleteClientByID(clientID)
router := gin.Default()
router.DELETE("/api/client/:id", DeleteClientByID)
w := httptest.NewRecorder()
req, _ := http.NewRequest("DELETE", fmt.Sprintf("/api/client/%s", clientID), nil)
router.ServeHTTP(w, req)
st.Expect(t, http.StatusNotFound, w.Code)
}
// TestDeleteClient2 test case
func TestDeleteClient2(t *testing.T) {
clientAPI := api.Client{}
st.Expect(t, clientAPI.Init(), true)
// Clean Before
createdAt := time.Now().Unix()
updatedAt := time.Now().Unix()
clientResult := api.ClientResult{
ID: "c6da288b-9024-4578-a3c2-d23795fa1067",
Token: "eyJhbGciOiJIUzI1NiIs",
Channels: []string{"chat1"},
CreatedAt: createdAt,
UpdatedAt: updatedAt,
}
clientAPI.DeleteClientByID(clientResult.ID)
clientAPI.CreateClient(clientResult)
router := gin.Default()
router.DELETE("/api/client/:id", DeleteClientByID)
w := httptest.NewRecorder()
req, _ := http.NewRequest("DELETE", fmt.Sprintf("/api/client/%s", clientResult.ID), nil)
router.ServeHTTP(w, req)
st.Expect(t, http.StatusNoContent, w.Code)
// Clean After
clientAPI.DeleteClientByID(clientResult.ID)
}
// TestCreateClient1 test case
func TestCreateClient1(t *testing.T) {
router := gin.Default()
router.POST("/api/client", CreateClient)
w := httptest.NewRecorder()
req, _ := http.NewRequest("POST", "/api/client", strings.NewReader(`{}`))
router.ServeHTTP(w, req)
st.Expect(t, http.StatusCreated, w.Code)
}
// TestCreateClient2 test case
func TestCreateClient2(t *testing.T) {
router := gin.Default()
router.POST("/api/client", CreateClient)
w := httptest.NewRecorder()
req, _ := http.NewRequest("POST", "/api/client", strings.NewReader(`{"channels":["chat"}`))
router.ServeHTTP(w, req)
st.Expect(t, http.StatusBadRequest, w.Code)
}
| [
"\"GOPATH\""
]
| []
| [
"GOPATH"
]
| [] | ["GOPATH"] | go | 1 | 0 | |
command.go | package rebirth
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/stdcopy"
"github.com/goccy/rebirth/internal/errors"
"github.com/mitchellh/go-ps"
"golang.org/x/xerrors"
)
type Command struct {
cmd *exec.Cmd
args []string
}
func NewCommand(args ...string) *Command {
cmd := exec.Command(args[0], args[1:]...)
cmd.Env = os.Environ()
return &Command{
cmd: cmd,
args: args,
}
}
func (c *Command) SetDir(dir string) {
c.cmd.Dir = dir
}
func (c *Command) AddEnv(env []string) {
c.cmd.Env = append(c.cmd.Env, env...)
}
func (c *Command) String() string {
return fmt.Sprintf("%s; %s",
strings.Join(c.cmd.Env, " "),
strings.Join(c.args, " "),
)
}
func (c *Command) Stop() error {
if c == nil {
return nil
}
if c.cmd == nil {
return nil
}
if c.cmd.Process == nil {
return nil
}
pid := c.cmd.Process.Pid
process, err := ps.FindProcess(pid)
if err != nil {
return xerrors.Errorf("failed to find process by pid(%d): %w", pid, err)
}
if process != nil {
if err := c.cmd.Process.Kill(); err != nil {
return xerrors.Errorf("failed to kill process: %w", err)
}
}
return nil
}
func (c *Command) Run() error {
if err := c.run(); err != nil {
return xerrors.Errorf("failed to run: %w", err)
}
return nil
}
func (c *Command) RunAsync() {
go func() {
if err := c.run(); err != nil {
fmt.Println(err)
}
}()
}
func (c *Command) run() error {
stdout, err := c.cmd.StdoutPipe()
if err != nil {
return xerrors.Errorf("failed to pipe stdout: %w", err)
}
stderr, err := c.cmd.StderrPipe()
if err != nil {
return xerrors.Errorf("failed to pipe stderr: %w", err)
}
if err := c.cmd.Start(); err != nil {
return xerrors.Errorf("failed to run build command: %w", err)
}
go io.Copy(os.Stdout, stdout)
go io.Copy(os.Stderr, stderr)
if err := c.cmd.Wait(); err != nil {
return err
}
return nil
}
type DockerCommand struct {
container string
cmd []string
execID string
}
func NewDockerCommand(container string, cmd ...string) *DockerCommand {
return &DockerCommand{
container: container,
cmd: cmd,
}
}
/*
type DockerProcess struct {
Pid int
}
func (c *DockerCommand) Process() *DockerProcess {
if c.execID == "" {
return nil
}
cli, err := client.NewEnvClient()
if err != nil {
return nil
}
resp, err := cli.ContainerExecInspect(context.Background(), c.execID)
if err != nil {
return nil
}
// resp.Pid is number on host
return &DockerProcess{
Pid: resp.Pid,
}
}
*/
func (c *DockerCommand) Output() ([]byte, error) {
stdout := new(bytes.Buffer)
stderr := new(bytes.Buffer)
if err := c.run(context.Background(), func(reader *bufio.Reader) error {
if _, err := stdcopy.StdCopy(stdout, stderr, reader); err != nil {
return xerrors.Errorf("failed to copy stdout/stderr: %w", err)
}
return nil
}); err != nil {
return nil, xerrors.Errorf("failed to run: %w", err)
}
return []byte(c.chomp(stdout.String())), nil
}
func (c *DockerCommand) Run() error {
if err := c.run(context.Background(), func(reader *bufio.Reader) error {
if _, err := stdcopy.StdCopy(os.Stdout, os.Stderr, reader); err != nil {
return xerrors.Errorf("failed to copy stdout/stderr: %w", err)
}
return nil
}); err != nil {
return xerrors.Errorf("failed to run: %w", err)
}
return nil
}
func (c *DockerCommand) run(ctx context.Context, ioCallback func(reader *bufio.Reader) error) error {
cli, err := client.NewEnvClient()
if err != nil {
return xerrors.Errorf("failed to create docker client: %w", err)
}
cfg := types.ExecConfig{
AttachStdout: true,
AttachStderr: true,
Cmd: c.cmd,
}
execResp, err := cli.ContainerExecCreate(ctx, c.container, cfg)
if err != nil {
return xerrors.Errorf("failed to ContainerExecCreate: %w", err)
}
execID := execResp.ID
c.execID = execID
attachResp, err := cli.ContainerExecAttach(ctx, execID, cfg)
if err != nil {
return xerrors.Errorf("failed to ContainerExecAttach: %w", err)
}
defer attachResp.Close()
if err := ioCallback(attachResp.Reader); err != nil {
return xerrors.Errorf("failed to i/o callback: %w", err)
}
return nil
}
func (c *DockerCommand) chomp(src string) string {
return strings.TrimRight(src, "\n")
}
type GoCommand struct {
cmd []string
container string
isCrossBuild bool
extEnv []string
dir string
}
func NewGoCommand() *GoCommand {
return &GoCommand{
extEnv: []string{},
}
}
func (c *GoCommand) EnableCrossBuild(container string) {
c.container = container
c.isCrossBuild = true
}
func (c *GoCommand) AddEnv(env []string) {
c.extEnv = append(c.extEnv, env...)
}
func (c *GoCommand) SetDir(dir string) {
c.dir = dir
}
func (c *GoCommand) RunInGoContext(args ...string) error {
cmd := NewCommand(args...)
env := []string{}
if c.dir == "" {
symlinkPath, err := c.getOrCreateSymlink()
if err != nil {
return xerrors.Errorf("failed to get symlink path: %w", err)
}
gopath, err := c.gopath()
if err != nil {
return xerrors.Errorf("failed to get GOPATH: %w", err)
}
env = append(env, fmt.Sprintf("GOPATH=%s", gopath))
env = append(env, fmt.Sprintf("PATH=%s:%s/bin", os.Getenv("PATH"), gopath))
cmd.SetDir(symlinkPath)
} else {
cmd.SetDir(c.dir)
}
cmd.AddEnv(env)
if err := cmd.Run(); err != nil {
return xerrors.Errorf("failed to command: %w", err)
}
return nil
}
func (c *GoCommand) Build(args ...string) error {
cmd := []string{"go", "build"}
cmd = append(cmd, c.linkerFlags()...)
cmd = append(cmd, args...)
if err := c.run(cmd...); err != nil {
return xerrors.Errorf("failed to run: %w", err)
}
return nil
}
func (c *GoCommand) Run(args ...string) error {
if !c.isCrossBuild {
cmd := []string{"go", "run"}
cmd = append(cmd, c.linkerFlags()...)
cmd = append(cmd, args...)
if err := c.run(cmd...); err != nil {
return xerrors.Errorf("failed to run: %w", err)
}
return nil
}
if len(args) == 0 {
return xerrors.New("go run: no go files listed")
}
if filepath.Ext(args[0]) != ".go" {
return xerrors.New("go run: no go files listed")
}
tmpfile, err := ioutil.TempFile(configDir, "script")
if err != nil {
return xerrors.Errorf("failed to create temporary file: %w", err)
}
defer os.Remove(tmpfile.Name())
gofile := args[0]
var goargs []string
if len(args) > 1 {
goargs = args[1:]
}
cmd := []string{"go", "build", "-o", tmpfile.Name()}
cmd = append(cmd, c.linkerFlags()...)
cmd = append(cmd, gofile)
if err := c.run(cmd...); err != nil {
return xerrors.Errorf("failed to run: %w", err)
}
dockerCmd := []string{tmpfile.Name()}
dockerCmd = append(dockerCmd, goargs...)
if err := NewDockerCommand(c.container, dockerCmd...).Run(); err != nil {
return xerrors.Errorf("failed to run on docker container: %w", err)
}
return nil
}
func (c *GoCommand) Test(args ...string) error {
if !c.isCrossBuild {
cmd := []string{"go", "test"}
cmd = append(cmd, c.linkerFlags()...)
cmd = append(cmd, args...)
if err := c.run(cmd...); err != nil {
return xerrors.Errorf("failed to run: %w", err)
}
return nil
}
cmd := []string{"go", "test", "-c", "-o", filepath.Join(configDir, "app.test")}
cmd = append(cmd, c.linkerFlags()...)
cmd = append(cmd, args...)
if err := c.run(cmd...); err != nil {
return xerrors.Errorf("failed to run: %w", err)
}
dockerCmd := []string{filepath.Join(configDir, "app.test")}
testArgs := []string{}
for idx, arg := range args {
switch arg {
case "-v":
testArgs = append(testArgs, "-test.v")
case "-run":
testArgs = append(testArgs, "-test.run", args[idx+1])
}
}
dockerCmd = append(dockerCmd, testArgs...)
if err := NewDockerCommand(c.container, dockerCmd...).Run(); err != nil {
return xerrors.Errorf("failed to run on docker container: %w", err)
}
return nil
}
func (c *GoCommand) linkerFlags() []string {
if c.isCrossBuild {
return []string{
"--ldflags",
`-linkmode external -extldflags "-static"`,
}
}
return []string{}
}
func (c *GoCommand) run(args ...string) error {
env, err := c.buildEnv()
if err != nil {
return xerrors.Errorf("failed to get build env: %w", err)
}
cmd := NewCommand(args...)
if c.dir == "" {
symlinkPath, err := c.getOrCreateSymlink()
if err != nil {
return xerrors.Errorf("failed to get symlink path: %w", err)
}
gopath, err := c.gopath()
if err != nil {
return xerrors.Errorf("failed to get GOPATH: %w", err)
}
env = append(env, fmt.Sprintf("GOPATH=%s", gopath))
env = append(env, fmt.Sprintf("PATH=%s:%s/bin", os.Getenv("PATH"), gopath))
cmd.SetDir(symlinkPath)
} else {
cmd.SetDir(c.dir)
}
cmd.AddEnv(env)
if err := cmd.Run(); err != nil {
return xerrors.Errorf("failed to command: %w", err)
}
return nil
}
func (c *GoCommand) buildEnv() ([]string, error) {
goos, err := c.buildGOOS()
if err != nil {
return nil, xerrors.Errorf("failed to get GOOS for build: %w", err)
}
goarch, err := c.buildGOARCH()
if err != nil {
return nil, xerrors.Errorf("failed to get GOARCH for build: %w", err)
}
env := []string{
"CGO_ENABLED=1",
fmt.Sprintf("GOOS=%s", goos),
fmt.Sprintf("GOARCH=%s", goarch),
}
env = append(env, c.extEnv...)
if c.isCrossBuild && runtime.GOOS == "darwin" {
if _, err := exec.LookPath("x86_64-linux-musl-cc"); err != nil {
return nil, errors.ErrCrossCompiler
}
env = append(env, []string{
"CC=x86_64-linux-musl-cc",
"CXX=x86_64-linux-musl-c++",
}...)
}
return env, nil
}
func (c *GoCommand) buildGOOS() (string, error) {
if c.isCrossBuild {
goos, err := NewDockerCommand(c.container, "go", "env", "GOOS").Output()
if err != nil {
return "", xerrors.Errorf("failed to get GOOS env on container: %w", err)
}
return string(goos), nil
}
return runtime.GOOS, nil
}
func (c *GoCommand) buildGOARCH() (string, error) {
if c.isCrossBuild {
goarch, err := NewDockerCommand(c.container, "go", "env", "GOARCH").Output()
if err != nil {
return "", xerrors.Errorf("failed to get GOARCH env on container: %w", err)
}
return string(goarch), nil
}
return runtime.GOARCH, nil
}
func (c *GoCommand) gopath() (string, error) {
path, err := filepath.Abs(configDir)
if err != nil {
return "", xerrors.Errorf("failed to get absolute path from %s: %w", configDir, err)
}
return path, nil
}
func (c *GoCommand) srcPath() (string, error) {
gopath, err := c.gopath()
if err != nil {
return "", xerrors.Errorf("failed to get GOPATH: %w", err)
}
return filepath.Join(gopath, "src"), nil
}
func (c *GoCommand) getOrCreateSymlink() (string, error) {
modpath, err := c.getModulePath()
if err != nil {
return "", xerrors.Errorf("failed to get module path: %w", err)
}
srcPath, err := c.srcPath()
if err != nil {
return "", xerrors.Errorf("failed to get $GOPATH/src path: %w", err)
}
if err := os.MkdirAll(filepath.Join(srcPath, filepath.Dir(modpath)), 0755); err != nil {
return "", xerrors.Errorf("failed to create path to %s: %w", modpath, err)
}
symlinkPath := filepath.Join(srcPath, modpath)
if _, err := os.Stat(symlinkPath); err != nil {
oldpath, err := filepath.Abs(".")
if err != nil {
return "", xerrors.Errorf("failed to get abolute path from current dir: %w", err)
}
newpath, err := filepath.Abs(symlinkPath)
if err != nil {
return "", xerrors.Errorf("failed to get abolute path from %s: %w", symlinkPath, err)
}
if err := os.Symlink(oldpath, newpath); err != nil {
return "", xerrors.Errorf("failed to create symlink from %s to %s: %w", oldpath, newpath, err)
}
}
return symlinkPath, nil
}
func (c *GoCommand) getModulePath() (string, error) {
if existsGoMod() {
file, _ := ioutil.ReadFile(goModPath)
return parseModulePath(file), nil
}
curpath, err := filepath.Abs(".")
if err != nil {
return "", xerrors.Errorf("failed to get abolute path from current dir: %w", err)
}
return filepath.Base(curpath), nil
}
| [
"\"PATH\"",
"\"PATH\""
]
| []
| [
"PATH"
]
| [] | ["PATH"] | go | 1 | 0 | |
cmd/update-main.go | /*
* MinIO Cloud Storage, (C) 2015, 2016, 2017 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd
import (
"crypto"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/fatih/color"
"github.com/inconshreveable/go-update"
isatty "github.com/mattn/go-isatty"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
_ "github.com/minio/sha256-simd" // Needed for sha256 hash verifier.
)
// Check for new software updates.
var updateCmd = cli.Command{
Name: "update",
Usage: "update mc to latest release",
Action: mainUpdate,
Flags: []cli.Flag{
cli.BoolFlag{
Name: "json",
Usage: "enable JSON formatted output",
},
},
CustomHelpTemplate: `Name:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}}{{if .VisibleFlags}} [FLAGS]{{end}}
{{if .VisibleFlags}}
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}{{end}}
EXIT STATUS:
0 - you are already running the most recent version
1 - new update was applied successfully
-1 - error in getting update information
EXAMPLES:
1. Check and update mc:
{{.Prompt}} {{.HelpName}}
`,
}
const (
mcReleaseTagTimeLayout = "2006-01-02T15-04-05Z"
mcOSARCH = runtime.GOOS + "-" + runtime.GOARCH
mcReleaseURL = "https://dl.min.io/client/mc/release/" + mcOSARCH + "/"
)
var (
// Newer official download info URLs appear earlier below.
mcReleaseInfoURLs = []string{
mcReleaseURL + "mc.sha256sum",
mcReleaseURL + "mc.shasum",
}
// For windows our files have .exe additionally.
mcReleaseWindowsInfoURLs = []string{
mcReleaseURL + "mc.exe.sha256sum",
mcReleaseURL + "mc.exe.shasum",
}
)
// mcVersionToReleaseTime - parses a standard official release
// mc --version string.
//
// An official binary's version string is the release time formatted
// with RFC3339 (in UTC) - e.g. `2017-09-29T19:16:56Z`
func mcVersionToReleaseTime(version string) (releaseTime time.Time, err *probe.Error) {
var e error
releaseTime, e = time.Parse(time.RFC3339, version)
return releaseTime, probe.NewError(e)
}
// releaseTimeToReleaseTag - converts a time to a string formatted as
// an official mc release tag.
//
// An official mc release tag looks like:
// `RELEASE.2017-09-29T19-16-56Z`
func releaseTimeToReleaseTag(releaseTime time.Time) string {
return "RELEASE." + releaseTime.Format(mcReleaseTagTimeLayout)
}
// releaseTagToReleaseTime - reverse of `releaseTimeToReleaseTag()`
func releaseTagToReleaseTime(releaseTag string) (releaseTime time.Time, err *probe.Error) {
tagTimePart := strings.TrimPrefix(releaseTag, "RELEASE.")
if tagTimePart == releaseTag {
return releaseTime, probe.NewError(fmt.Errorf("%s is not a valid release tag", releaseTag))
}
var e error
releaseTime, e = time.Parse(mcReleaseTagTimeLayout, tagTimePart)
return releaseTime, probe.NewError(e)
}
// getModTime - get the file modification time of `path`
func getModTime(path string) (t time.Time, err *probe.Error) {
var e error
path, e = filepath.EvalSymlinks(path)
if e != nil {
return t, probe.NewError(fmt.Errorf("Unable to get absolute path of %s. %w", path, e))
}
// Version is mc non-standard, we will use mc binary's
// ModTime as release time.
var fi os.FileInfo
fi, e = os.Stat(path)
if e != nil {
return t, probe.NewError(fmt.Errorf("Unable to get ModTime of %s. %w", path, e))
}
// Return the ModTime
return fi.ModTime().UTC(), nil
}
// GetCurrentReleaseTime - returns this process's release time. If it
// is official mc --version, parsed version is returned else mc
// binary's mod time is returned.
func GetCurrentReleaseTime() (releaseTime time.Time, err *probe.Error) {
if releaseTime, err = mcVersionToReleaseTime(Version); err == nil {
return releaseTime, nil
}
// Looks like version is mc non-standard, we use mc
// binary's ModTime as release time:
path, e := os.Executable()
if e != nil {
return releaseTime, probe.NewError(e)
}
return getModTime(path)
}
// IsDocker - returns if the environment mc is running in docker or
// not. The check is a simple file existence check.
//
// https://github.com/moby/moby/blob/master/daemon/initlayer/setup_unix.go#L25
//
// "/.dockerenv": "file",
//
func IsDocker() bool {
_, e := os.Stat("/.dockerenv")
if os.IsNotExist(e) {
return false
}
return e == nil
}
// IsDCOS returns true if mc is running in DCOS.
func IsDCOS() bool {
// http://mesos.apache.org/documentation/latest/docker-containerizer/
// Mesos docker containerizer sets this value
return os.Getenv("MESOS_CONTAINER_NAME") != ""
}
// IsKubernetes returns true if MinIO is running in kubernetes.
func IsKubernetes() bool {
// Kubernetes env used to validate if we are
// indeed running inside a kubernetes pod
// is KUBERNETES_SERVICE_HOST but in future
// we might need to enhance this.
return os.Getenv("KUBERNETES_SERVICE_HOST") != ""
}
// IsSourceBuild - returns if this binary is a non-official build from
// source code.
func IsSourceBuild() bool {
_, err := mcVersionToReleaseTime(Version)
return err != nil
}
// DO NOT CHANGE USER AGENT STYLE.
// The style should be
//
// mc (<OS>; <ARCH>[; dcos][; kubernetes][; docker][; source]) mc/<VERSION> mc/<RELEASE-TAG> mc/<COMMIT-ID>
//
// Any change here should be discussed by opening an issue at
// https://github.com/minio/mc/issues.
func getUserAgent() string {
userAgentParts := []string{}
// Helper function to concisely append a pair of strings to a
// the user-agent slice.
uaAppend := func(p, q string) {
userAgentParts = append(userAgentParts, p, q)
}
uaAppend("os (", runtime.GOOS)
uaAppend("; ", runtime.GOARCH)
if IsDCOS() {
uaAppend("; ", "dcos")
}
if IsKubernetes() {
uaAppend("; ", "kubernetes")
}
if IsDocker() {
uaAppend("; ", "docker")
}
if IsSourceBuild() {
uaAppend("; ", "source")
}
uaAppend(") os/", Version)
uaAppend(" os/", ReleaseTag)
uaAppend(" os/", CommitID)
return strings.Join(userAgentParts, "")
}
func downloadReleaseURL(releaseChecksumURL string, timeout time.Duration) (content string, err *probe.Error) {
req, e := http.NewRequest("GET", releaseChecksumURL, nil)
if e != nil {
return content, probe.NewError(e)
}
req.Header.Set("User-Agent", getUserAgent())
client := &http.Client{
Timeout: timeout,
Transport: &http.Transport{
// need to close connection after usage.
DisableKeepAlives: true,
},
}
resp, e := client.Do(req)
if e != nil {
return content, probe.NewError(e)
}
if resp == nil {
return content, probe.NewError(fmt.Errorf("No response from server to download URL %s", releaseChecksumURL))
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return content, probe.NewError(fmt.Errorf("Error downloading URL %s. Response: %v", releaseChecksumURL, resp.Status))
}
contentBytes, e := ioutil.ReadAll(resp.Body)
if e != nil {
return content, probe.NewError(fmt.Errorf("Error reading response. %s", err))
}
return string(contentBytes), nil
}
// DownloadReleaseData - downloads release data from mc official server.
func DownloadReleaseData(timeout time.Duration) (data string, err *probe.Error) {
releaseURLs := mcReleaseInfoURLs
if runtime.GOOS == "windows" {
releaseURLs = mcReleaseWindowsInfoURLs
}
return func() (data string, err *probe.Error) {
for _, url := range releaseURLs {
data, err = downloadReleaseURL(url, timeout)
if err == nil {
return data, nil
}
}
return data, err.Trace(releaseURLs...)
}()
}
// parseReleaseData - parses release info file content fetched from
// official mc download server.
//
// The expected format is a single line with two words like:
//
// fbe246edbd382902db9a4035df7dce8cb441357d mc.RELEASE.2016-10-07T01-16-39Z
//
// The second word must be `mc.` appended to a standard release tag.
func parseReleaseData(data string) (sha256Hex string, releaseTime time.Time, err *probe.Error) {
fields := strings.Fields(data)
if len(fields) != 2 {
return sha256Hex, releaseTime, probe.NewError(fmt.Errorf("Unknown release data `%s`", data))
}
sha256Hex = fields[0]
releaseInfo := fields[1]
fields = strings.SplitN(releaseInfo, ".", 2)
if len(fields) != 2 {
return sha256Hex, releaseTime, probe.NewError(fmt.Errorf("Unknown release information `%s`", releaseInfo))
}
if fields[0] != "mc" {
return sha256Hex, releaseTime, probe.NewError(fmt.Errorf("Unknown release `%s`", releaseInfo))
}
releaseTime, err = releaseTagToReleaseTime(fields[1])
if err != nil {
return sha256Hex, releaseTime, err.Trace(fields...)
}
return sha256Hex, releaseTime, nil
}
func getLatestReleaseTime(timeout time.Duration) (sha256Hex string, releaseTime time.Time, err *probe.Error) {
data, err := DownloadReleaseData(timeout)
if err != nil {
return sha256Hex, releaseTime, err.Trace()
}
return parseReleaseData(data)
}
func getDownloadURL(releaseTag string) (downloadURL string) {
// Check if we are docker environment, return docker update command
if IsDocker() {
// Construct release tag name.
return fmt.Sprintf("docker pull minio/mc:%s", releaseTag)
}
// For binary only installations, we return link to the latest binary.
if runtime.GOOS == "windows" {
return mcReleaseURL + "mc.exe"
}
return mcReleaseURL + "mc"
}
func getUpdateInfo(timeout time.Duration) (updateMsg string, sha256Hex string, currentReleaseTime, latestReleaseTime time.Time, err *probe.Error) {
currentReleaseTime, err = GetCurrentReleaseTime()
if err != nil {
return updateMsg, sha256Hex, currentReleaseTime, latestReleaseTime, err.Trace()
}
sha256Hex, latestReleaseTime, err = getLatestReleaseTime(timeout)
if err != nil {
return updateMsg, sha256Hex, currentReleaseTime, latestReleaseTime, err.Trace()
}
var older time.Duration
var downloadURL string
if latestReleaseTime.After(currentReleaseTime) {
older = latestReleaseTime.Sub(currentReleaseTime)
downloadURL = getDownloadURL(releaseTimeToReleaseTag(latestReleaseTime))
}
return prepareUpdateMessage(downloadURL, older), sha256Hex, currentReleaseTime, latestReleaseTime, nil
}
var (
// Check if we stderr, stdout are dumb terminals, we do not apply
// ansi coloring on dumb terminals.
isTerminal = func() bool {
return isatty.IsTerminal(os.Stdout.Fd()) && isatty.IsTerminal(os.Stderr.Fd())
}
colorCyanBold = func() func(a ...interface{}) string {
if isTerminal() {
color.New(color.FgCyan, color.Bold).SprintFunc()
}
return fmt.Sprint
}()
colorYellowBold = func() func(format string, a ...interface{}) string {
if isTerminal() {
return color.New(color.FgYellow, color.Bold).SprintfFunc()
}
return fmt.Sprintf
}()
colorGreenBold = func() func(format string, a ...interface{}) string {
if isTerminal() {
return color.New(color.FgGreen, color.Bold).SprintfFunc()
}
return fmt.Sprintf
}()
)
func doUpdate(sha256Hex string, latestReleaseTime time.Time, ok bool) (updateStatusMsg string, err *probe.Error) {
if !ok {
updateStatusMsg = colorGreenBold("mc update to version RELEASE.%s canceled.",
latestReleaseTime.Format(mcReleaseTagTimeLayout))
return updateStatusMsg, nil
}
var sha256Sum []byte
var e error
sha256Sum, e = hex.DecodeString(sha256Hex)
if e != nil {
return updateStatusMsg, probe.NewError(e)
}
resp, e := http.Get(getDownloadURL(releaseTimeToReleaseTag(latestReleaseTime)))
if e != nil {
return updateStatusMsg, probe.NewError(e)
}
defer resp.Body.Close()
// FIXME: add support for gpg verification as well.
if e = update.Apply(resp.Body,
update.Options{
Hash: crypto.SHA256,
Checksum: sha256Sum,
},
); e != nil {
return updateStatusMsg, probe.NewError(e)
}
return colorGreenBold("mc updated to version RELEASE.%s successfully.",
latestReleaseTime.Format(mcReleaseTagTimeLayout)), nil
}
type updateMessage struct {
Status string `json:"status"`
Message string `json:"message"`
}
// String colorized make bucket message.
func (s updateMessage) String() string {
return s.Message
}
// JSON jsonified make bucket message.
func (s updateMessage) JSON() string {
s.Status = "success"
updateJSONBytes, e := json.MarshalIndent(s, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(updateJSONBytes)
}
func mainUpdate(ctx *cli.Context) {
if len(ctx.Args()) != 0 {
cli.ShowCommandHelpAndExit(ctx, "update", -1)
}
globalQuiet = ctx.Bool("quiet") || ctx.GlobalBool("quiet")
globalJSON = ctx.Bool("json") || ctx.GlobalBool("json")
updateMsg, sha256Hex, _, latestReleaseTime, err := getUpdateInfo(10 * time.Second)
if err != nil {
errorIf(err, "Unable to update ‘mc’.")
os.Exit(-1)
}
// Nothing to update running the latest release.
color.New(color.FgGreen, color.Bold)
if updateMsg == "" {
printMsg(updateMessage{
Status: "success",
Message: colorGreenBold("You are already running the most recent version of ‘mc’."),
})
os.Exit(0)
}
printMsg(updateMessage{
Status: "success",
Message: updateMsg,
})
// Avoid updating mc development, source builds.
if strings.Contains(updateMsg, mcReleaseURL) {
var updateStatusMsg string
var err *probe.Error
updateStatusMsg, err = doUpdate(sha256Hex, latestReleaseTime, true)
if err != nil {
errorIf(err, "Unable to update ‘mc’.")
os.Exit(-1)
}
printMsg(updateMessage{Status: "success", Message: updateStatusMsg})
os.Exit(1)
}
}
| [
"\"MESOS_CONTAINER_NAME\"",
"\"KUBERNETES_SERVICE_HOST\""
]
| []
| [
"MESOS_CONTAINER_NAME",
"KUBERNETES_SERVICE_HOST"
]
| [] | ["MESOS_CONTAINER_NAME", "KUBERNETES_SERVICE_HOST"] | go | 2 | 0 | |
py2app_tests/test_pkg_script.py | """
Test case for a project that includes a script that has the same
base-name as a package used by the script.
"""
import sys
if (sys.version_info[0] == 2 and sys.version_info[:2] >= (2,7)) or \
(sys.version_info[0] == 3 and sys.version_info[:2] >= (3,2)):
import unittest
else:
import unittest2 as unittest
import subprocess
import shutil
import time
import os
import signal
import py2app
import zipfile
if __name__ == "__main__":
from tools import kill_child_processes
else:
from .tools import kill_child_processes
DIR_NAME=os.path.dirname(os.path.abspath(__file__))
class TestBasicApp (unittest.TestCase):
py2app_args = []
python_args = []
app_dir = os.path.join(DIR_NAME, 'pkg_script_app')
# Basic setup code
#
# The code in this block needs to be moved to
# a base-class.
@classmethod
def setUpClass(cls):
kill_child_processes()
env=os.environ.copy()
env['TMPDIR'] = os.getcwd()
pp = os.path.dirname(os.path.dirname(py2app.__file__))
if 'PYTHONPATH' in env:
env['PYTHONPATH'] = pp + ':' + env['PYTHONPATH']
else:
env['PYTHONPATH'] = pp
if 'LANG' not in env:
# Ensure that testing though SSH works
env['LANG'] = 'en_US.UTF-8'
p = subprocess.Popen([
sys.executable ] + cls.python_args + [
'setup.py', 'py2app'] + cls.py2app_args,
cwd = cls.app_dir,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
close_fds=False,
env=env
)
lines = p.communicate()[0]
if p.wait() != 0:
print (lines)
raise AssertionError("Creating basic_app bundle failed")
@classmethod
def tearDownClass(cls):
if os.path.exists(os.path.join(cls.app_dir, 'build')):
shutil.rmtree(os.path.join(cls.app_dir, 'build'))
if os.path.exists(os.path.join(cls.app_dir, 'dist')):
shutil.rmtree(os.path.join(cls.app_dir, 'dist'))
time.sleep(2)
def tearDown(self):
kill_child_processes()
time.sleep(1)
def start_app(self):
# Start the test app, return a subprocess object where
# stdin and stdout are connected to pipes.
path = os.path.join(
self.app_dir,
'dist/quot.app/Contents/MacOS/quot')
p = subprocess.Popen([path],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
close_fds=False,
)
#stderr=subprocess.STDOUT)
return p
def wait_with_timeout(self, proc, timeout=10):
for i in range(timeout):
x = proc.poll()
if x is None:
time.sleep(1)
else:
return x
os.kill(proc.pid, signal.SIGKILL)
return proc.wait()
#
# End of setup code
#
def test_basic_start(self):
p = self.start_app()
p.stdin.close()
exit = self.wait_with_timeout(p)
self.assertEqual(exit, 0)
p.stdout.close()
def test_simple_imports(self):
p = self.start_app()
p.stdin.write(("print(%r in sys.path)\n"%(
os.path.join(self.app_dir, 'dist/quot.app/Contents/Resources'),)).encode('latin1'))
p.stdin.flush()
ln = p.stdout.readline()
self.assertEqual(ln.strip(), b"False")
# Basic module that is always present:
p.stdin.write('import_module("os")\n'.encode('latin1'))
p.stdin.flush()
ln = p.stdout.readline()
self.assertEqual(ln.strip(), b"os")
# Dependency of the main module:
p.stdin.write('import_module("quot")\n'.encode('latin1'))
p.stdin.flush()
ln = p.stdout.readline()
self.assertEqual(ln.strip(), b"quot")
# - verify that the right one gets loaded
if '--alias' not in self.py2app_args:
p.stdin.write('import quot;print(quot.__file__)\n'.encode('latin1'))
p.stdin.flush()
ln = p.stdout.readline()
self.assertTrue(b"Contents/Resources/lib" in ln.strip())
p.stdin.write('import_module("quot.queue")\n'.encode('latin1'))
p.stdin.flush()
ln = p.stdout.readline()
self.assertEqual(ln.strip(), b"quot.queue")
p.stdin.close()
p.stdout.close()
def test_zip_contents(self):
if '--alias' in self.py2app_args:
raise unittest.SkipTest("Not relevant for Alias builds")
dirpath = os.path.join(self.app_dir, 'dist/quot.app/Contents')
zfpath = os.path.join(dirpath, 'Resources/lib/python%d%d.zip'%(
sys.version_info[:2]))
if not os.path.exists(zfpath):
zfpath = os.path.join(dirpath, 'Resources/lib/python%d.%d/site-packages.zip'%(
sys.version_info[:2]))
if not os.path.exists(zfpath):
zfpath = os.path.join(dirpath, 'Resources/lib/site-packages.zip')
if not os.path.exists(zfpath):
self.fail("Cannot locate embedded zipfile")
zf = zipfile.ZipFile(zfpath, 'r')
for nm in ('quot.py', 'quot.pyc', 'quot.pyo'):
try:
zf.read(nm)
self.fail("'quot' module is in the zipfile")
except KeyError:
pass
class TestBasicAliasApp (TestBasicApp):
py2app_args = [ '--alias', ]
class TestBasicSemiStandaloneApp (TestBasicApp):
py2app_args = [ '--semi-standalone', ]
if __name__ == "__main__":
unittest.main()
| []
| []
| []
| [] | [] | python | 0 | 0 | |
demoApp/manage.py | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'demoApp.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
| []
| []
| []
| [] | [] | python | 0 | 0 | |
pkg/config/postgres.go | package config
// Postgres config
type Postgres struct {
Host string `validate:"required" envconfig:"ATHENS_INDEX_POSTGRES_HOST"`
Port int `validate:"required" envconfig:"ATHENS_INDEX_POSTGRES_PORT"`
User string `validate:"required" envconfig:"ATHENS_INDEX_POSTGRES_USER"`
Password string `validate:"" envconfig:"ATHENS_INDEX_POSTGRES_PASSWORD"`
Database string `validate:"required" envconfig:"ATHENS_INDEX_POSTGRES_DATABASE"`
Params map[string]string `validate:"required" envconfig:"ATHENS_INDEX_POSTGRES_PARAMS"`
}
| []
| []
| []
| [] | [] | go | null | null | null |
micromailer/settings.py | # -*- coding: utf-8 -*-
"""Application configuration."""
import os
class Config(object):
"""Base configuration."""
SECRET_KEY = os.environ.get('MICROMAILER_SECRET', 'secret-key') # TODO: Change me
APP_DIR = os.path.abspath(os.path.dirname(__file__)) # This directory
PROJECT_ROOT = os.path.abspath(os.path.join(APP_DIR, os.pardir))
BCRYPT_LOG_ROUNDS = 13
DEBUG_TB_ENABLED = False # Disable Debug toolbar
DEBUG_TB_INTERCEPT_REDIRECTS = False
CACHE_TYPE = 'simple' # Can be "memcached", "redis", etc.
NO_REPLY_CLUEPOINTS = '[email protected]'
# Configuration for marrow mailer
MARROWMAILER_CONFIG = {
'transport.use': 'smtp',
'manager.use': 'futures',
'transport.host': 'localhost',
'transport.port': 2525,
'transport.tls': 'optional',
'transport.max_messages_per_connection': 5
}
class ProdConfig(Config):
"""Production configuration."""
ENV = 'prod'
DEBUG = False
DEBUG_TB_ENABLED = False # Disable Debug toolbar
class DevConfig(Config):
"""Development configuration."""
ENV = 'dev'
DEBUG = True
DEBUG_TB_ENABLED = True
CACHE_TYPE = 'simple' # Can be "memcached", "redis", etc.
class TestConfig(Config):
"""Test configuration."""
TESTING = True
DEBUG = True
WTF_CSRF_ENABLED = False # Allows form testing
| []
| []
| [
"MICROMAILER_SECRET"
]
| [] | ["MICROMAILER_SECRET"] | python | 1 | 0 | |
cmd/server-main.go | /*
* Minio Cloud Storage, (C) 2015, 2016, 2017 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd
import (
"errors"
"fmt"
"net"
"net/url"
"os"
"path"
"sort"
"strconv"
"strings"
"time"
"runtime"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
)
var serverFlags = []cli.Flag{
cli.StringFlag{
Name: "address",
Value: ":9000",
Usage: "Bind to a specific ADDRESS:PORT, ADDRESS can be an IP or hostname.",
},
}
var serverCmd = cli.Command{
Name: "server",
Usage: "Start object storage server.",
Flags: append(serverFlags, globalFlags...),
Action: serverMain,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} {{if .VisibleFlags}}[FLAGS] {{end}}PATH [PATH...]
{{if .VisibleFlags}}
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}{{end}}
ENVIRONMENT VARIABLES:
ACCESS:
MINIO_ACCESS_KEY: Custom username or access key of 5 to 20 characters in length.
MINIO_SECRET_KEY: Custom password or secret key of 8 to 40 characters in length.
BROWSER:
MINIO_BROWSER: To disable web browser access, set this value to "off".
EXAMPLES:
1. Start minio server on "/home/shared" directory.
$ {{.HelpName}} /home/shared
2. Start minio server bound to a specific ADDRESS:PORT.
$ {{.HelpName}} --address 192.168.1.101:9000 /home/shared
3. Start erasure coded minio server on a 12 disks server.
$ {{.HelpName}} /mnt/export1/ /mnt/export2/ /mnt/export3/ /mnt/export4/ \
/mnt/export5/ /mnt/export6/ /mnt/export7/ /mnt/export8/ /mnt/export9/ \
/mnt/export10/ /mnt/export11/ /mnt/export12/
4. Start erasure coded distributed minio server on a 4 node setup with 1 drive each. Run following commands on all the 4 nodes.
$ export MINIO_ACCESS_KEY=minio
$ export MINIO_SECRET_KEY=miniostorage
$ {{.HelpName}} http://192.168.1.11/mnt/export/ http://192.168.1.12/mnt/export/ \
http://192.168.1.13/mnt/export/ http://192.168.1.14/mnt/export/
`,
}
// Check for updates and print a notification message
func checkUpdate(mode string) {
// Its OK to ignore any errors during getUpdateInfo() here.
if older, downloadURL, err := getUpdateInfo(1*time.Second, mode); err == nil {
if older > time.Duration(0) {
console.Println(colorizeUpdateMessage(downloadURL, older))
}
}
}
// envParams holds all env parameters
type envParams struct {
creds credential
browser string
}
func migrate() {
// Migrate config file
err := migrateConfig()
fatalIf(err, "Config migration failed.")
// Migrate other configs here.
}
func enableLoggers() {
// Enable all loggers here.
enableConsoleLogger()
enableFileLogger()
// Add your logger here.
}
// Initializes a new config if it doesn't exist, else migrates any old config
// to newer config and finally loads the config to memory.
func initConfig() {
accessKey := os.Getenv("MINIO_ACCESS_KEY")
secretKey := os.Getenv("MINIO_SECRET_KEY")
var cred credential
var err error
if accessKey != "" && secretKey != "" {
if cred, err = createCredential(accessKey, secretKey); err != nil {
console.Fatalf("Invalid access/secret Key set in environment. Err: %s.\n", err)
}
// credential Envs are set globally.
globalIsEnvCreds = true
}
browser := os.Getenv("MINIO_BROWSER")
if browser != "" {
if !(strings.EqualFold(browser, "off") || strings.EqualFold(browser, "on")) {
console.Fatalf("Invalid value ‘%s’ in MINIO_BROWSER environment variable.", browser)
}
// browser Envs are set globally, this doesn't represent
// if browser is turned off or on.
globalIsEnvBrowser = true
}
envs := envParams{
creds: cred,
browser: browser,
}
// Config file does not exist, we create it fresh and return upon success.
if !isConfigFileExists() {
if err := newConfig(envs); err != nil {
console.Fatalf("Unable to initialize minio config for the first time. Error: %s.\n", err)
}
console.Println("Created minio configuration file successfully at " + getConfigDir())
return
}
// Migrate any old version of config / state files to newer format.
migrate()
// Validate config file
if err := validateConfig(); err != nil {
console.Fatalf("Cannot validate configuration file. Error: %s\n", err)
}
// Once we have migrated all the old config, now load them.
if err := loadConfig(envs); err != nil {
console.Fatalf("Unable to initialize minio config. Error: %s.\n", err)
}
}
// Generic Minio initialization to create/load config, prepare loggers, etc..
func minioInit(ctx *cli.Context) {
// Create certs path.
fatalIf(createConfigDir(), "Unable to create \"certs\" directory.")
// Is TLS configured?.
globalIsSSL = isSSL()
// Initialize minio server config.
initConfig()
// Enable all loggers by now so we can use errorIf() and fatalIf()
enableLoggers()
// Init the error tracing module.
initError()
}
type serverCmdConfig struct {
serverAddr string
endpoints []*url.URL
}
// Parse an array of end-points (from the command line)
func parseStorageEndpoints(eps []string) (endpoints []*url.URL, err error) {
for _, ep := range eps {
if ep == "" {
return nil, errInvalidArgument
}
var u *url.URL
u, err = url.Parse(ep)
if err != nil {
return nil, err
}
if u.Host != "" {
_, port, err := net.SplitHostPort(u.Host)
// Ignore the missing port error as the default port can be globalMinioPort.
if err != nil && !strings.Contains(err.Error(), "missing port in address") {
return nil, err
}
if globalMinioHost == "" {
// For ex.: minio server host1:port1 host2:port2...
// we return error as port is configurable only
// using "--address :port"
if port != "" {
return nil, fmt.Errorf("Invalid Argument %s, port configurable using --address :<port>", u.Host)
}
u.Host = net.JoinHostPort(u.Host, globalMinioPort)
} else {
// For ex.: minio server --address host:port host1:port1 host2:port2...
// i.e if "--address host:port" is specified
// port info in u.Host is mandatory else return error.
if port == "" {
return nil, fmt.Errorf("Invalid Argument %s, port mandatory when --address <host>:<port> is used", u.Host)
}
}
}
endpoints = append(endpoints, u)
}
return endpoints, nil
}
// initServer initialize server config.
func initServerConfig(c *cli.Context) {
// Initialization such as config generating/loading config, enable logging, ..
minioInit(c)
// Load user supplied root CAs
fatalIf(loadRootCAs(), "Unable to load a CA files")
// Set system resources to maximum.
errorIf(setMaxResources(), "Unable to change resource limit")
}
// Validate if input disks are sufficient for initializing XL.
func checkSufficientDisks(eps []*url.URL) error {
// Verify total number of disks.
total := len(eps)
if total > maxErasureBlocks {
return errXLMaxDisks
}
if total < minErasureBlocks {
return errXLMinDisks
}
// isEven function to verify if a given number if even.
isEven := func(number int) bool {
return number%2 == 0
}
// Verify if we have even number of disks.
// only combination of 4, 6, 8, 10, 12, 14, 16 are supported.
if !isEven(total) {
return errXLNumDisks
}
// Success.
return nil
}
// Returns if slice of disks is a distributed setup.
func isDistributedSetup(eps []*url.URL) bool {
// Validate if one the disks is not local.
for _, ep := range eps {
if !isLocalStorage(ep) {
// One or more disks supplied as arguments are
// not attached to the local node.
return true
}
}
return false
}
// Returns true if path is empty, or equals to '.', '/', '\' characters.
func isPathSentinel(path string) bool {
return path == "" || path == "." || path == "/" || path == `\`
}
// Returned when path is empty or root path.
var errEmptyRootPath = errors.New("Empty or root path is not allowed")
// Invalid scheme passed.
var errInvalidScheme = errors.New("Invalid scheme")
// Check if endpoint is in expected syntax by valid scheme/path across all platforms.
func checkEndpointURL(endpointURL *url.URL) (err error) {
// Applicable to all OS.
if endpointURL.Scheme == "" || endpointURL.Scheme == httpScheme || endpointURL.Scheme == httpsScheme {
if isPathSentinel(path.Clean(endpointURL.Path)) {
err = errEmptyRootPath
}
return err
}
// Applicable to Windows only.
if runtime.GOOS == globalWindowsOSName {
// On Windows, endpoint can be a path with drive eg. C:\Export and its URL.Scheme is 'C'.
// Check if URL.Scheme is a single letter alphabet to represent a drive.
// Note: URL.Parse() converts scheme into lower case always.
if len(endpointURL.Scheme) == 1 && endpointURL.Scheme[0] >= 'a' && endpointURL.Scheme[0] <= 'z' {
// If endpoint is C:\ or C:\export, URL.Path does not have path information like \ or \export
// hence we directly work with endpoint.
if isPathSentinel(strings.SplitN(path.Clean(endpointURL.String()), ":", 2)[1]) {
err = errEmptyRootPath
}
return err
}
}
return errInvalidScheme
}
// Check if endpoints are in expected syntax by valid scheme/path across all platforms.
func checkEndpointsSyntax(eps []*url.URL, disks []string) error {
for i, u := range eps {
if err := checkEndpointURL(u); err != nil {
return fmt.Errorf("%s: %s (%s)", err.Error(), u.Path, disks[i])
}
}
return nil
}
// Make sure all the command line parameters are OK and exit in case of invalid parameters.
func checkServerSyntax(c *cli.Context) {
serverAddr := c.String("address")
host, portStr, err := net.SplitHostPort(serverAddr)
fatalIf(err, "Unable to parse %s.", serverAddr)
// Verify syntax for all the XL disks.
disks := c.Args()
// Parse disks check if they comply with expected URI style.
endpoints, err := parseStorageEndpoints(disks)
fatalIf(err, "Unable to parse storage endpoints %s", strings.Join(disks, " "))
// Validate if endpoints follow the expected syntax.
err = checkEndpointsSyntax(endpoints, disks)
fatalIf(err, "Invalid endpoints found %s", strings.Join(disks, " "))
// Validate for duplicate endpoints are supplied.
err = checkDuplicateEndpoints(endpoints)
fatalIf(err, "Duplicate entries in %s", strings.Join(disks, " "))
if len(endpoints) > 1 {
// Validate if we have sufficient disks for XL setup.
err = checkSufficientDisks(endpoints)
fatalIf(err, "Insufficient number of disks.")
} else {
// Validate if we have invalid disk for FS setup.
if endpoints[0].Host != "" && endpoints[0].Scheme != "" {
fatalIf(errInvalidArgument, "%s, FS setup expects a filesystem path", endpoints[0])
}
}
if !isDistributedSetup(endpoints) {
// for FS and singlenode-XL validation is done, return.
return
}
// Rest of the checks applies only to distributed XL setup.
if host != "" {
// We are here implies --address host:port is passed, hence the user is trying
// to run one minio process per export disk.
if portStr == "" {
fatalIf(errInvalidArgument, "Port missing, Host:Port should be specified for --address")
}
foundCnt := 0
for _, ep := range endpoints {
if ep.Host == serverAddr {
foundCnt++
}
}
if foundCnt == 0 {
// --address host:port should be available in the XL disk list.
fatalIf(errInvalidArgument, "%s is not available in %s", serverAddr, strings.Join(disks, " "))
}
if foundCnt > 1 {
// --address host:port should match exactly one entry in the XL disk list.
fatalIf(errInvalidArgument, "%s matches % entries in %s", serverAddr, foundCnt, strings.Join(disks, " "))
}
}
for _, ep := range endpoints {
if ep.Scheme == httpsScheme && !globalIsSSL {
// Certificates should be provided for https configuration.
fatalIf(errInvalidArgument, "Certificates not provided for secure configuration")
}
}
}
// Checks if any of the endpoints supplied is local to this server.
func isAnyEndpointLocal(eps []*url.URL) bool {
anyLocalEp := false
for _, ep := range eps {
if isLocalStorage(ep) {
anyLocalEp = true
break
}
}
return anyLocalEp
}
// Returned when there are no ports.
var errEmptyPort = errors.New("Port cannot be empty or '0', please use `--address` to pick a specific port")
// Convert an input address of form host:port into, host and port, returns if any.
func getHostPort(address string) (host, port string, err error) {
// Check if requested port is available.
host, port, err = net.SplitHostPort(address)
if err != nil {
return "", "", err
}
// Empty ports.
if port == "0" || port == "" {
// Port zero or empty means use requested to choose any freely available
// port. Avoid this since it won't work with any configured clients,
// can lead to serious loss of availability.
return "", "", errEmptyPort
}
// Parse port.
if _, err = strconv.Atoi(port); err != nil {
return "", "", err
}
if runtime.GOOS == "darwin" {
// On macOS, if a process already listens on 127.0.0.1:PORT, net.Listen() falls back
// to IPv6 address ie minio will start listening on IPv6 address whereas another
// (non-)minio process is listening on IPv4 of given port.
// To avoid this error sutiation we check for port availability only for macOS.
if err = checkPortAvailability(port); err != nil {
return "", "", err
}
}
// Success.
return host, port, nil
}
// serverMain handler called for 'minio server' command.
func serverMain(c *cli.Context) {
if !c.Args().Present() || c.Args().First() == "help" {
cli.ShowCommandHelpAndExit(c, "server", 1)
}
// Get quiet flag from command line argument.
quietFlag := c.Bool("quiet") || c.GlobalBool("quiet")
// Get configuration directory from command line argument.
configDir := c.String("config-dir")
if !c.IsSet("config-dir") && c.GlobalIsSet("config-dir") {
configDir = c.GlobalString("config-dir")
}
if configDir == "" {
console.Fatalln("Configuration directory cannot be empty.")
}
// Set configuration directory.
setConfigDir(configDir)
// Start profiler if env is set.
if profiler := os.Getenv("_MINIO_PROFILER"); profiler != "" {
globalProfiler = startProfiler(profiler)
}
// Initializes server config, certs, logging and system settings.
initServerConfig(c)
// Server address.
serverAddr := c.String("address")
var err error
globalMinioHost, globalMinioPort, err = getHostPort(serverAddr)
fatalIf(err, "Unable to extract host and port %s", serverAddr)
// Check server syntax and exit in case of errors.
// Done after globalMinioHost and globalMinioPort is set
// as parseStorageEndpoints() depends on it.
checkServerSyntax(c)
// Disks to be used in server init.
endpoints, err := parseStorageEndpoints(c.Args())
fatalIf(err, "Unable to parse storage endpoints %s", c.Args())
// Should exit gracefully if none of the endpoints passed
// as command line args are local to this server.
if !isAnyEndpointLocal(endpoints) {
fatalIf(errInvalidArgument, "None of the disks passed as command line args are local to this server.")
}
// Sort endpoints for consistent ordering across multiple
// nodes in a distributed setup. This is to avoid format.json
// corruption if the disks aren't supplied in the same order
// on all nodes.
sort.Sort(byHostPath(endpoints))
// Configure server.
srvConfig := serverCmdConfig{
serverAddr: serverAddr,
endpoints: endpoints,
}
// Check if endpoints are part of distributed setup.
globalIsDistXL = isDistributedSetup(endpoints)
// Set nodes for dsync for distributed setup.
if globalIsDistXL {
fatalIf(initDsyncNodes(endpoints), "Unable to initialize distributed locking clients")
}
// Set globalIsXL if erasure code backend is about to be
// initialized for the given endpoints.
if len(endpoints) > 1 {
globalIsXL = true
}
if !quietFlag {
// Check for new updates from dl.minio.io.
mode := globalMinioModeFS
if globalIsXL {
mode = globalMinioModeXL
}
if globalIsDistXL {
mode = globalMinioModeDistXL
}
checkUpdate(mode)
}
// Initialize name space lock.
initNSLock(globalIsDistXL)
// Configure server.
handler, err := configureServerHandler(srvConfig)
fatalIf(err, "Unable to configure one of server's RPC services.")
// Initialize a new HTTP server.
apiServer := NewServerMux(serverAddr, handler)
// Set the global minio addr for this server.
globalMinioAddr = getLocalAddress(srvConfig)
// Initialize S3 Peers inter-node communication only in distributed setup.
initGlobalS3Peers(endpoints)
// Initialize Admin Peers inter-node communication only in distributed setup.
initGlobalAdminPeers(endpoints)
// Determine API endpoints where we are going to serve the S3 API from.
apiEndPoints, err := finalizeAPIEndpoints(apiServer.Addr)
fatalIf(err, "Unable to finalize API endpoints for %s", apiServer.Addr)
// Set the global API endpoints value.
globalAPIEndpoints = apiEndPoints
// Start server, automatically configures TLS if certs are available.
go func() {
cert, key := "", ""
if globalIsSSL {
cert, key = getPublicCertFile(), getPrivateKeyFile()
}
fatalIf(apiServer.ListenAndServe(cert, key), "Failed to start minio server.")
}()
// Set endpoints of []*url.URL type to globalEndpoints.
globalEndpoints = endpoints
newObject, err := newObjectLayer(srvConfig)
fatalIf(err, "Initializing object layer failed")
globalObjLayerMutex.Lock()
globalObjectAPI = newObject
globalObjLayerMutex.Unlock()
// Prints the formatted startup message once object layer is initialized.
if !quietFlag {
printStartupMessage(apiEndPoints)
}
// Set uptime time after object layer has initialized.
globalBootTime = UTCNow()
// Waits on the server.
<-globalServiceDoneCh
}
// Initialize object layer with the supplied disks, objectLayer is nil upon any error.
func newObjectLayer(srvCmdCfg serverCmdConfig) (newObject ObjectLayer, err error) {
// For FS only, directly use the disk.
isFS := len(srvCmdCfg.endpoints) == 1
if isFS {
// Unescape is needed for some UNC paths on windows
// which are of this form \\127.0.0.1\\export\test.
var fsPath string
fsPath, err = url.QueryUnescape(srvCmdCfg.endpoints[0].String())
if err != nil {
return nil, err
}
// Initialize new FS object layer.
newObject, err = newFSObjectLayer(fsPath)
if err != nil {
return nil, err
}
// FS initialized, return.
return newObject, nil
}
// First disk argument check if it is local.
firstDisk := isLocalStorage(srvCmdCfg.endpoints[0])
// Initialize storage disks.
storageDisks, err := initStorageDisks(srvCmdCfg.endpoints)
if err != nil {
return nil, err
}
// Wait for formatting disks for XL backend.
var formattedDisks []StorageAPI
formattedDisks, err = waitForFormatXLDisks(firstDisk, srvCmdCfg.endpoints, storageDisks)
if err != nil {
return nil, err
}
// Cleanup objects that weren't successfully written into the namespace.
if err = houseKeeping(storageDisks); err != nil {
return nil, err
}
// Once XL formatted, initialize object layer.
newObject, err = newXLObjectLayer(formattedDisks)
if err != nil {
return nil, err
}
// XL initialized, return.
return newObject, nil
}
| [
"\"MINIO_ACCESS_KEY\"",
"\"MINIO_SECRET_KEY\"",
"\"MINIO_BROWSER\"",
"\"_MINIO_PROFILER\""
]
| []
| [
"MINIO_BROWSER",
"_MINIO_PROFILER",
"MINIO_SECRET_KEY",
"MINIO_ACCESS_KEY"
]
| [] | ["MINIO_BROWSER", "_MINIO_PROFILER", "MINIO_SECRET_KEY", "MINIO_ACCESS_KEY"] | go | 4 | 0 | |
cmd/start.go | // Copyright © 2017 NAME HERE <EMAIL ADDRESS>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd
import (
"fmt"
"github.com/Sirupsen/logrus"
"github.com/kubernetes-incubator/external-storage/lib/controller"
"github.com/raffaelespazzoli/iscsi-controller/provisioner"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"time"
)
var log = logrus.New()
// start-controllerCmd represents the start-controller command
var startcontrollerCmd = &cobra.Command{
Use: "start",
Short: "A brief description of your command",
Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Run: func(cmd *cobra.Command, args []string) {
initLog()
log.Debugln("start called")
// creates the in-cluster config
log.Debugln("creating in cluster default kube client config")
config, err := rest.InClusterConfig()
if err != nil {
log.Fatalln(err)
}
log.WithFields(logrus.Fields{
"config-host": config.Host,
}).Debugln("kube client config created")
// creates the clientset
log.Debugln("creating kube client set")
kubernetesClientSet, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatalln(err)
}
log.Debugln("kube client set created")
// The controller needs to know what the server version is because out-of-tree
// provisioners aren't officially supported until 1.5
serverVersion, err := kubernetesClientSet.Discovery().ServerVersion()
if err != nil {
log.Fatalf("Error getting server version: %v", err)
}
//url := viper.GetString("targetd-scheme") + "://" + viper.GetString("targetd-username") + ":" + viper.GetString("targetd-password") + "@" + viper.GetString("targetd-address") + ":" + viper.GetInt("targetd-port")
url := fmt.Sprintf("%s://%s:%s@%s:%d/targetrpc", viper.GetString("targetd-scheme"), viper.GetString("targetd-username"), viper.GetString("targetd-password"), viper.GetString("targetd-address"), viper.GetInt("targetd-port"))
log.Debugln("targed URL", url)
iscsiProvisioner := provisioner.NewiscsiProvisioner(url)
log.Debugln("iscsi provisioner created")
pc := controller.NewProvisionController(kubernetesClientSet, viper.GetDuration("resync-period"), viper.GetString("provisioner-name"), iscsiProvisioner, serverVersion.GitVersion,
viper.GetBool("exponential-backoff-on-error"), viper.GetInt("fail-retry-threshold"), viper.GetDuration("lease-period"),
viper.GetDuration("renew-deadline"), viper.GetDuration("retry-priod"), viper.GetDuration("term-limit"))
log.Debugln("iscsi controller created, running forever...")
pc.Run(wait.NeverStop)
},
}
func init() {
RootCmd.AddCommand(startcontrollerCmd)
startcontrollerCmd.Flags().String("provisioner-name", "iscsi-provisioner", "name of this provisioner, must match what is passed int the storage class annotation")
viper.BindPFlag("provisioner-name", startcontrollerCmd.Flags().Lookup("provisioner-name"))
startcontrollerCmd.Flags().Duration("resync-period", 15*time.Second, "how often to poll the master API for updates")
viper.BindPFlag("resync-period", startcontrollerCmd.Flags().Lookup("resync-period"))
startcontrollerCmd.Flags().Bool("exponential-backoff-on-error", true, "exponential-backoff-on-error doubles the retry-period everytime there is an error")
viper.BindPFlag("exponential-backoff-on-error", startcontrollerCmd.Flags().Lookup("exponential-backoff-on-error"))
startcontrollerCmd.Flags().Int("fail-retry-threshold", 10, "Threshold for max number of retries on failure of provisioner")
viper.BindPFlag("fail-retry-threshold", startcontrollerCmd.Flags().Lookup("fail-retry-threshold"))
startcontrollerCmd.Flags().Duration("lease-period", controller.DefaultLeaseDuration, "LeaseDuration is the duration that non-leader candidates will wait to force acquire leadership. This is measured against time of last observed ack")
viper.BindPFlag("lease-period", startcontrollerCmd.Flags().Lookup("lease-period"))
startcontrollerCmd.Flags().Duration("renew-deadline", controller.DefaultRenewDeadline, "RenewDeadline is the duration that the acting master will retry refreshing leadership before giving up")
viper.BindPFlag("renew-deadline", startcontrollerCmd.Flags().Lookup("renew-deadline"))
startcontrollerCmd.Flags().Duration("retry-priod", controller.DefaultRetryPeriod, "RetryPeriod is the duration the LeaderElector clients should wait between tries of actions")
viper.BindPFlag("retry-priod", startcontrollerCmd.Flags().Lookup("retry-priod"))
startcontrollerCmd.Flags().Duration("term-limit", controller.DefaultTermLimit, "TermLimit is the maximum duration that a leader may remain the leader to complete the task before it must give up its leadership. 0 for forever or indefinite.")
viper.BindPFlag("term-limit", startcontrollerCmd.Flags().Lookup("term-limit"))
startcontrollerCmd.Flags().String("targetd-scheme", "http", "scheme of the targetd connection, can be http or https")
viper.BindPFlag("targetd-scheme", startcontrollerCmd.Flags().Lookup("targetd-scheme"))
startcontrollerCmd.Flags().String("targetd-username", "admin", "username for the targetd connection")
viper.BindPFlag("targetd-username", startcontrollerCmd.Flags().Lookup("targetd-username"))
startcontrollerCmd.Flags().String("targetd-password", "", "password for the targetd connection")
viper.BindPFlag("targetd-password", startcontrollerCmd.Flags().Lookup("targetd-password"))
startcontrollerCmd.Flags().String("targetd-address", "localhost", "ip or dns of the targetd server")
viper.BindPFlag("targetd-address", startcontrollerCmd.Flags().Lookup("targetd-address"))
startcontrollerCmd.Flags().Int("targetd-port", 18700, "port on which targetd is listening")
viper.BindPFlag("targetd-port", startcontrollerCmd.Flags().Lookup("targetd-port"))
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// start-controllerCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// start-controllerCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
func initLog() {
var err error
log.Level, err = logrus.ParseLevel(viper.GetString("log-level"))
if err != nil {
log.Fatalln(err)
}
}
| []
| []
| []
| [] | [] | go | null | null | null |
sdk/storage/azure-storage-queue/src/samples/java/com/azure/storage/queue/ReadmeSamples.java | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.storage.queue;
import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import com.azure.core.util.Context;
import com.azure.storage.queue.models.QueueProperties;
import com.azure.storage.queue.models.QueueServiceProperties;
import com.azure.storage.queue.models.QueueServiceStatistics;
import com.azure.storage.queue.models.QueueStorageException;
import com.azure.storage.queue.models.QueuesSegmentOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* WARNING: MODIFYING THIS FILE WILL REQUIRE CORRESPONDING UPDATES TO README.md FILE. LINE NUMBERS
* ARE USED TO EXTRACT APPROPRIATE CODE SEGMENTS FROM THIS FILE. ADD NEW CODE AT THE BOTTOM TO AVOID CHANGING
* LINE NUMBERS OF EXISTING CODE SAMPLES.
*
* Code samples for the README.md
*/
@SuppressWarnings("unused")
public class ReadmeSamples {
private static final String ACCOUNT_NAME = System.getenv("AZURE_STORAGE_ACCOUNT_NAME");
private static final String SAS_TOKEN = System.getenv("PRIMARY_SAS_TOKEN");
String markers = "marker";
QueuesSegmentOptions options = new QueuesSegmentOptions();
Duration timeout = Duration.ofSeconds(1);
Context context = Context.NONE;
String messageId = "messageId";
String popReceipt = "popReceipt";
String messageText = "messageText";
Duration visibilityTimeout = Duration.ofSeconds(1);
String key = "key";
String value = "value";
String queueAsyncName = "queueAsyncName";
String queueName = "queueName";
Map<String, String> metadata = new HashMap<String, String>() {
{
put("key1", "val1");
put("key2", "val2");
}
};
private final Logger logger = LoggerFactory.getLogger(ReadmeSamples.class);
public void handleException() {
// BEGIN: readme-sample-handleException
String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL)
.sasToken(SAS_TOKEN).buildClient();
try {
queueServiceClient.createQueue("myQueue");
} catch (QueueStorageException e) {
logger.error("Failed to create a queue with error code: " + e.getErrorCode());
}
// END: readme-sample-handleException
}
public void createQueue1() {
// BEGIN: readme-sample-createQueue1
String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL)
.sasToken(SAS_TOKEN).buildClient();
QueueClient newQueueClient = queueServiceClient.createQueue("myQueue");
// END: readme-sample-createQueue1
}
public void createQueue2() {
// BEGIN: readme-sample-createQueue2
String queueServiceAsyncURL = String.format("https://%s.queue.core.windows.net/", ACCOUNT_NAME);
QueueServiceAsyncClient queueServiceAsyncClient = new QueueServiceClientBuilder().endpoint(queueServiceAsyncURL)
.sasToken(SAS_TOKEN).buildAsyncClient();
queueServiceAsyncClient.createQueue("newAsyncQueue").subscribe(result -> {
// do something when new queue created
}, error -> {
// do something if something wrong happened
}, () -> {
// completed, do something
});
// END: readme-sample-createQueue2
}
public void createWithResponse1() {
// BEGIN: readme-sample-createWithResponse1
String queueURL = String.format("https://%s.queue.core.windows.net/%s", ACCOUNT_NAME, queueName);
QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).buildClient();
// metadata is map of key-value pair
queueClient.createWithResponse(metadata, Duration.ofSeconds(30), Context.NONE);
// END: readme-sample-createWithResponse1
}
public void createWithResponse2() {
// BEGIN: readme-sample-createWithResponse2
// Only one "?" is needed here. If the sastoken starts with "?", please removing one "?".
String queueAsyncURL = String.format("https://%s.queue.core.windows.net/%s?%s", ACCOUNT_NAME, queueAsyncName,
SAS_TOKEN);
QueueAsyncClient queueAsyncClient = new QueueClientBuilder().endpoint(queueAsyncURL).buildAsyncClient();
queueAsyncClient.createWithResponse(metadata).subscribe(result -> {
// do something when new queue created
}, error -> {
// do something if something wrong happened
}, () -> {
// completed, do something
});
// END: readme-sample-createWithResponse2
}
public void getQueueServiceClient1() {
// BEGIN: readme-sample-getQueueServiceClient1
// Only one "?" is needed here. If the sastoken starts with "?", please removing one "?".
String queueServiceURL = String.format("https://%s.queue.core.windows.net/?%s", ACCOUNT_NAME, SAS_TOKEN);
QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL).buildClient();
// END: readme-sample-getQueueServiceClient1
}
public void getQueueServiceClient2() {
// BEGIN: readme-sample-getQueueServiceClient2
String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL)
.sasToken(SAS_TOKEN).buildClient();
// END: readme-sample-getQueueServiceClient2
}
public void deleteQueue() {
// BEGIN: readme-sample-deleteQueue
String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL)
.sasToken(SAS_TOKEN).buildClient();
queueServiceClient.deleteQueue("myqueue");
// END: readme-sample-deleteQueue
}
public void getQueueListInAccount() {
// BEGIN: readme-sample-getQueueListInAccount
String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL)
.sasToken(SAS_TOKEN).buildClient();
// @param marker: Starting point to list the queues
// @param options: Filter for queue selection
// @param timeout: An optional timeout applied to the operation.
// @param context: Additional context that is passed through the Http pipeline during the service call.
queueServiceClient.listQueues(options, timeout, context).stream().forEach(queueItem ->
System.out.printf("Queue %s exists in the account.", queueItem.getName()));
// END: readme-sample-getQueueListInAccount
}
public void getPropertiesInQueueAccount() {
// BEGIN: readme-sample-getPropertiesInQueueAccount
String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL)
.sasToken(SAS_TOKEN).buildClient();
QueueServiceProperties properties = queueServiceClient.getProperties();
// END: readme-sample-getPropertiesInQueueAccount
}
public void setPropertiesInQueueAccount() {
// BEGIN: readme-sample-setPropertiesInQueueAccount
String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL)
.sasToken(SAS_TOKEN).buildClient();
QueueServiceProperties properties = queueServiceClient.getProperties();
properties.setCors(Collections.emptyList());
queueServiceClient.setProperties(properties);
// END: readme-sample-setPropertiesInQueueAccount
}
public void getQueueServiceStatistics() {
// BEGIN: readme-sample-getQueueServiceStatistics
String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL)
.sasToken(SAS_TOKEN).buildClient();
QueueServiceStatistics queueStats = queueServiceClient.getStatistics();
// END: readme-sample-getQueueServiceStatistics
}
public void enqueueMessage() {
// BEGIN: readme-sample-enqueueMessage
String queueURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).queueName("myqueue")
.buildClient();
queueClient.sendMessage("myMessage");
// END: readme-sample-enqueueMessage
}
public void updateMessage() {
// BEGIN: readme-sample-updateMessage
String queueURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).queueName("myqueue")
.buildClient();
// @param messageId: Id of the message
// @param popReceipt: Unique identifier that must match the message for it to be updated
// @param visibilityTimeout: How long the message will be invisible in the queue in seconds
queueClient.updateMessage(messageId, popReceipt, "new message", visibilityTimeout);
// END: readme-sample-updateMessage
}
public void peekAtMessage() {
// BEGIN: readme-sample-peekAtMessage
String queueURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).queueName("myqueue")
.buildClient();
// @param key: The key with which the specified value should be associated.
// @param value: The value to be associated with the specified key.
queueClient.peekMessages(5, Duration.ofSeconds(1), new Context(key, value)).forEach(message ->
System.out.println(message.getBody().toString()));
// END: readme-sample-peekAtMessage
}
public void receiveMessageFromQueue() {
// BEGIN: readme-sample-receiveMessageFromQueue
String queueURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).queueName("myqueue")
.buildClient();
// Try to receive 10 messages: Maximum number of messages to get
queueClient.receiveMessages(10).forEach(message ->
System.out.println(message.getBody().toString()));
// END: readme-sample-receiveMessageFromQueue
}
public void deleteMessageFromQueue() {
// BEGIN: readme-sample-deleteMessageFromQueue
String queueURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).queueName("myqueue")
.buildClient();
queueClient.deleteMessage(messageId, popReceipt);
// END: readme-sample-deleteMessageFromQueue
}
public void getQueueProperties() {
// BEGIN: readme-sample-getQueueProperties
String queueURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).queueName("myqueue")
.buildClient();
QueueProperties properties = queueClient.getProperties();
// END: readme-sample-getQueueProperties
}
public void setQueueMetadata() {
// BEGIN: readme-sample-setQueueMetadata
String queueURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).queueName("myqueue")
.buildClient();
Map<String, String> metadata = new HashMap<>();
metadata.put("key1", "val1");
metadata.put("key2", "val2");
queueClient.setMetadata(metadata);
// END: readme-sample-setQueueMetadata
}
}
| [
"\"AZURE_STORAGE_ACCOUNT_NAME\"",
"\"PRIMARY_SAS_TOKEN\""
]
| []
| [
"PRIMARY_SAS_TOKEN",
"AZURE_STORAGE_ACCOUNT_NAME"
]
| [] | ["PRIMARY_SAS_TOKEN", "AZURE_STORAGE_ACCOUNT_NAME"] | java | 2 | 0 | |
vendor/github.com/Azure/azure-sdk-for-go/services/cosmos-db/mgmt/2015-04-08/documentdb/collectionpartition.go | package documentdb
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"github.com/Azure/go-autorest/tracing"
"net/http"
)
// CollectionPartitionClient is the azure Cosmos DB Database Service Resource Provider REST API
type CollectionPartitionClient struct {
BaseClient
}
// NewCollectionPartitionClient creates an instance of the CollectionPartitionClient client.
func NewCollectionPartitionClient(subscriptionID string) CollectionPartitionClient {
return NewCollectionPartitionClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewCollectionPartitionClientWithBaseURI creates an instance of the CollectionPartitionClient client.
func NewCollectionPartitionClientWithBaseURI(baseURI string, subscriptionID string) CollectionPartitionClient {
return CollectionPartitionClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// ListMetrics retrieves the metrics determined by the given filter for the given collection, split by partition.
// Parameters:
// resourceGroupName - name of an Azure resource group.
// accountName - cosmos DB database account name.
// databaseRid - cosmos DB database rid.
// collectionRid - cosmos DB collection rid.
// filter - an OData filter expression that describes a subset of metrics to return. The parameters that can be
// filtered are name.value (name of the metric, can have an or of multiple names), startTime, endTime, and
// timeGrain. The supported operator is eq.
func (client CollectionPartitionClient) ListMetrics(ctx context.Context, resourceGroupName string, accountName string, databaseRid string, collectionRid string, filter string) (result PartitionMetricListResult, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/CollectionPartitionClient.ListMetrics")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}},
{TargetValue: accountName,
Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil},
{Target: "accountName", Name: validation.Pattern, Rule: `^[a-z0-9]+(-[a-z0-9]+)*`, Chain: nil}}}}); err != nil {
return result, validation.NewError("documentdb.CollectionPartitionClient", "ListMetrics", err.Error())
}
req, err := client.ListMetricsPreparer(ctx, resourceGroupName, accountName, databaseRid, collectionRid, filter)
if err != nil {
err = autorest.NewErrorWithError(err, "documentdb.CollectionPartitionClient", "ListMetrics", nil, "Failure preparing request")
return
}
resp, err := client.ListMetricsSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "documentdb.CollectionPartitionClient", "ListMetrics", resp, "Failure sending request")
return
}
result, err = client.ListMetricsResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "documentdb.CollectionPartitionClient", "ListMetrics", resp, "Failure responding to request")
}
return
}
// ListMetricsPreparer prepares the ListMetrics request.
func (client CollectionPartitionClient) ListMetricsPreparer(ctx context.Context, resourceGroupName string, accountName string, databaseRid string, collectionRid string, filter string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"accountName": autorest.Encode("path", accountName),
"collectionRid": autorest.Encode("path", collectionRid),
"databaseRid": autorest.Encode("path", databaseRid),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2015-04-08"
queryParameters := map[string]interface{}{
"$filter": autorest.Encode("query", filter),
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/databases/{databaseRid}/collections/{collectionRid}/partitions/metrics", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListMetricsSender sends the ListMetrics request. The method will close the
// http.Response Body if it receives an error.
func (client CollectionPartitionClient) ListMetricsSender(req *http.Request) (*http.Response, error) {
sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client))
return autorest.SendWithSender(client, req, sd...)
}
// ListMetricsResponder handles the response to the ListMetrics request. The method always
// closes the http.Response Body.
func (client CollectionPartitionClient) ListMetricsResponder(resp *http.Response) (result PartitionMetricListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListUsages retrieves the usages (most recent storage data) for the given collection, split by partition.
// Parameters:
// resourceGroupName - name of an Azure resource group.
// accountName - cosmos DB database account name.
// databaseRid - cosmos DB database rid.
// collectionRid - cosmos DB collection rid.
// filter - an OData filter expression that describes a subset of usages to return. The supported parameter is
// name.value (name of the metric, can have an or of multiple names).
func (client CollectionPartitionClient) ListUsages(ctx context.Context, resourceGroupName string, accountName string, databaseRid string, collectionRid string, filter string) (result PartitionUsagesResult, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/CollectionPartitionClient.ListUsages")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}},
{TargetValue: accountName,
Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil},
{Target: "accountName", Name: validation.Pattern, Rule: `^[a-z0-9]+(-[a-z0-9]+)*`, Chain: nil}}}}); err != nil {
return result, validation.NewError("documentdb.CollectionPartitionClient", "ListUsages", err.Error())
}
req, err := client.ListUsagesPreparer(ctx, resourceGroupName, accountName, databaseRid, collectionRid, filter)
if err != nil {
err = autorest.NewErrorWithError(err, "documentdb.CollectionPartitionClient", "ListUsages", nil, "Failure preparing request")
return
}
resp, err := client.ListUsagesSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "documentdb.CollectionPartitionClient", "ListUsages", resp, "Failure sending request")
return
}
result, err = client.ListUsagesResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "documentdb.CollectionPartitionClient", "ListUsages", resp, "Failure responding to request")
}
return
}
// ListUsagesPreparer prepares the ListUsages request.
func (client CollectionPartitionClient) ListUsagesPreparer(ctx context.Context, resourceGroupName string, accountName string, databaseRid string, collectionRid string, filter string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"accountName": autorest.Encode("path", accountName),
"collectionRid": autorest.Encode("path", collectionRid),
"databaseRid": autorest.Encode("path", databaseRid),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2015-04-08"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
if len(filter) > 0 {
queryParameters["$filter"] = autorest.Encode("query", filter)
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/databases/{databaseRid}/collections/{collectionRid}/partitions/usages", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListUsagesSender sends the ListUsages request. The method will close the
// http.Response Body if it receives an error.
func (client CollectionPartitionClient) ListUsagesSender(req *http.Request) (*http.Response, error) {
sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client))
return autorest.SendWithSender(client, req, sd...)
}
// ListUsagesResponder handles the response to the ListUsages request. The method always
// closes the http.Response Body.
func (client CollectionPartitionClient) ListUsagesResponder(resp *http.Response) (result PartitionUsagesResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
| []
| []
| []
| [] | [] | go | null | null | null |
plugins/logs/src/commands/commands.go | package main
import (
"flag"
"fmt"
"os"
"strconv"
"strings"
"github.com/dokku/dokku/plugins/common"
"github.com/dokku/dokku/plugins/logs"
)
const (
helpHeader = `Usage: dokku logs[:COMMAND]
Manage log integration for an app
Additional commands:`
helpContent = `
logs [-h] [-t] [-n num] [-q] [-p process] <app>, Display recent log output
logs:failed [<app>], Shows the last failed deploy logs
`
)
func main() {
flag.Usage = usage
flag.Parse()
cmd := flag.Arg(0)
switch cmd {
case "logs":
args := flag.NewFlagSet("logs", flag.ExitOnError)
var num int64
var ps string
var tail bool
var quiet bool
help := args.Bool("h", false, "-h: print help for the command")
args.Int64Var(&num, "n", 0, "-n: the number of lines to display")
args.Int64Var(&num, "num", 0, "--num: the number of lines to display")
args.StringVar(&ps, "p", "", "-p: only display logs from the given process")
args.StringVar(&ps, "ps", "", "--p: only display logs from the given process")
args.BoolVar(&tail, "t", true, "-t: continually stream logs")
args.BoolVar(&tail, "tail", true, "--tail: continually stream logs")
args.BoolVar(&quiet, "q", true, "-q: display raw logs without colors, time and names")
args.BoolVar(&quiet, "quiet", true, "--quiet: display raw logs without colors, time and names")
args.Parse(flag.Args()[1:])
if *help {
usage()
return
}
appName := args.Arg(0)
err := logs.CommandDefault(appName, num, ps, tail, quiet)
if err != nil {
common.LogFail(err.Error())
}
case "logs:help":
usage()
case "help":
command := common.NewShellCmd(fmt.Sprintf("ps -o command= %d", os.Getppid()))
command.ShowOutput = false
output, err := command.Output()
if err == nil && strings.Contains(string(output), "--all") {
fmt.Println(helpContent)
} else {
fmt.Print("\n logs, Manage log integration for an app\n")
}
default:
dokkuNotImplementExitCode, err := strconv.Atoi(os.Getenv("DOKKU_NOT_IMPLEMENTED_EXIT"))
if err != nil {
fmt.Println("failed to retrieve DOKKU_NOT_IMPLEMENTED_EXIT environment variable")
dokkuNotImplementExitCode = 10
}
os.Exit(dokkuNotImplementExitCode)
}
}
func usage() {
common.CommandUsage(helpHeader, helpContent)
}
| [
"\"DOKKU_NOT_IMPLEMENTED_EXIT\""
]
| []
| [
"DOKKU_NOT_IMPLEMENTED_EXIT"
]
| [] | ["DOKKU_NOT_IMPLEMENTED_EXIT"] | go | 1 | 0 | |
spring-core/src/test/java/org/springframework/core/env/StandardEnvironmentTests.java | /*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.env;
import java.lang.reflect.Field;
import java.security.AccessControlException;
import java.security.Permission;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.core.SpringProperties;
import org.springframework.mock.env.MockPropertySource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.springframework.core.env.AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME;
import static org.springframework.core.env.AbstractEnvironment.DEFAULT_PROFILES_PROPERTY_NAME;
import static org.springframework.core.env.AbstractEnvironment.RESERVED_DEFAULT_PROFILE_NAME;
/**
* Unit tests for {@link StandardEnvironment}.
*
* @author Chris Beams
* @author Juergen Hoeller
*/
@SuppressWarnings("deprecation")
public class StandardEnvironmentTests {
private static final String ALLOWED_PROPERTY_NAME = "theanswer";
private static final String ALLOWED_PROPERTY_VALUE = "42";
private static final String DISALLOWED_PROPERTY_NAME = "verboten";
private static final String DISALLOWED_PROPERTY_VALUE = "secret";
private static final String STRING_PROPERTY_NAME = "stringPropName";
private static final String STRING_PROPERTY_VALUE = "stringPropValue";
private static final Object NON_STRING_PROPERTY_NAME = new Object();
private static final Object NON_STRING_PROPERTY_VALUE = new Object();
private final ConfigurableEnvironment environment = new StandardEnvironment();
@Test
void merge() {
ConfigurableEnvironment child = new StandardEnvironment();
child.setActiveProfiles("c1", "c2");
child.getPropertySources().addLast(
new MockPropertySource("childMock")
.withProperty("childKey", "childVal")
.withProperty("bothKey", "childBothVal"));
ConfigurableEnvironment parent = new StandardEnvironment();
parent.setActiveProfiles("p1", "p2");
parent.getPropertySources().addLast(
new MockPropertySource("parentMock")
.withProperty("parentKey", "parentVal")
.withProperty("bothKey", "parentBothVal"));
assertThat(child.getProperty("childKey")).isEqualTo("childVal");
assertThat(child.getProperty("parentKey")).isNull();
assertThat(child.getProperty("bothKey")).isEqualTo("childBothVal");
assertThat(parent.getProperty("childKey")).isNull();
assertThat(parent.getProperty("parentKey")).isEqualTo("parentVal");
assertThat(parent.getProperty("bothKey")).isEqualTo("parentBothVal");
assertThat(child.getActiveProfiles()).isEqualTo(new String[]{"c1","c2"});
assertThat(parent.getActiveProfiles()).isEqualTo(new String[]{"p1","p2"});
child.merge(parent);
assertThat(child.getProperty("childKey")).isEqualTo("childVal");
assertThat(child.getProperty("parentKey")).isEqualTo("parentVal");
assertThat(child.getProperty("bothKey")).isEqualTo("childBothVal");
assertThat(parent.getProperty("childKey")).isNull();
assertThat(parent.getProperty("parentKey")).isEqualTo("parentVal");
assertThat(parent.getProperty("bothKey")).isEqualTo("parentBothVal");
assertThat(child.getActiveProfiles()).isEqualTo(new String[]{"c1","c2","p1","p2"});
assertThat(parent.getActiveProfiles()).isEqualTo(new String[]{"p1","p2"});
}
@Test
void propertySourceOrder() {
ConfigurableEnvironment env = new StandardEnvironment();
MutablePropertySources sources = env.getPropertySources();
assertThat(sources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME))).isEqualTo(0);
assertThat(sources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME))).isEqualTo(1);
assertThat(sources).hasSize(2);
}
@Test
void propertySourceTypes() {
ConfigurableEnvironment env = new StandardEnvironment();
MutablePropertySources sources = env.getPropertySources();
assertThat(sources.get(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)).isInstanceOf(SystemEnvironmentPropertySource.class);
}
@Test
void activeProfilesIsEmptyByDefault() {
assertThat(environment.getActiveProfiles().length).isEqualTo(0);
}
@Test
void defaultProfilesContainsDefaultProfileByDefault() {
assertThat(environment.getDefaultProfiles().length).isEqualTo(1);
assertThat(environment.getDefaultProfiles()[0]).isEqualTo("default");
}
@Test
void setActiveProfiles() {
environment.setActiveProfiles("local", "embedded");
String[] activeProfiles = environment.getActiveProfiles();
assertThat(activeProfiles).contains("local", "embedded");
assertThat(activeProfiles.length).isEqualTo(2);
}
@Test
void setActiveProfiles_withNullProfileArray() {
assertThatIllegalArgumentException().isThrownBy(() ->
environment.setActiveProfiles((String[]) null));
}
@Test
void setActiveProfiles_withNullProfile() {
assertThatIllegalArgumentException().isThrownBy(() ->
environment.setActiveProfiles((String) null));
}
@Test
void setActiveProfiles_withEmptyProfile() {
assertThatIllegalArgumentException().isThrownBy(() ->
environment.setActiveProfiles(""));
}
@Test
void setActiveProfiles_withNotOperator() {
assertThatIllegalArgumentException().isThrownBy(() ->
environment.setActiveProfiles("p1", "!p2"));
}
@Test
void setDefaultProfiles_withNullProfileArray() {
assertThatIllegalArgumentException().isThrownBy(() ->
environment.setDefaultProfiles((String[]) null));
}
@Test
void setDefaultProfiles_withNullProfile() {
assertThatIllegalArgumentException().isThrownBy(() ->
environment.setDefaultProfiles((String) null));
}
@Test
void setDefaultProfiles_withEmptyProfile() {
assertThatIllegalArgumentException().isThrownBy(() ->
environment.setDefaultProfiles(""));
}
@Test
void setDefaultProfiles_withNotOperator() {
assertThatIllegalArgumentException().isThrownBy(() ->
environment.setDefaultProfiles("d1", "!d2"));
}
@Test
void addActiveProfile() {
assertThat(environment.getActiveProfiles().length).isEqualTo(0);
environment.setActiveProfiles("local", "embedded");
assertThat(environment.getActiveProfiles()).contains("local", "embedded");
assertThat(environment.getActiveProfiles().length).isEqualTo(2);
environment.addActiveProfile("p1");
assertThat(environment.getActiveProfiles()).contains("p1");
assertThat(environment.getActiveProfiles().length).isEqualTo(3);
environment.addActiveProfile("p2");
environment.addActiveProfile("p3");
assertThat(environment.getActiveProfiles()).contains("p2", "p3");
assertThat(environment.getActiveProfiles().length).isEqualTo(5);
}
@Test
void addActiveProfile_whenActiveProfilesPropertyIsAlreadySet() {
ConfigurableEnvironment env = new StandardEnvironment();
assertThat(env.getProperty(ACTIVE_PROFILES_PROPERTY_NAME)).isNull();
env.getPropertySources().addFirst(new MockPropertySource().withProperty(ACTIVE_PROFILES_PROPERTY_NAME, "p1"));
assertThat(env.getProperty(ACTIVE_PROFILES_PROPERTY_NAME)).isEqualTo("p1");
env.addActiveProfile("p2");
assertThat(env.getActiveProfiles()).contains("p1", "p2");
}
@Test
void reservedDefaultProfile() {
assertThat(environment.getDefaultProfiles()).isEqualTo(new String[]{RESERVED_DEFAULT_PROFILE_NAME});
System.setProperty(DEFAULT_PROFILES_PROPERTY_NAME, "d0");
assertThat(environment.getDefaultProfiles()).isEqualTo(new String[]{"d0"});
environment.setDefaultProfiles("d1", "d2");
assertThat(environment.getDefaultProfiles()).isEqualTo(new String[]{"d1","d2"});
System.getProperties().remove(DEFAULT_PROFILES_PROPERTY_NAME);
}
@Test
void defaultProfileWithCircularPlaceholder() {
System.setProperty(DEFAULT_PROFILES_PROPERTY_NAME, "${spring.profiles.default}");
try {
assertThatIllegalArgumentException().isThrownBy(() ->
environment.getDefaultProfiles());
}
finally {
System.getProperties().remove(DEFAULT_PROFILES_PROPERTY_NAME);
}
}
@Test
void getActiveProfiles_systemPropertiesEmpty() {
assertThat(environment.getActiveProfiles().length).isEqualTo(0);
System.setProperty(ACTIVE_PROFILES_PROPERTY_NAME, "");
assertThat(environment.getActiveProfiles().length).isEqualTo(0);
System.getProperties().remove(ACTIVE_PROFILES_PROPERTY_NAME);
}
@Test
void getActiveProfiles_fromSystemProperties() {
System.setProperty(ACTIVE_PROFILES_PROPERTY_NAME, "foo");
assertThat(Arrays.asList(environment.getActiveProfiles())).contains("foo");
System.getProperties().remove(ACTIVE_PROFILES_PROPERTY_NAME);
}
@Test
void getActiveProfiles_fromSystemProperties_withMultipleProfiles() {
System.setProperty(ACTIVE_PROFILES_PROPERTY_NAME, "foo,bar");
assertThat(environment.getActiveProfiles()).contains("foo", "bar");
System.getProperties().remove(ACTIVE_PROFILES_PROPERTY_NAME);
}
@Test
void getActiveProfiles_fromSystemProperties_withMulitpleProfiles_withWhitespace() {
System.setProperty(ACTIVE_PROFILES_PROPERTY_NAME, " bar , baz "); // notice whitespace
assertThat(environment.getActiveProfiles()).contains("bar", "baz");
System.getProperties().remove(ACTIVE_PROFILES_PROPERTY_NAME);
}
@Test
void getDefaultProfiles() {
assertThat(environment.getDefaultProfiles()).isEqualTo(new String[] {RESERVED_DEFAULT_PROFILE_NAME});
environment.getPropertySources().addFirst(new MockPropertySource().withProperty(DEFAULT_PROFILES_PROPERTY_NAME, "pd1"));
assertThat(environment.getDefaultProfiles().length).isEqualTo(1);
assertThat(Arrays.asList(environment.getDefaultProfiles())).contains("pd1");
}
@Test
void setDefaultProfiles() {
environment.setDefaultProfiles();
assertThat(environment.getDefaultProfiles().length).isEqualTo(0);
environment.setDefaultProfiles("pd1");
assertThat(Arrays.asList(environment.getDefaultProfiles())).contains("pd1");
environment.setDefaultProfiles("pd2", "pd3");
assertThat(environment.getDefaultProfiles()).doesNotContain("pd1");
assertThat(environment.getDefaultProfiles()).contains("pd2", "pd3");
}
@Test
void acceptsProfiles_withEmptyArgumentList() {
assertThatIllegalArgumentException().isThrownBy(
environment::acceptsProfiles);
}
@Test
void acceptsProfiles_withNullArgumentList() {
assertThatIllegalArgumentException().isThrownBy(() ->
environment.acceptsProfiles((String[]) null));
}
@Test
void acceptsProfiles_withNullArgument() {
assertThatIllegalArgumentException().isThrownBy(() ->
environment.acceptsProfiles((String) null));
}
@Test
void acceptsProfiles_withEmptyArgument() {
assertThatIllegalArgumentException().isThrownBy(() ->
environment.acceptsProfiles(""));
}
@Test
void acceptsProfiles_activeProfileSetProgrammatically() {
assertThat(environment.acceptsProfiles("p1", "p2")).isFalse();
environment.setActiveProfiles("p1");
assertThat(environment.acceptsProfiles("p1", "p2")).isTrue();
environment.setActiveProfiles("p2");
assertThat(environment.acceptsProfiles("p1", "p2")).isTrue();
environment.setActiveProfiles("p1", "p2");
assertThat(environment.acceptsProfiles("p1", "p2")).isTrue();
}
@Test
void acceptsProfiles_activeProfileSetViaProperty() {
assertThat(environment.acceptsProfiles("p1")).isFalse();
environment.getPropertySources().addFirst(new MockPropertySource().withProperty(ACTIVE_PROFILES_PROPERTY_NAME, "p1"));
assertThat(environment.acceptsProfiles("p1")).isTrue();
}
@Test
void acceptsProfiles_defaultProfile() {
assertThat(environment.acceptsProfiles("pd")).isFalse();
environment.setDefaultProfiles("pd");
assertThat(environment.acceptsProfiles("pd")).isTrue();
environment.setActiveProfiles("p1");
assertThat(environment.acceptsProfiles("pd")).isFalse();
assertThat(environment.acceptsProfiles("p1")).isTrue();
}
@Test
void acceptsProfiles_withNotOperator() {
assertThat(environment.acceptsProfiles("p1")).isFalse();
assertThat(environment.acceptsProfiles("!p1")).isTrue();
environment.addActiveProfile("p1");
assertThat(environment.acceptsProfiles("p1")).isTrue();
assertThat(environment.acceptsProfiles("!p1")).isFalse();
}
@Test
void acceptsProfiles_withInvalidNotOperator() {
assertThatIllegalArgumentException().isThrownBy(() ->
environment.acceptsProfiles("p1", "!"));
}
@Test
void acceptsProfiles_withProfileExpression() {
assertThat(environment.acceptsProfiles(Profiles.of("p1 & p2"))).isFalse();
environment.addActiveProfile("p1");
assertThat(environment.acceptsProfiles(Profiles.of("p1 & p2"))).isFalse();
environment.addActiveProfile("p2");
assertThat(environment.acceptsProfiles(Profiles.of("p1 & p2"))).isTrue();
}
@Test
void environmentSubclass_withCustomProfileValidation() {
ConfigurableEnvironment env = new AbstractEnvironment() {
@Override
protected void validateProfile(String profile) {
super.validateProfile(profile);
if (profile.contains("-")) {
throw new IllegalArgumentException(
"Invalid profile [" + profile + "]: must not contain dash character");
}
}
};
env.addActiveProfile("validProfile"); // succeeds
assertThatIllegalArgumentException().isThrownBy(() ->
env.addActiveProfile("invalid-profile"))
.withMessage("Invalid profile [invalid-profile]: must not contain dash character");
}
@Test
void suppressGetenvAccessThroughSystemProperty() {
System.setProperty("spring.getenv.ignore", "true");
assertThat(environment.getSystemEnvironment().isEmpty()).isTrue();
System.clearProperty("spring.getenv.ignore");
}
@Test
void suppressGetenvAccessThroughSpringProperty() {
SpringProperties.setProperty("spring.getenv.ignore", "true");
assertThat(environment.getSystemEnvironment().isEmpty()).isTrue();
SpringProperties.setProperty("spring.getenv.ignore", null);
}
@Test
void suppressGetenvAccessThroughSpringFlag() {
SpringProperties.setFlag("spring.getenv.ignore");
assertThat(environment.getSystemEnvironment().isEmpty()).isTrue();
SpringProperties.setProperty("spring.getenv.ignore", null);
}
@Test
void getSystemProperties_withAndWithoutSecurityManager() {
System.setProperty(ALLOWED_PROPERTY_NAME, ALLOWED_PROPERTY_VALUE);
System.setProperty(DISALLOWED_PROPERTY_NAME, DISALLOWED_PROPERTY_VALUE);
System.getProperties().put(STRING_PROPERTY_NAME, NON_STRING_PROPERTY_VALUE);
System.getProperties().put(NON_STRING_PROPERTY_NAME, STRING_PROPERTY_VALUE);
{
Map<?, ?> systemProperties = environment.getSystemProperties();
assertThat(systemProperties).isNotNull();
assertThat(System.getProperties()).isSameAs(systemProperties);
assertThat(systemProperties.get(ALLOWED_PROPERTY_NAME)).isEqualTo(ALLOWED_PROPERTY_VALUE);
assertThat(systemProperties.get(DISALLOWED_PROPERTY_NAME)).isEqualTo(DISALLOWED_PROPERTY_VALUE);
// non-string keys and values work fine... until the security manager is introduced below
assertThat(systemProperties.get(STRING_PROPERTY_NAME)).isEqualTo(NON_STRING_PROPERTY_VALUE);
assertThat(systemProperties.get(NON_STRING_PROPERTY_NAME)).isEqualTo(STRING_PROPERTY_VALUE);
}
SecurityManager oldSecurityManager = System.getSecurityManager();
SecurityManager securityManager = new SecurityManager() {
@Override
public void checkPropertiesAccess() {
// see https://download.oracle.com/javase/1.5.0/docs/api/java/lang/System.html#getProperties()
throw new AccessControlException("Accessing the system properties is disallowed");
}
@Override
public void checkPropertyAccess(String key) {
// see https://download.oracle.com/javase/1.5.0/docs/api/java/lang/System.html#getProperty(java.lang.String)
if (DISALLOWED_PROPERTY_NAME.equals(key)) {
throw new AccessControlException(
String.format("Accessing the system property [%s] is disallowed", DISALLOWED_PROPERTY_NAME));
}
}
@Override
public void checkPermission(Permission perm) {
// allow everything else
}
};
System.setSecurityManager(securityManager);
{
Map<?, ?> systemProperties = environment.getSystemProperties();
assertThat(systemProperties).isNotNull();
assertThat(systemProperties).isInstanceOf(ReadOnlySystemAttributesMap.class);
assertThat((String)systemProperties.get(ALLOWED_PROPERTY_NAME)).isEqualTo(ALLOWED_PROPERTY_VALUE);
assertThat(systemProperties.get(DISALLOWED_PROPERTY_NAME)).isNull();
// nothing we can do here in terms of warning the user that there was
// actually a (non-string) value available. By this point, we only
// have access to calling System.getProperty(), which itself returns null
// if the value is non-string. So we're stuck with returning a potentially
// misleading null.
assertThat(systemProperties.get(STRING_PROPERTY_NAME)).isNull();
// in the case of a non-string *key*, however, we can do better. Alert
// the user that under these very special conditions (non-object key +
// SecurityManager that disallows access to system properties), they
// cannot do what they're attempting.
assertThatIllegalArgumentException().as("searching with non-string key against ReadOnlySystemAttributesMap").isThrownBy(() ->
systemProperties.get(NON_STRING_PROPERTY_NAME));
}
System.setSecurityManager(oldSecurityManager);
System.clearProperty(ALLOWED_PROPERTY_NAME);
System.clearProperty(DISALLOWED_PROPERTY_NAME);
System.getProperties().remove(STRING_PROPERTY_NAME);
System.getProperties().remove(NON_STRING_PROPERTY_NAME);
}
@Test
void getSystemEnvironment_withAndWithoutSecurityManager() {
getModifiableSystemEnvironment().put(ALLOWED_PROPERTY_NAME, ALLOWED_PROPERTY_VALUE);
getModifiableSystemEnvironment().put(DISALLOWED_PROPERTY_NAME, DISALLOWED_PROPERTY_VALUE);
{
Map<String, Object> systemEnvironment = environment.getSystemEnvironment();
assertThat(systemEnvironment).isNotNull();
assertThat(System.getenv()).isSameAs(systemEnvironment);
}
SecurityManager oldSecurityManager = System.getSecurityManager();
SecurityManager securityManager = new SecurityManager() {
@Override
public void checkPermission(Permission perm) {
//see https://download.oracle.com/javase/1.5.0/docs/api/java/lang/System.html#getenv()
if ("getenv.*".equals(perm.getName())) {
throw new AccessControlException("Accessing the system environment is disallowed");
}
//see https://download.oracle.com/javase/1.5.0/docs/api/java/lang/System.html#getenv(java.lang.String)
if (("getenv."+DISALLOWED_PROPERTY_NAME).equals(perm.getName())) {
throw new AccessControlException(
String.format("Accessing the system environment variable [%s] is disallowed", DISALLOWED_PROPERTY_NAME));
}
}
};
System.setSecurityManager(securityManager);
{
Map<String, Object> systemEnvironment = environment.getSystemEnvironment();
assertThat(systemEnvironment).isNotNull();
assertThat(systemEnvironment).isInstanceOf(ReadOnlySystemAttributesMap.class);
assertThat(systemEnvironment.get(ALLOWED_PROPERTY_NAME)).isEqualTo(ALLOWED_PROPERTY_VALUE);
assertThat(systemEnvironment.get(DISALLOWED_PROPERTY_NAME)).isNull();
}
System.setSecurityManager(oldSecurityManager);
getModifiableSystemEnvironment().remove(ALLOWED_PROPERTY_NAME);
getModifiableSystemEnvironment().remove(DISALLOWED_PROPERTY_NAME);
}
@SuppressWarnings("unchecked")
public static Map<String, String> getModifiableSystemEnvironment() {
// for os x / linux
Class<?>[] classes = Collections.class.getDeclaredClasses();
Map<String, String> env = System.getenv();
for (Class<?> cl : classes) {
if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
try {
Field field = cl.getDeclaredField("m");
field.setAccessible(true);
Object obj = field.get(env);
if (obj != null && obj.getClass().getName().equals("java.lang.ProcessEnvironment$StringEnvironment")) {
return (Map<String, String>) obj;
}
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
// for windows
Class<?> processEnvironmentClass;
try {
processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
}
catch (Exception ex) {
throw new IllegalStateException(ex);
}
try {
Field theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment");
theCaseInsensitiveEnvironmentField.setAccessible(true);
Object obj = theCaseInsensitiveEnvironmentField.get(null);
return (Map<String, String>) obj;
}
catch (NoSuchFieldException ex) {
// do nothing
}
catch (Exception ex) {
throw new IllegalStateException(ex);
}
try {
Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
theEnvironmentField.setAccessible(true);
Object obj = theEnvironmentField.get(null);
return (Map<String, String>) obj;
}
catch (NoSuchFieldException ex) {
// do nothing
}
catch (Exception ex) {
throw new IllegalStateException(ex);
}
throw new IllegalStateException();
}
}
| []
| []
| []
| [] | [] | java | 0 | 0 | |
mussels/recipe.py | """
Copyright (C) 2019-2020 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
This module provides the base class for every Recipe.
This includes the logic for how to perform a build and how to relocate (or "install")
select files to a directory structure where other recipes can find & depend on them.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import datetime
from distutils import dir_util
import glob
import inspect
from io import StringIO
import logging
import os
import platform
import shutil
import stat
import subprocess
import sys
import tarfile
import time
import zipfile
import requests
import urllib.request
import patch
from mussels.utils.versions import pick_platform, nvc_str
class BaseRecipe(object):
"""
Base class for Mussels recipe.
"""
name = "sample"
version = "1.2.3"
# Set collection to True if this is just a collection of recipes to build, and not an actual recipe.
# If True, only `dependencies` and `required_tools` matter. Everything else should be omited.
is_collection = False
url = "https://sample.com/sample.tar.gz" # URL of project release materials.
# archive_name_change is a tuple of strings to replace.
# For example:
# ("v", "nghttp2-")
# will change:
# v2.3.4 to nghttp2-2.3.4.
# This hack is necessary because archives with changed names will extract to their original directory name.
archive_name_change: tuple = ("", "")
platforms: dict = {} # Dictionary of recipe instructions for each platform.
builds: dict = {} # Dictionary of build paths.
module_file: str = ""
variables: dict = {} # variables that will be evaluated in build scripts
def __init__(
self,
toolchain: dict,
platform: str,
target: str,
install_dir: str = "",
data_dir: str = "",
work_dir: str = "",
log_dir: str = "",
download_dir: str = "",
log_level: str = "DEBUG",
):
"""
Download the archive (if necessary) to the Downloads directory.
Extract the archive to the temp directory so it is ready to build.
"""
self.toolchain = toolchain
self.platform = platform
self.target = target
if data_dir == "":
# No temp dir provided, build in the current working directory.
self.data_dir = os.getcwd()
else:
self.data_dir = os.path.abspath(data_dir)
self.install_dir = install_dir
if download_dir != "":
self.download_dir = download_dir
else:
self.download_dir = os.path.join(self.data_dir, "cache", "downloads")
if log_dir != "":
self.log_dir = log_dir
else:
self.log_dir = os.path.join(self.data_dir, "logs", "recipes")
if work_dir != "":
self.work_dir = work_dir
else:
self.work_dir = os.path.join(self.data_dir, "cache", "work")
self.module_dir = os.path.split(self.module_file)[0]
if "patches" in self.platforms[self.platform][self.target]:
self.patch_dir = os.path.join(
self.module_dir, self.platforms[self.platform][self.target]["patches"]
)
else:
self.patch_dir = ""
self._init_logging(log_level)
def _init_logging(self, level="DEBUG"):
"""
Initializes the logging parameters
"""
levels = {
"DEBUG": logging.DEBUG,
"INFO": logging.INFO,
"WARN": logging.WARNING,
"WARNING": logging.WARNING,
"ERROR": logging.ERROR,
}
os.makedirs(self.log_dir, exist_ok=True)
self.logger = logging.getLogger(f"{nvc_str(self.name, self.version)}")
formatter = logging.Formatter(
fmt="%(asctime)s - %(levelname)s: %(message)s",
datefmt="%m/%d/%Y %I:%M:%S %p",
)
self.log_file = os.path.join(
self.log_dir,
f"{nvc_str(self.name, self.version)}.{datetime.datetime.now()}.log".replace(
":", "_"
),
)
filehandler = logging.FileHandler(filename=self.log_file)
filehandler.setLevel(logging.DEBUG)
filehandler.setFormatter(formatter)
self.logger.addHandler(filehandler)
self.logger.setLevel(levels[os.environ.get("LOG_LEVEL", level)])
def _download_archive(self) -> bool:
"""
Use the URL to download the archive if it doesn't already exist in the Downloads directory.
"""
os.makedirs(self.download_dir, exist_ok=True)
# Determine download path from URL & possible archive name change.
self.archive = self.url.split("/")[-1]
if self.archive_name_change[0] != "":
self.archive = self.archive.replace(
self.archive_name_change[0], self.archive_name_change[1]
)
self.download_path = os.path.join(
self.download_dir, self.archive
)
# Exit early if we already have the archive.
if os.path.exists(self.download_path):
self.logger.debug(f"Archive already downloaded.")
return True
self.logger.info(f"Downloading {self.url}")
self.logger.info(f" to {self.download_path} ...")
if self.url.startswith("ftp"):
try:
urllib.request.urlretrieve(self.url, self.download_path)
except Exception as exc:
self.logger.info(f"Failed to download archive from {self.url}, {exc}!")
return False
else:
try:
r = requests.get(self.url)
with open(self.download_path, "wb") as f:
f.write(r.content)
except Exception:
self.logger.info(f"Failed to download archive from {self.url}!")
return False
return True
def _extract_archive(self, rebuild: bool) -> bool:
"""
Extract the archive found in Downloads directory, if necessary.
"""
if self.archive.endswith(".tar.gz"):
self.builds[self.target] = os.path.join(
self.work_dir, self.target, f"{self.archive[:-len('.tar.gz')]}"
)
elif self.archive.endswith(".zip"):
self.builds[self.target] = os.path.join(
self.work_dir, self.target, f"{self.archive[:-len('.zip')]}"
)
else:
self.logger.error(
f"Unexpected archive extension. Currently only supports .tar.gz and .zip!"
)
return False
self.prior_build_exists = os.path.exists(self.builds[self.target])
if self.prior_build_exists:
if not rebuild:
# Build directory already exists. We're good.
return True
# Remove previous built, start over.
self.logger.info(
f"--rebuild: Removing previous {self.target} build directory:"
)
self.logger.info(f" {self.builds[self.target]}")
shutil.rmtree(self.builds[self.target])
self.prior_build_exists = False
os.makedirs(os.path.join(self.work_dir, self.target), exist_ok=True)
# Make our own copy of the extracted source so we don't dirty the original.
self.logger.debug(f"Preparing {self.target} build directory:")
self.logger.debug(f" {self.builds[self.target]}")
if self.archive.endswith(".tar.gz"):
# Un-tar
self.logger.info(
f"Extracting tarball archive {self.archive} to {self.builds[self.target]} ..."
)
tar = tarfile.open(self.download_path, "r:gz")
tar.extractall(os.path.join(self.work_dir, self.target))
tar.close()
elif self.archive.endswith(".zip"):
# Un-zip
self.logger.info(
f"Extracting zip archive {self.archive} to {self.builds[self.target]} ..."
)
zip_ref = zipfile.ZipFile(self.download_path, "r")
zip_ref.extractall(os.path.join(self.work_dir, self.target))
zip_ref.close()
return True
def _run_script(self, target, name, script) -> bool:
"""
Run a script in the current working directory.
"""
# Create a build script.
if platform.system() == "Windows":
script_name = f"_{name}.bat"
newline = "\r\n"
else:
script_name = f"_{name}.sh"
newline = "\n"
with open(os.path.join(os.getcwd(), script_name), "w", newline=newline) as fd:
# Evaluate "".format() syntax in the build script
script = script.format(**self.variables)
# Write the build commands to a file
build_lines = script.splitlines()
for line in build_lines:
line = line.strip()
if platform.system() == "Windows" and line.endswith("\\"):
fd.write(line.rstrip("\\") + " ")
else:
fd.write(line + "\n")
if platform.system() != "Windows":
st = os.stat(script_name)
os.chmod(script_name, st.st_mode | stat.S_IEXEC)
# Run the build script.
process = subprocess.Popen(
os.path.join(os.getcwd(), script_name),
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
with process.stdout:
for line in iter(process.stdout.readline, b""):
self.logger.debug(line.decode("utf-8", errors='replace').strip())
process.wait()
if process.returncode != 0:
self.logger.warning(
f"{nvc_str(self.name, self.version)} {target} build failed!"
)
self.logger.warning(f"Command:")
for line in script.splitlines():
self.logger.warning(line)
self.logger.warning(f"Exit code: {process.returncode}")
self.logger.error(f'"{name}" script failed for {target} build')
return False
return True
def build(self, rebuild: bool = False) -> bool:
"""
Patch source materials if not already patched.
Then, for each architecture, run the build commands if the output files don't already exist.
"""
if self.is_collection:
self.logger.debug(
f"Build completed for recipe collection {nvc_str(self.name, self.version)}"
)
return True
os.makedirs(self.work_dir, exist_ok=True)
# Download and build if necessary.
if not self._download_archive():
self.logger.error(
f"Failed to download source archive for {nvc_str(self.name, self.version)}"
)
return False
# Extract to the work_dir.
if not self._extract_archive(rebuild):
self.logger.error(
f"Failed to extract source archive for {nvc_str(self.name, self.version)}"
)
return False
if not os.path.isdir(self.patch_dir):
self.logger.debug(f"No patch directory found.")
else:
# Patches exists for this recipe.
self.logger.debug(
f"Patch directory found for {nvc_str(self.name, self.version)}."
)
if not os.path.exists(
os.path.join(self.builds[self.target], "_mussles.patched")
):
# Not yet patched. Apply patches.
self.logger.info(
f"Applying patches to {nvc_str(self.name, self.version)} ({self.target}) build directory ..."
)
for patchfile in os.listdir(self.patch_dir):
if patchfile.endswith(".diff") or patchfile.endswith(".patch"):
self.logger.info(f"Attempting to apply patch: {patchfile}")
pset = patch.fromfile(os.path.join(self.patch_dir, patchfile))
patched = pset.apply(1, root=self.builds[self.target])
if not patched:
self.logger.error(f"Patch failed!")
return False
else:
self.logger.info(
f"Copying new file {patchfile} to {nvc_str(self.name, self.version)} ({self.target}) build directory ..."
)
shutil.copyfile(
os.path.join(self.patch_dir, patchfile),
os.path.join(self.builds[self.target], patchfile),
)
with open(
os.path.join(self.builds[self.target], "_mussles.patched"), "w"
) as patchmark:
patchmark.write("patched")
build_scripts = self.platforms[self.platform][self.target]["build_script"]
self.logger.info(
f"Attempting to build {nvc_str(self.name, self.version)} for {self.target}"
)
self.variables["includes"] = os.path.join(self.install_dir, "include").replace("\\", "/")
self.variables["libs"] = os.path.join(self.install_dir, "lib").replace("\\", "/")
self.variables["install"] = os.path.join(self.install_dir).replace("\\", "/")
self.variables["build"] = os.path.join(self.builds[self.target]).replace("\\", "/")
self.variables["target"] = self.target
for tool in self.toolchain:
# Add each tool from the toolchain to the PATH environment variable.
if self.toolchain[tool].tool_path != "":
self.logger.debug(
f"Adding tool {tool} path {self.toolchain[tool].tool_path} to PATH"
)
os.environ["PATH"] = (
self.toolchain[tool].tool_path + os.pathsep + os.environ["PATH"]
)
# Collect tool variables for use in the build.
platform_options = self.toolchain[tool].platforms.keys()
matching_platform = pick_platform(platform.system(), platform_options)
if "variables" in self.toolchain[tool].platforms[matching_platform]:
# The following will allow us to format strings like "echo {tool.variable}"
tool_vars = lambda: None
for variable in self.toolchain[tool].platforms[matching_platform]["variables"]:
setattr(tool_vars, variable, self.toolchain[tool].platforms[matching_platform]["variables"][variable])
self.variables[tool] = tool_vars
cwd = os.getcwd()
os.chdir(self.builds[self.target])
if not self.prior_build_exists:
# Run "configure" script, if exists.
if "configure" in build_scripts.keys():
if not self._run_script(
self.target, "configure", build_scripts["configure"]
):
self.logger.error(
f"{nvc_str(self.name, self.version)} {self.target} build failed."
)
os.chdir(cwd)
return False
else:
os.chdir(self.builds[self.target])
# Run "make" script, if exists.
if "make" in build_scripts.keys():
if not self._run_script(self.target, "make", build_scripts["make"]):
self.logger.error(
f"{nvc_str(self.name, self.version)} {self.target} build failed."
)
os.chdir(cwd)
return False
# Run "install" script, if exists.
if "install" in build_scripts.keys():
if not self._run_script(self.target, "install", build_scripts["install"]):
self.logger.error(
f"{nvc_str(self.name, self.version)} {self.target} build failed."
)
os.chdir(cwd)
return False
self.logger.info(
f"{nvc_str(self.name, self.version)} {self.target} build succeeded."
)
os.chdir(cwd)
if not self._install():
return False
return True
def _install(self):
"""
Copy the headers and libs to an install directory.
"""
os.makedirs(self.install_dir, exist_ok=True)
self.logger.info(
f"Copying {nvc_str(self.name, self.version)} install files to: {self.install_dir}."
)
if 'install_paths' not in self.platforms[self.platform][self.target]:
self.logger.info(
f"{nvc_str(self.name, self.version)} {self.target} nothing additional to install."
)
else:
install_paths = self.platforms[self.platform][self.target]["install_paths"]
for install_path in install_paths:
for install_item in install_paths[install_path]:
item_installed = False
src_path = os.path.join(self.builds[self.target], install_item)
for src_filepath in glob.glob(src_path):
dst_path = os.path.join(
self.install_dir, install_path, os.path.basename(src_filepath)
)
# Remove prior installation, if exists.
if os.path.isdir(dst_path):
shutil.rmtree(dst_path)
elif os.path.isfile(dst_path):
os.remove(dst_path)
# Create the target install paths, if it doesn't already exist.
os.makedirs(os.path.split(dst_path)[0], exist_ok=True)
self.logger.debug(f"Copying: {src_filepath}")
self.logger.debug(f" to: {dst_path}")
# Now copy the file or directory.
if os.path.isdir(src_filepath):
dir_util.copy_tree(src_filepath, dst_path)
else:
shutil.copyfile(src_filepath, dst_path)
item_installed = True
# Globbing only shows us files that actually exists.
# It's possible we didn't install anything at all.
# Verify that we installed at least one item.
if not item_installed:
self.logger.error(
f"Required target install files do not exist: {src_path}"
)
return False
self.logger.info(
f"{nvc_str(self.name, self.version)} {self.target} install succeeded."
)
return True
| []
| []
| [
"PATH",
"LOG_LEVEL"
]
| [] | ["PATH", "LOG_LEVEL"] | python | 2 | 0 | |
noxfile.py | """Nox sessions."""
import shutil
import sys
from pathlib import Path
from textwrap import dedent
import nox
try:
from nox_poetry import Session
from nox_poetry import session
except ImportError:
message = f"""\
Nox failed to import the 'nox-poetry' package.
Please install it using the following command:
{sys.executable} -m pip install nox-poetry"""
raise SystemExit(dedent(message))
package = "conjurscenarios"
python_versions = ["3.9", "3.8", "3.7", "3.6"]
nox.needs_version = ">= 2021.6.6"
nox.options.sessions = (
"pre-commit",
"safety",
"mypy",
"tests",
"typeguard",
"xdoctest",
"docs-build",
)
def activate_virtualenv_in_precommit_hooks(session: Session) -> None:
"""Activate virtualenv in hooks installed by pre-commit.
This function patches git hooks installed by pre-commit to activate the
session's virtual environment. This allows pre-commit to locate hooks in
that environment when invoked from git.
Args:
session: The Session object.
"""
if session.bin is None:
return
virtualenv = session.env.get("VIRTUAL_ENV")
if virtualenv is None:
return
hookdir = Path(".git") / "hooks"
if not hookdir.is_dir():
return
for hook in hookdir.iterdir():
if hook.name.endswith(".sample") or not hook.is_file():
continue
text = hook.read_text()
bindir = repr(session.bin)[1:-1] # strip quotes
if not (
Path("A") == Path("a") and bindir.lower() in text.lower() or bindir in text
):
continue
lines = text.splitlines()
if not (lines[0].startswith("#!") and "python" in lines[0].lower()):
continue
header = dedent(
f"""\
import os
os.environ["VIRTUAL_ENV"] = {virtualenv!r}
os.environ["PATH"] = os.pathsep.join((
{session.bin!r},
os.environ.get("PATH", ""),
))
"""
)
lines.insert(1, header)
hook.write_text("\n".join(lines))
@session(name="pre-commit", python="3.9")
def precommit(session: Session) -> None:
"""Lint using pre-commit."""
args = session.posargs or ["run", "--all-files", "--show-diff-on-failure"]
session.install(
"black",
"darglint",
"flake8",
"flake8-bandit",
"flake8-bugbear",
"flake8-docstrings",
"flake8-rst-docstrings",
"pep8-naming",
"pre-commit",
"pre-commit-hooks",
"reorder-python-imports",
)
session.run("pre-commit", *args)
if args and args[0] == "install":
activate_virtualenv_in_precommit_hooks(session)
@session(python="3.9")
def safety(session: Session) -> None:
"""Scan dependencies for insecure packages."""
requirements = session.poetry.export_requirements()
session.install("safety")
session.run("safety", "check", "--full-report", f"--file={requirements}")
@session(python=python_versions)
def mypy(session: Session) -> None:
"""Type-check using mypy."""
args = session.posargs or ["src", "tests", "docs/conf.py"]
session.install(".")
session.install("mypy", "pytest")
session.run("mypy", *args)
if not session.posargs:
session.run("mypy", f"--python-executable={sys.executable}", "noxfile.py")
@session(python=python_versions)
def tests(session: Session) -> None:
"""Run the test suite."""
session.install(".")
session.install("coverage[toml]", "pytest", "pygments")
try:
session.run("coverage", "run", "--parallel", "-m", "pytest", *session.posargs)
finally:
if session.interactive:
session.notify("coverage", posargs=[])
@session
def coverage(session: Session) -> None:
"""Produce the coverage report."""
args = session.posargs or ["report"]
session.install("coverage[toml]")
if not session.posargs and any(Path().glob(".coverage.*")):
session.run("coverage", "combine")
session.run("coverage", *args)
@session(python=python_versions)
def typeguard(session: Session) -> None:
"""Runtime type checking using Typeguard."""
session.install(".")
session.install("pytest", "typeguard", "pygments")
session.run("pytest", f"--typeguard-packages={package}", *session.posargs)
@session(python=python_versions)
def xdoctest(session: Session) -> None:
"""Run examples with xdoctest."""
args = session.posargs or ["all"]
session.install(".")
session.install("xdoctest[colors]")
session.run("python", "-m", "xdoctest", package, *args)
@session(name="docs-build", python="3.9")
def docs_build(session: Session) -> None:
"""Build the documentation."""
args = session.posargs or ["docs", "docs/_build"]
session.install(".")
session.install("sphinx", "sphinx-click", "sphinx-rtd-theme")
build_dir = Path("docs", "_build")
if build_dir.exists():
shutil.rmtree(build_dir)
session.run("sphinx-build", *args)
@session(python="3.9")
def docs(session: Session) -> None:
"""Build and serve the documentation with live reloading on file changes."""
args = session.posargs or ["--open-browser", "docs", "docs/_build"]
session.install(".")
session.install("sphinx", "sphinx-autobuild", "sphinx-click", "sphinx-rtd-theme")
build_dir = Path("docs", "_build")
if build_dir.exists():
shutil.rmtree(build_dir)
session.run("sphinx-autobuild", *args)
| []
| []
| [
"VIRTUAL_ENV",
"PATH"
]
| [] | ["VIRTUAL_ENV", "PATH"] | python | 2 | 0 | |
infra/terraform/modules/tflite_converter_function/function_code/main.py | import tensorflow as tf
from google.cloud import storage
from flask import abort
import os
from pathlib import Path
def model_converter(request):
saved_model_dir_gcs = ""
saved_model_dir_local = "/tmp"
project_name = ""
email = ""
if request.method == 'POST':
request_json = request.get_json(silent=True)
if request_json and 'saved_model_dir_gcs' in request_json and 'project_name' in request_json and 'email' in request_json:
saved_model_dir_gcs = request_json['saved_model_dir_gcs']
project_name = request_json['project_name']
email = request_json['email']
# Downloading the SavedModel
storage_client = storage.Client()
source_bucket = os.getenv('SOURCE_BUCKET')
tf_source_bucket = storage_client.bucket(source_bucket)
blobs = tf_source_bucket.list_blobs(prefix=email + "/" + project_name + "/" + saved_model_dir_gcs) # Get list of files
for blob in blobs:
file_split = blob.name.split("/")
directory = "/".join(file_split[0:-1])
Path("/tmp/" + directory).mkdir(parents=True, exist_ok=True)
blob.download_to_filename("/tmp/" + blob.name)
# Convert the model
converter = tf.lite.TFLiteConverter.from_saved_model("/tmp/" + email + "/" + project_name + "/" + saved_model_dir_gcs) # path to the SavedModel directory
tflite_model = converter.convert()
# Save the model.
with open(saved_model_dir_local + '/model.tflite', 'wb') as f:
f.write(tflite_model)
tflite_blob = tf_source_bucket.blob(email + "/" + project_name + "/model.tflite")
tflite_blob.upload_from_filename(saved_model_dir_local + '/model.tflite')
else:
return abort(405) | []
| []
| [
"SOURCE_BUCKET"
]
| [] | ["SOURCE_BUCKET"] | python | 1 | 0 | |
.mvn/wrapper/MavenWrapperDownloader.java | /*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
@SuppressWarnings("all") //this is mvnw autogenerated code - supress all warnings
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.5";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
| [
"\"MVNW_USERNAME\"",
"\"MVNW_PASSWORD\"",
"\"MVNW_USERNAME\"",
"\"MVNW_PASSWORD\""
]
| []
| [
"MVNW_USERNAME",
"MVNW_PASSWORD"
]
| [] | ["MVNW_USERNAME", "MVNW_PASSWORD"] | java | 2 | 0 | |
pilot/pkg/config/kube/ingress/status.go | // Copyright Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ingress
import (
"context"
"net"
"sort"
"strings"
"time"
coreV1 "k8s.io/api/core/v1"
"k8s.io/api/networking/v1beta1"
metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/kubernetes"
listerv1 "k8s.io/client-go/listers/core/v1"
listerv1beta1 "k8s.io/client-go/listers/networking/v1beta1"
meshconfig "istio.io/api/mesh/v1alpha1"
"istio.io/istio/pilot/pkg/serviceregistry/kube"
kubelib "istio.io/istio/pkg/kube"
"istio.io/istio/pkg/queue"
"istio.io/pkg/log"
)
const (
updateInterval = 60 * time.Second
)
// StatusSyncer keeps the status IP in each Ingress resource updated
type StatusSyncer struct {
client kubernetes.Interface
ingressClass string
defaultIngressClass string
// Name of service (ingressgateway default) to find the IP
ingressService string
queue queue.Instance
ingressLister listerv1beta1.IngressLister
podLister listerv1.PodLister
serviceLister listerv1.ServiceLister
nodeLister listerv1.NodeLister
}
// Run the syncer until stopCh is closed
func (s *StatusSyncer) Run(stopCh <-chan struct{}) {
go s.queue.Run(stopCh)
go s.runUpdateStatus(stopCh)
}
// NewStatusSyncer creates a new instance
func NewStatusSyncer(mesh *meshconfig.MeshConfig, client kubelib.Client) (*StatusSyncer, error) {
// we need to use the defined ingress class to allow multiple leaders
// in order to update information about ingress status
ingressClass, defaultIngressClass := convertIngressControllerMode(mesh.IngressControllerMode, mesh.IngressClass)
// queue requires a time duration for a retry delay after a handler error
q := queue.NewQueue(1 * time.Second)
st := StatusSyncer{
client: client,
ingressLister: client.KubeInformer().Networking().V1beta1().Ingresses().Lister(),
podLister: client.KubeInformer().Core().V1().Pods().Lister(),
serviceLister: client.KubeInformer().Core().V1().Services().Lister(),
nodeLister: client.KubeInformer().Core().V1().Nodes().Lister(),
queue: q,
ingressClass: ingressClass,
defaultIngressClass: defaultIngressClass,
ingressService: mesh.IngressService,
}
return &st, nil
}
func (s *StatusSyncer) onEvent() error {
addrs, err := s.runningAddresses(ingressNamespace)
if err != nil {
return err
}
return s.updateStatus(sliceToStatus(addrs))
}
func (s *StatusSyncer) runUpdateStatus(stop <-chan struct{}) {
if _, err := s.runningAddresses(ingressNamespace); err != nil {
log.Warna("Missing ingress, skip status updates")
err = wait.PollUntil(10*time.Second, func() (bool, error) {
if sa, err := s.runningAddresses(ingressNamespace); err != nil || len(sa) == 0 {
return false, nil
}
return true, nil
}, stop)
if err != nil {
log.Warna("Error waiting for ingress")
return
}
}
err := wait.PollUntil(updateInterval, func() (bool, error) {
s.queue.Push(s.onEvent)
return false, nil
}, stop)
if err != nil {
log.Errorf("Stop requested")
}
}
// updateStatus updates ingress status with the list of IP
func (s *StatusSyncer) updateStatus(status []coreV1.LoadBalancerIngress) error {
l, err := s.ingressLister.List(labels.Everything())
if err != nil {
return err
}
for _, currIng := range l {
if !classIsValid(currIng, s.ingressClass, s.defaultIngressClass) {
continue
}
curIPs := currIng.Status.LoadBalancer.Ingress
sort.SliceStable(status, lessLoadBalancerIngress(status))
sort.SliceStable(curIPs, lessLoadBalancerIngress(curIPs))
if ingressSliceEqual(status, curIPs) {
log.Debugf("skipping update of Ingress %v/%v (no change)", currIng.Namespace, currIng.Name)
return nil
}
currIng.Status.LoadBalancer.Ingress = status
_, err := s.client.NetworkingV1beta1().Ingresses(currIng.Namespace).UpdateStatus(context.TODO(), currIng, metaV1.UpdateOptions{})
if err != nil {
log.Warnf("error updating ingress status: %v", err)
}
}
return nil
}
// runningAddresses returns a list of IP addresses and/or FQDN where the
// ingress controller is currently running
func (s *StatusSyncer) runningAddresses(ingressNs string) ([]string, error) {
addrs := make([]string, 0)
if s.ingressService != "" {
svc, err := s.serviceLister.Services(ingressNs).Get(s.ingressService)
if err != nil {
return nil, err
}
if svc.Spec.Type == coreV1.ServiceTypeExternalName {
addrs = append(addrs, svc.Spec.ExternalName)
return addrs, nil
}
for _, ip := range svc.Status.LoadBalancer.Ingress {
if ip.IP == "" {
addrs = append(addrs, ip.Hostname)
} else {
addrs = append(addrs, ip.IP)
}
}
addrs = append(addrs, svc.Spec.ExternalIPs...)
return addrs, nil
}
// get information about all the pods running the ingress controller (gateway)
pods, err := s.podLister.Pods(ingressNamespace).List(labels.SelectorFromSet(map[string]string{"app": "ingressgateway"}))
if err != nil {
return nil, err
}
for _, pod := range pods {
// only Running pods are valid
if pod.Status.Phase != coreV1.PodRunning {
continue
}
// Find node external IP
node, err := s.nodeLister.Get(pod.Spec.NodeName)
if err != nil {
continue
}
for _, address := range node.Status.Addresses {
if address.Type == coreV1.NodeExternalIP {
if address.Address != "" && !addressInSlice(address.Address, addrs) {
addrs = append(addrs, address.Address)
}
}
}
}
return addrs, nil
}
func addressInSlice(addr string, list []string) bool {
for _, v := range list {
if v == addr {
return true
}
}
return false
}
// sliceToStatus converts a slice of IP and/or hostnames to LoadBalancerIngress
func sliceToStatus(endpoints []string) []coreV1.LoadBalancerIngress {
lbi := make([]coreV1.LoadBalancerIngress, 0)
for _, ep := range endpoints {
if net.ParseIP(ep) == nil {
lbi = append(lbi, coreV1.LoadBalancerIngress{Hostname: ep})
} else {
lbi = append(lbi, coreV1.LoadBalancerIngress{IP: ep})
}
}
return lbi
}
func lessLoadBalancerIngress(addrs []coreV1.LoadBalancerIngress) func(int, int) bool {
return func(a, b int) bool {
switch strings.Compare(addrs[a].Hostname, addrs[b].Hostname) {
case -1:
return true
case 1:
return false
}
return addrs[a].IP < addrs[b].IP
}
}
func ingressSliceEqual(lhs, rhs []coreV1.LoadBalancerIngress) bool {
if len(lhs) != len(rhs) {
return false
}
for i := range lhs {
if lhs[i].IP != rhs[i].IP {
return false
}
if lhs[i].Hostname != rhs[i].Hostname {
return false
}
}
return true
}
// convertIngressControllerMode converts Ingress controller mode into k8s ingress status syncer ingress class and
// default ingress class. Ingress class and default ingress class are used by the syncer to determine whether or not to
// update the IP of a ingress resource.
func convertIngressControllerMode(mode meshconfig.MeshConfig_IngressControllerMode,
class string) (string, string) {
var ingressClass, defaultIngressClass string
switch mode {
case meshconfig.MeshConfig_DEFAULT:
defaultIngressClass = class
ingressClass = class
case meshconfig.MeshConfig_STRICT:
ingressClass = class
}
return ingressClass, defaultIngressClass
}
// classIsValid returns true if the given Ingress either doesn't specify
// the ingress.class annotation, or it's set to the configured in the
// ingress controller.
func classIsValid(ing *v1beta1.Ingress, controller, defClass string) bool {
// ingress fetched through annotation.
var ingress string
if ing != nil && len(ing.GetAnnotations()) != 0 {
ingress = ing.GetAnnotations()[kube.IngressClassAnnotation]
}
// we have 2 valid combinations
// 1 - ingress with default class | blank annotation on ingress
// 2 - ingress with specific class | same annotation on ingress
//
// and 2 invalid combinations
// 3 - ingress with default class | fixed annotation on ingress
// 4 - ingress with specific class | different annotation on ingress
if ingress == "" && controller == defClass {
return true
}
return ingress == controller
}
| []
| []
| []
| [] | [] | go | null | null | null |
django_projects/forum_site/community/wsgi.py | """
WSGI config for community project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "community.settings")
application = get_wsgi_application()
| []
| []
| []
| [] | [] | python | 0 | 0 | |
examples/manage-plnt.py | import os
import click
from werkzeug.serving import run_simple
def make_app():
"""Helper function that creates a plnt app."""
from plnt import Plnt
database_uri = os.environ.get("PLNT_DATABASE_URI")
app = Plnt(database_uri or "sqlite:////tmp/plnt.db")
app.bind_to_context()
return app
@click.group()
def cli():
pass
@cli.command()
def initdb():
"""Initialize the database"""
from plnt.database import Blog, session
make_app().init_database()
# and now fill in some python blogs everybody should read (shamelessly
# added my own blog too)
blogs = [
Blog(
"Armin Ronacher",
"http://lucumr.pocoo.org/",
"http://lucumr.pocoo.org/cogitations/feed/",
),
Blog(
"Georg Brandl",
"http://pyside.blogspot.com/",
"http://pyside.blogspot.com/feeds/posts/default",
),
Blog(
"Ian Bicking",
"http://blog.ianbicking.org/",
"http://blog.ianbicking.org/feed/",
),
Blog(
"Amir Salihefendic", "http://amix.dk/", "http://feeds.feedburner.com/amixdk"
),
Blog(
"Christopher Lenz",
"http://www.cmlenz.net/blog/",
"http://www.cmlenz.net/blog/atom.xml",
),
Blog(
"Frederick Lundh",
"http://online.effbot.org/",
"http://online.effbot.org/rss.xml",
),
]
# okay. got tired here. if someone feels that he is missing, drop me
# a line ;-)
for blog in blogs:
session.add(blog)
session.commit()
click.echo("Initialized database, now run manage-plnt.py sync to get the posts")
@cli.command()
@click.option("-h", "--hostname", type=str, default="localhost", help="localhost")
@click.option("-p", "--port", type=int, default=5000, help="5000")
@click.option("--no-reloader", is_flag=True, default=False)
@click.option("--debugger", is_flag=True)
@click.option("--no-evalex", is_flag=True, default=False)
@click.option("--threaded", is_flag=True)
@click.option("--processes", type=int, default=1, help="1")
def runserver(hostname, port, no_reloader, debugger, no_evalex, threaded, processes):
"""Start a new development server."""
app = make_app()
reloader = not no_reloader
evalex = not no_evalex
run_simple(
hostname,
port,
app,
use_reloader=reloader,
use_debugger=debugger,
use_evalex=evalex,
threaded=threaded,
processes=processes,
)
@cli.command()
@click.option("--no-ipython", is_flag=True, default=False)
def shell(no_ipython):
"""Start a new interactive python session."""
banner = "Interactive Werkzeug Shell"
namespace = {"app": make_app()}
if not no_ipython:
try:
try:
from IPython.frontend.terminal.embed import InteractiveShellEmbed
sh = InteractiveShellEmbed.instance(banner1=banner)
except ImportError:
from IPython.Shell import IPShellEmbed
sh = IPShellEmbed(banner=banner)
except ImportError:
pass
else:
sh(local_ns=namespace)
return
from code import interact
interact(banner, local=namespace)
@cli.command()
def sync():
"""Sync the blogs in the planet. Call this from a cronjob."""
from plnt.sync import sync
make_app().bind_to_context()
sync()
if __name__ == "__main__":
cli()
| []
| []
| [
"PLNT_DATABASE_URI"
]
| [] | ["PLNT_DATABASE_URI"] | python | 1 | 0 | |
operator/src/main/java/oracle/kubernetes/operator/helpers/ConfigMapHelper.java | // Copyright (c) 2018, 2019, Oracle Corporation and/or its affiliates. All rights reserved.
// Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
package oracle.kubernetes.operator.helpers;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import io.kubernetes.client.models.V1ConfigMap;
import io.kubernetes.client.models.V1DeleteOptions;
import io.kubernetes.client.models.V1ObjectMeta;
import oracle.kubernetes.operator.KubernetesConstants;
import oracle.kubernetes.operator.LabelConstants;
import oracle.kubernetes.operator.ProcessingConstants;
import oracle.kubernetes.operator.calls.CallResponse;
import oracle.kubernetes.operator.logging.LoggingFacade;
import oracle.kubernetes.operator.logging.LoggingFactory;
import oracle.kubernetes.operator.logging.MessageKeys;
import oracle.kubernetes.operator.rest.Scan;
import oracle.kubernetes.operator.rest.ScanCache;
import oracle.kubernetes.operator.steps.DefaultResponseStep;
import oracle.kubernetes.operator.wlsconfig.WlsDomainConfig;
import oracle.kubernetes.operator.work.NextAction;
import oracle.kubernetes.operator.work.Packet;
import oracle.kubernetes.operator.work.Step;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.joda.time.DateTime;
import static oracle.kubernetes.operator.VersionConstants.DEFAULT_DOMAIN_VERSION;
public class ConfigMapHelper {
private static final LoggingFacade LOGGER = LoggingFactory.getLogger("Operator", "Operator");
private static final String SCRIPT_LOCATION = "/scripts";
private static final ConfigMapComparator COMPARATOR = new ConfigMapComparatorImpl();
private static final FileGroupReader scriptReader = new FileGroupReader(SCRIPT_LOCATION);
private ConfigMapHelper() {
}
/**
* Factory for {@link Step} that creates config map containing scripts.
*
* @param operatorNamespace the operator's namespace
* @param domainNamespace the domain's namespace
* @return Step for creating config map containing scripts
*/
public static Step createScriptConfigMapStep(String operatorNamespace, String domainNamespace) {
return new ScriptConfigMapStep(operatorNamespace, domainNamespace);
}
static FileGroupReader getScriptReader() {
return scriptReader;
}
/**
* Factory for {@link Step} that creates config map containing sit config.
*
* @param next Next step
* @return Step for creating config map containing sit config
*/
public static Step createSitConfigMapStep(Step next) {
return new SitConfigMapStep(next);
}
/**
* Factory for {@link Step} that deletes introspector config map.
*
* @param domainUid The unique identifier assigned to the Weblogic domain when it was registered
* @param namespace Namespace
* @param next Next processing step
* @return Step for deleting introspector config map
*/
public static Step deleteDomainIntrospectorConfigMapStep(
String domainUid, String namespace, Step next) {
return new DeleteIntrospectorConfigMapStep(domainUid, namespace, next);
}
public static Step readExistingSituConfigMap(String ns, String domainUid) {
String situConfigMapName = ConfigMapHelper.SitConfigMapContext.getConfigMapName(domainUid);
return new CallBuilder().readConfigMapAsync(situConfigMapName, ns, new ReadSituConfigMapStep());
}
static Map<String, String> parseIntrospectorResult(String text, String domainUid) {
Map<String, String> map = new HashMap<>();
try (BufferedReader reader = new BufferedReader(new StringReader(text))) {
String line = reader.readLine();
while (line != null) {
if (line.startsWith(">>>") && !line.endsWith("EOF")) {
// Beginning of file, extract file name
String filename = extractFilename(line);
readFile(reader, filename, map, domainUid);
}
line = reader.readLine();
}
} catch (IOException exc) {
LOGGER.warning(MessageKeys.CANNOT_PARSE_INTROSPECTOR_RESULT, domainUid, exc);
}
return map;
}
static void readFile(
BufferedReader reader, String fileName, Map<String, String> map, String domainUid) {
StringBuilder stringBuilder = new StringBuilder();
try {
String line = reader.readLine();
while (line != null) {
if (line.startsWith(">>>") && line.endsWith("EOF")) {
map.put(fileName, stringBuilder.toString());
return;
} else {
// add line to StringBuilder
stringBuilder.append(line);
stringBuilder.append(System.getProperty("line.separator"));
}
line = reader.readLine();
}
} catch (IOException ioe) {
LOGGER.warning(MessageKeys.CANNOT_PARSE_INTROSPECTOR_FILE, fileName, domainUid, ioe);
}
}
static String extractFilename(String line) {
int lastSlash = line.lastIndexOf('/');
String fname = line.substring(lastSlash + 1, line.length());
return fname;
}
public static DomainTopology parseDomainTopologyYaml(String topologyYaml) {
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
try {
DomainTopology domainTopology = mapper.readValue(topologyYaml, DomainTopology.class);
LOGGER.fine(
ReflectionToStringBuilder.toString(domainTopology, ToStringStyle.MULTI_LINE_STYLE));
return domainTopology;
} catch (Exception e) {
LOGGER.warning(MessageKeys.CANNOT_PARSE_TOPOLOGY, e);
}
return null;
}
interface ConfigMapComparator {
/** Returns true if the actual map contains all of the entries from the expected map. */
boolean containsAll(V1ConfigMap actual, V1ConfigMap expected);
}
static class ScriptConfigMapStep extends Step {
ConfigMapContext context;
ScriptConfigMapStep(String operatorNamespace, String domainNamespace) {
context = new ScriptConfigMapContext(this, operatorNamespace, domainNamespace);
}
@Override
public NextAction apply(Packet packet) {
return doNext(context.verifyConfigMap(getNext()), packet);
}
}
static class ScriptConfigMapContext extends ConfigMapContext {
private final Map<String, String> classpathScripts = loadScriptsFromClasspath();
ScriptConfigMapContext(Step conflictStep, String operatorNamespace, String domainNamespace) {
super(conflictStep, operatorNamespace, domainNamespace);
this.model = createModel(classpathScripts);
}
private V1ConfigMap createModel(Map<String, String> data) {
return new V1ConfigMap().metadata(createMetadata()).data(data);
}
private V1ObjectMeta createMetadata() {
return super.createMetadata(KubernetesConstants.DOMAIN_CONFIG_MAP_NAME)
.putLabelsItem(LabelConstants.OPERATORNAME_LABEL, operatorNamespace);
}
private synchronized Map<String, String> loadScriptsFromClasspath() {
Map<String, String> scripts = scriptReader.loadFilesFromClasspath();
LOGGER.fine(MessageKeys.SCRIPT_LOADED, this.domainNamespace);
return scripts;
}
ResponseStep<V1ConfigMap> createReadResponseStep(Step next) {
return new ReadResponseStep(next);
}
ResponseStep<V1ConfigMap> createCreateResponseStep(Step next) {
return new CreateResponseStep(next);
}
ResponseStep<V1ConfigMap> createReplaceResponseStep(Step next) {
return new ReplaceResponseStep(next);
}
Step updateConfigMap(Step next, V1ConfigMap existingConfigMap) {
return new CallBuilder()
.replaceConfigMapAsync(
model.getMetadata().getName(),
domainNamespace,
createModel(getCombinedData(existingConfigMap)),
createReplaceResponseStep(next));
}
Map<String, String> getCombinedData(V1ConfigMap existingConfigMap) {
Map<String, String> updated = existingConfigMap.getData();
updated.putAll(this.classpathScripts);
return updated;
}
class ReadResponseStep extends DefaultResponseStep<V1ConfigMap> {
ReadResponseStep(Step next) {
super(next);
}
@Override
public NextAction onSuccess(Packet packet, CallResponse<V1ConfigMap> callResponse) {
V1ConfigMap existingMap = callResponse.getResult();
if (existingMap == null) {
return doNext(createConfigMap(getNext()), packet);
} else if (isCompatibleMap(existingMap)) {
logConfigMapExists();
packet.put(ProcessingConstants.SCRIPT_CONFIG_MAP, existingMap);
return doNext(packet);
} else {
return doNext(updateConfigMap(getNext(), existingMap), packet);
}
}
}
private class CreateResponseStep extends ResponseStep<V1ConfigMap> {
CreateResponseStep(Step next) {
super(next);
}
@Override
public NextAction onFailure(Packet packet, CallResponse<V1ConfigMap> callResponse) {
return super.onFailure(conflictStep, packet, callResponse);
}
@Override
public NextAction onSuccess(Packet packet, CallResponse<V1ConfigMap> callResponse) {
LOGGER.info(MessageKeys.CM_CREATED, domainNamespace);
packet.put(ProcessingConstants.SCRIPT_CONFIG_MAP, callResponse.getResult());
return doNext(packet);
}
}
private class ReplaceResponseStep extends ResponseStep<V1ConfigMap> {
ReplaceResponseStep(Step next) {
super(next);
}
@Override
public NextAction onFailure(Packet packet, CallResponse<V1ConfigMap> callResponse) {
return super.onFailure(conflictStep, packet, callResponse);
}
@Override
public NextAction onSuccess(Packet packet, CallResponse<V1ConfigMap> callResponse) {
LOGGER.info(MessageKeys.CM_REPLACED, domainNamespace);
packet.put(ProcessingConstants.SCRIPT_CONFIG_MAP, callResponse.getResult());
return doNext(packet);
}
}
}
abstract static class ConfigMapContext {
protected final Step conflictStep;
protected final String operatorNamespace;
protected final String domainNamespace;
protected V1ConfigMap model;
ConfigMapContext(Step conflictStep, String operatorNamespace, String domainNamespace) {
this.conflictStep = conflictStep;
this.operatorNamespace = operatorNamespace;
this.domainNamespace = domainNamespace;
}
protected V1ObjectMeta createMetadata(String configMapName) {
return new V1ObjectMeta()
.name(configMapName)
.namespace(this.domainNamespace)
.putLabelsItem(LabelConstants.RESOURCE_VERSION_LABEL, DEFAULT_DOMAIN_VERSION)
.putLabelsItem(LabelConstants.CREATEDBYOPERATOR_LABEL, "true");
}
Step verifyConfigMap(Step next) {
return new CallBuilder()
.readConfigMapAsync(
model.getMetadata().getName(), domainNamespace, createReadResponseStep(next));
}
abstract ResponseStep<V1ConfigMap> createReadResponseStep(Step next);
Step createConfigMap(Step next) {
return new CallBuilder()
.createConfigMapAsync(domainNamespace, model, createCreateResponseStep(next));
}
abstract ResponseStep<V1ConfigMap> createCreateResponseStep(Step next);
protected boolean isCompatibleMap(V1ConfigMap existingMap) {
return VersionHelper.matchesResourceVersion(existingMap.getMetadata(), DEFAULT_DOMAIN_VERSION)
&& COMPARATOR.containsAll(existingMap, this.model);
}
void logConfigMapExists() {
LOGGER.fine(MessageKeys.CM_EXISTS, domainNamespace);
}
}
static class ConfigMapComparatorImpl implements ConfigMapComparator {
@Override
public boolean containsAll(V1ConfigMap actual, V1ConfigMap expected) {
return actual.getData().entrySet().containsAll(expected.getData().entrySet());
}
}
static class SitConfigMapStep extends Step {
SitConfigMapStep(Step next) {
super(next);
}
private static String getOperatorNamespace() {
String namespace = System.getenv("OPERATOR_NAMESPACE");
if (namespace == null) {
namespace = "default";
}
return namespace;
}
@Override
public NextAction apply(Packet packet) {
DomainPresenceInfo info = packet.getSpi(DomainPresenceInfo.class);
String result = (String) packet.remove(ProcessingConstants.DOMAIN_INTROSPECTOR_LOG_RESULT);
// Parse results into separate data files
Map<String, String> data = parseIntrospectorResult(result, info.getDomainUid());
LOGGER.fine("================");
LOGGER.fine(data.toString());
LOGGER.fine("================");
String topologyYaml = data.get("topology.yaml");
if (topologyYaml != null) {
LOGGER.fine("topology.yaml: " + topologyYaml);
DomainTopology domainTopology = parseDomainTopologyYaml(topologyYaml);
if (domainTopology == null || !domainTopology.getDomainValid()) {
// If introspector determines Domain is invalid then log erros and terminate the fiber
if (domainTopology != null) {
logValidationErrors(domainTopology.getValidationErrors());
}
return doNext(null, packet);
}
WlsDomainConfig wlsDomainConfig = domainTopology.getDomain();
ScanCache.INSTANCE.registerScan(
info.getNamespace(), info.getDomainUid(), new Scan(wlsDomainConfig, new DateTime()));
packet.put(ProcessingConstants.DOMAIN_TOPOLOGY, wlsDomainConfig);
LOGGER.info(
MessageKeys.WLS_CONFIGURATION_READ,
(System.currentTimeMillis() - ((Long) packet.get(JobHelper.START_TIME))),
wlsDomainConfig);
SitConfigMapContext context =
new SitConfigMapContext(
this, info.getDomainUid(), getOperatorNamespace(), info.getNamespace(), data);
return doNext(context.verifyConfigMap(getNext()), packet);
}
// TODO: How do we handle no topology?
return doNext(getNext(), packet);
}
private void logValidationErrors(List<String> validationErrors) {
if (!validationErrors.isEmpty()) {
for (String err : validationErrors) {
LOGGER.severe(err);
}
}
}
}
public static class SitConfigMapContext extends ConfigMapContext {
Map<String, String> data;
String domainUid;
String cmName;
SitConfigMapContext(
Step conflictStep,
String domainUid,
String operatorNamespace,
String domainNamespace,
Map<String, String> data) {
super(conflictStep, operatorNamespace, domainNamespace);
this.domainUid = domainUid;
this.cmName = getConfigMapName(domainUid);
this.data = data;
this.model = createModel(data);
}
public static String getConfigMapName(String domainUid) {
return domainUid + KubernetesConstants.INTROSPECTOR_CONFIG_MAP_NAME_SUFFIX;
}
private V1ConfigMap createModel(Map<String, String> data) {
return new V1ConfigMap()
.apiVersion("v1")
.kind("ConfigMap")
.metadata(createMetadata())
.data(data);
}
ResponseStep<V1ConfigMap> createReadResponseStep(Step next) {
return new ReadResponseStep(next);
}
private V1ObjectMeta createMetadata() {
return super.createMetadata(cmName).putLabelsItem(LabelConstants.DOMAINUID_LABEL, domainUid);
}
ResponseStep<V1ConfigMap> createCreateResponseStep(Step next) {
return new CreateResponseStep(next);
}
ResponseStep<V1ConfigMap> createReplaceResponseStep(Step next) {
return new ReplaceResponseStep(next);
}
Step updateConfigMap(Step next, V1ConfigMap existingConfigMap) {
return new CallBuilder()
.replaceConfigMapAsync(
model.getMetadata().getName(),
domainNamespace,
createModel(getCombinedData(existingConfigMap)),
createReplaceResponseStep(next));
}
Map<String, String> getCombinedData(V1ConfigMap existingConfigMap) {
Map<String, String> updated = existingConfigMap.getData();
updated.putAll(this.data);
return updated;
}
class ReadResponseStep extends DefaultResponseStep<V1ConfigMap> {
ReadResponseStep(Step next) {
super(next);
}
@Override
public NextAction onSuccess(Packet packet, CallResponse<V1ConfigMap> callResponse) {
V1ConfigMap existingMap = callResponse.getResult();
if (existingMap == null) {
return doNext(createConfigMap(getNext()), packet);
} else if (isCompatibleMap(existingMap)) {
logConfigMapExists();
packet.put(ProcessingConstants.SIT_CONFIG_MAP, existingMap);
return doNext(packet);
} else {
return doNext(updateConfigMap(getNext(), existingMap), packet);
}
}
}
private class CreateResponseStep extends ResponseStep<V1ConfigMap> {
CreateResponseStep(Step next) {
super(next);
}
@Override
public NextAction onFailure(Packet packet, CallResponse<V1ConfigMap> callResponse) {
return super.onFailure(conflictStep, packet, callResponse);
}
@Override
public NextAction onSuccess(Packet packet, CallResponse<V1ConfigMap> callResponse) {
LOGGER.info(MessageKeys.CM_CREATED, domainNamespace);
packet.put(ProcessingConstants.SIT_CONFIG_MAP, callResponse.getResult());
return doNext(packet);
}
}
private class ReplaceResponseStep extends ResponseStep<V1ConfigMap> {
ReplaceResponseStep(Step next) {
super(next);
}
@Override
public NextAction onFailure(Packet packet, CallResponse<V1ConfigMap> callResponse) {
return super.onFailure(conflictStep, packet, callResponse);
}
@Override
public NextAction onSuccess(Packet packet, CallResponse<V1ConfigMap> callResponse) {
LOGGER.info(MessageKeys.CM_REPLACED, domainNamespace);
packet.put(ProcessingConstants.SIT_CONFIG_MAP, callResponse.getResult());
return doNext(packet);
}
}
}
private static class DeleteIntrospectorConfigMapStep extends Step {
private String domainUid;
private String namespace;
DeleteIntrospectorConfigMapStep(String domainUid, String namespace, Step next) {
super(next);
this.domainUid = domainUid;
this.namespace = namespace;
}
@Override
public NextAction apply(Packet packet) {
return doNext(deleteSitConfigMap(getNext()), packet);
}
String getConfigMapDeletedMessageKey() {
return "Domain Introspector config map "
+ SitConfigMapContext.getConfigMapName(this.domainUid)
+ " deleted";
}
protected void logConfigMapDeleted() {
LOGGER.info(getConfigMapDeletedMessageKey());
}
private Step deleteSitConfigMap(Step next) {
logConfigMapDeleted();
String configMapName = SitConfigMapContext.getConfigMapName(this.domainUid);
Step step =
new CallBuilder()
.deleteConfigMapAsync(
configMapName,
this.namespace,
new V1DeleteOptions(),
new DefaultResponseStep<>(next));
return step;
}
}
private static class ReadSituConfigMapStep extends ResponseStep<V1ConfigMap> {
ReadSituConfigMapStep() {
}
@Override
public NextAction onFailure(Packet packet, CallResponse<V1ConfigMap> callResponse) {
return callResponse.getStatusCode() == CallBuilder.NOT_FOUND
? onSuccess(packet, callResponse)
: super.onFailure(packet, callResponse);
}
@Override
public NextAction onSuccess(Packet packet, CallResponse<V1ConfigMap> callResponse) {
DomainPresenceInfo info = packet.getSpi(DomainPresenceInfo.class);
V1ConfigMap result = callResponse.getResult();
if (result != null) {
Map<String, String> data = result.getData();
String topologyYaml = data.get("topology.yaml");
if (topologyYaml != null) {
ConfigMapHelper.DomainTopology domainTopology =
ConfigMapHelper.parseDomainTopologyYaml(topologyYaml);
if (domainTopology != null) {
WlsDomainConfig wlsDomainConfig = domainTopology.getDomain();
ScanCache.INSTANCE.registerScan(
info.getNamespace(),
info.getDomainUid(),
new Scan(wlsDomainConfig, new DateTime()));
packet.put(ProcessingConstants.DOMAIN_TOPOLOGY, wlsDomainConfig);
}
}
}
return doNext(packet);
}
}
public static class DomainTopology {
private boolean domainValid;
private WlsDomainConfig domain;
private List<String> validationErrors;
public boolean getDomainValid() {
// domainValid = true AND no validation errors exist
if (domainValid && getValidationErrors().isEmpty()) {
return true;
}
return false;
}
public void setDomainValid(boolean domainValid) {
this.domainValid = domainValid;
}
public WlsDomainConfig getDomain() {
this.domain.processDynamicClusters();
return this.domain;
}
public void setDomain(WlsDomainConfig domain) {
this.domain = domain;
}
public List<String> getValidationErrors() {
if (validationErrors == null) {
validationErrors = Collections.emptyList();
}
if (!domainValid && validationErrors.isEmpty()) {
// add a log message that domain was marked invalid since we have no validation
// errors from introspector.
validationErrors = new ArrayList<>();
validationErrors.add(
"Error, domain is invalid although there are no validation errors from introspector job.");
}
return validationErrors;
}
public void setValidationErrors(List<String> validationErrors) {
this.validationErrors = validationErrors;
}
public String toString() {
if (domainValid) {
return "domain: " + domain;
}
return "domainValid: " + domainValid + ", validationErrors: " + validationErrors;
}
}
}
| [
"\"OPERATOR_NAMESPACE\""
]
| []
| [
"OPERATOR_NAMESPACE"
]
| [] | ["OPERATOR_NAMESPACE"] | java | 1 | 0 | |
questioneer/manage.py | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "questioneer.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == "__main__":
main()
| []
| []
| []
| [] | [] | python | 0 | 0 | |
healthcare/api-client/dicom/dicomweb_test.py | # Copyright 2018 Google LLC All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import pytest
import sys
import time
# Add datasets for bootstrapping datasets for testing
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'datasets')) # noqa
import datasets
import dicom_stores
import dicomweb
cloud_region = 'us-central1'
base_url = 'https://healthcare.googleapis.com/v1beta1'
project_id = os.environ['GOOGLE_CLOUD_PROJECT']
service_account_json = os.environ['GOOGLE_APPLICATION_CREDENTIALS']
dataset_id = 'test_dataset-{}'.format(int(time.time()))
dicom_store_id = 'test_dicom_store_{}'.format(int(time.time()))
RESOURCES = os.path.join(os.path.dirname(__file__), 'resources')
dcm_file_name = 'dicom_00000001_000.dcm'
dcm_file = os.path.join(RESOURCES, dcm_file_name)
# The study_uid, series_uid, and instance_uid are not assigned by the
# server and are part of the metadata of dcm_file
study_uid = '1.3.6.1.4.1.11129.5.5.111396399361969898205364400549799252857604'
series_uid = '1.3.6.1.4.1.11129.5.5.195628213694300498946760767481291263511724'
instance_uid = '{}.{}'.format(
'1.3.6.1.4.1.11129.5.5',
'153751009835107614666834563294684339746480')
@pytest.fixture(scope='module')
def test_dataset():
dataset = datasets.create_dataset(
service_account_json,
project_id,
cloud_region,
dataset_id)
yield dataset
# Clean up
datasets.delete_dataset(
service_account_json,
project_id,
cloud_region,
dataset_id)
@pytest.fixture(scope='module')
def test_dicom_store():
dicom_store = dicom_stores.create_dicom_store(
service_account_json,
project_id,
cloud_region,
dataset_id,
dicom_store_id)
yield dicom_store
# Clean up
dicom_stores.delete_dicom_store(
service_account_json,
project_id,
cloud_region,
dataset_id,
dicom_store_id)
def test_dicomweb_store_instance(test_dataset, test_dicom_store, capsys):
dicomweb.dicomweb_store_instance(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
dicom_store_id,
dcm_file)
out, _ = capsys.readouterr()
# Check that store instance worked
assert 'Stored DICOM instance' in out
dicomweb.dicomweb_delete_study(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
dicom_store_id,
study_uid)
def test_dicomweb_search_instance(test_dataset, test_dicom_store, capsys):
dicomweb.dicomweb_store_instance(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
dicom_store_id,
dcm_file)
dicomweb.dicomweb_search_instance(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
dicom_store_id)
out, _ = capsys.readouterr()
# Check that store instance worked
assert 'Instances:' in out
dicomweb.dicomweb_delete_study(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
dicom_store_id,
study_uid)
def test_dicomweb_retrieve_study(test_dataset, test_dicom_store, capsys):
dicomweb.dicomweb_store_instance(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
dicom_store_id,
dcm_file)
dicomweb.dicomweb_retrieve_study(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
dicom_store_id,
study_uid)
# Assert study was downloaded
assert os.path.isfile('study.dcm')
out, _ = capsys.readouterr()
# Check that retrieve study worked
assert 'Retrieved study' in out
# Delete downloaded study
os.remove('study.dcm')
dicomweb.dicomweb_delete_study(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
dicom_store_id,
study_uid)
def test_dicomweb_retrieve_instance(test_dataset, test_dicom_store, capsys):
dicomweb.dicomweb_store_instance(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
dicom_store_id,
dcm_file)
dicomweb.dicomweb_retrieve_instance(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
dicom_store_id,
study_uid,
series_uid,
instance_uid)
# Assert instance was downloaded
assert os.path.isfile('instance.dcm')
out, _ = capsys.readouterr()
# Check that retrieve instance worked
assert 'Retrieved DICOM instance' in out
# Delete downloaded instance
os.remove('instance.dcm')
dicomweb.dicomweb_delete_study(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
dicom_store_id,
study_uid)
def test_dicomweb_retrieve_rendered(test_dataset, test_dicom_store, capsys):
dicomweb.dicomweb_store_instance(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
dicom_store_id,
dcm_file)
dicomweb.dicomweb_retrieve_rendered(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
dicom_store_id,
study_uid,
series_uid,
instance_uid)
# Assert rendered image was downloaded
assert os.path.isfile('rendered_image.png')
out, _ = capsys.readouterr()
# Check that retrieve rendered image worked
assert 'Retrieved rendered image' in out
# Delete downloaded rendered image
os.remove('rendered_image.png')
dicomweb.dicomweb_delete_study(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
dicom_store_id,
study_uid)
def test_dicomweb_delete_study(test_dataset, test_dicom_store, capsys):
dicomweb.dicomweb_store_instance(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
dicom_store_id,
dcm_file)
dicomweb.dicomweb_delete_study(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
dicom_store_id,
study_uid)
out, _ = capsys.readouterr()
# Check that store instance worked
assert 'Deleted study.' in out
| []
| []
| [
"GOOGLE_CLOUD_PROJECT",
"GOOGLE_APPLICATION_CREDENTIALS"
]
| [] | ["GOOGLE_CLOUD_PROJECT", "GOOGLE_APPLICATION_CREDENTIALS"] | python | 2 | 0 | |
pkg/minikube/driver/driver.go | /*
Copyright 2019 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package driver
import (
"fmt"
"os"
"runtime"
"sort"
"strconv"
"strings"
"k8s.io/klog/v2"
"k8s.io/minikube/pkg/drivers/kic/oci"
"k8s.io/minikube/pkg/minikube/config"
"k8s.io/minikube/pkg/minikube/registry"
)
const (
// Podman is Kubernetes in container using podman driver
Podman = "podman"
// Docker is Kubernetes in container using docker driver
Docker = "docker"
// Mock driver
Mock = "mock"
// None driver
None = "none"
// KVM2 driver
KVM2 = "kvm2"
// VirtualBox driver
VirtualBox = "virtualbox"
// HyperKit driver
HyperKit = "hyperkit"
// VMware driver
VMware = "vmware"
// VMwareFusion driver
VMwareFusion = "vmwarefusion"
// HyperV driver
HyperV = "hyperv"
// Parallels driver
Parallels = "parallels"
// AliasKVM is driver name alias for kvm2
AliasKVM = "kvm"
)
var (
// systemdResolvConf is path to systemd's DNS configuration. https://github.com/kubernetes/minikube/issues/3511
systemdResolvConf = "/run/systemd/resolve/resolv.conf"
)
// SupportedDrivers returns a list of supported drivers
func SupportedDrivers() []string {
return supportedDrivers
}
// DisplaySupportedDrivers returns a string with a list of supported drivers
func DisplaySupportedDrivers() string {
var sd []string
for _, d := range supportedDrivers {
if registry.Driver(d).Priority == registry.Experimental {
sd = append(sd, d+" (experimental)")
continue
}
sd = append(sd, d)
}
return strings.Join(sd, ", ")
}
// Supported returns if the driver is supported on this host.
func Supported(name string) bool {
for _, d := range supportedDrivers {
if name == d {
return true
}
}
return false
}
// MachineType returns appropriate machine name for the driver
func MachineType(name string) string {
if IsKIC(name) {
return "container"
}
if IsVM(name) {
return "VM"
}
// none or mock
return "bare metal machine"
}
// IsKIC checks if the driver is a Kubernetes in container
func IsKIC(name string) bool {
return name == Docker || name == Podman
}
// IsDocker checks if the driver docker
func IsDocker(name string) bool {
return name == Docker
}
// IsDockerDesktop checks if the driver is a Docker for Desktop (Docker on windows or MacOs)
// for linux and exotic archs, this will be false
func IsDockerDesktop(name string) bool {
if IsDocker(name) {
if runtime.GOOS == "darwin" || runtime.GOOS == "windows" {
return true
}
}
return false
}
// IsMock checks if the driver is a mock
func IsMock(name string) bool {
return name == Mock
}
// IsVM checks if the driver is a VM
func IsVM(name string) bool {
if IsKIC(name) || BareMetal(name) {
return false
}
return true
}
// BareMetal returns if this driver is unisolated
func BareMetal(name string) bool {
return name == None || name == Mock
}
// NeedsRoot returns true if driver needs to run with root privileges
func NeedsRoot(name string) bool {
return name == None
}
// NeedsPortForward returns true if driver is unable provide direct IP connectivity
func NeedsPortForward(name string) bool {
if !IsKIC(name) {
return false
}
if oci.IsExternalDaemonHost(name) {
return true
}
// Docker for Desktop
return runtime.GOOS == "darwin" || runtime.GOOS == "windows" || IsMicrosoftWSL()
}
// IsMicrosoftWSL will return true if process is running in WSL in windows
// checking for WSL env var based on this https://github.com/microsoft/WSL/issues/423#issuecomment-608237689
// also based on https://github.com/microsoft/vscode/blob/90a39ba0d49d75e9a4d7e62a6121ad946ecebc58/resources/win32/bin/code.sh#L24
func IsMicrosoftWSL() bool {
return os.Getenv("WSL_DISTRO_NAME") != "" || os.Getenv("WSLPATH") != "" || os.Getenv("WSLENV") != ""
}
// HasResourceLimits returns true if driver can set resource limits such as memory size or CPU count.
func HasResourceLimits(name string) bool {
return name != None
}
// NeedsShutdown returns true if driver needs manual shutdown command before stopping.
// Hyper-V requires special care to avoid ACPI and file locking issues
// KIC also needs shutdown to avoid container getting stuck, https://github.com/kubernetes/minikube/issues/7657
func NeedsShutdown(name string) bool {
if name == HyperV || IsKIC(name) {
return true
}
return false
}
// FullName will return the human-known and title formatted name for the driver based on platform
func FullName(name string) string {
switch name {
case oci.Docker:
if IsDockerDesktop(name) {
return "Docker Desktop"
}
return "Docker"
default:
return strings.Title(name)
}
}
// FlagHints are hints for what default options should be used for this driver
type FlagHints struct {
ExtraOptions []string
CacheImages bool
ContainerRuntime string
Bootstrapper string
}
// FlagDefaults returns suggested defaults based on a driver
func FlagDefaults(name string) FlagHints {
fh := FlagHints{}
if name != None {
fh.CacheImages = true
return fh
}
fh.CacheImages = false
// if specifc linux add this option for systemd work on none driver
if _, err := os.Stat(systemdResolvConf); err == nil {
noneEO := fmt.Sprintf("kubelet.resolv-conf=%s", systemdResolvConf)
fh.ExtraOptions = append(fh.ExtraOptions, noneEO)
return fh
}
return fh
}
// Choices returns a list of drivers which are possible on this system
func Choices(vm bool) []registry.DriverState {
options := registry.Available(vm)
// Descending priority for predictability and appearance
sort.Slice(options, func(i, j int) bool {
return options[i].Priority > options[j].Priority
})
return options
}
// Suggest returns a suggested driver, alternate drivers, and rejected drivers
func Suggest(options []registry.DriverState) (registry.DriverState, []registry.DriverState, []registry.DriverState) {
pick := registry.DriverState{}
for _, ds := range options {
if !ds.State.Installed {
continue
}
if !ds.State.Healthy {
klog.Infof("not recommending %q due to health: %v", ds.Name, ds.State.Error)
continue
}
if ds.Priority <= registry.Discouraged {
klog.Infof("not recommending %q due to priority: %d", ds.Name, ds.Priority)
continue
}
if ds.Priority > pick.Priority {
klog.V(1).Infof("%q has a higher priority (%d) than %q (%d)", ds.Name, ds.Priority, pick.Name, pick.Priority)
pick = ds
}
}
alternates := []registry.DriverState{}
rejects := []registry.DriverState{}
for _, ds := range options {
if ds != pick {
if !ds.State.Installed {
ds.Rejection = fmt.Sprintf("Not installed: %v", ds.State.Error)
rejects = append(rejects, ds)
continue
}
if !ds.State.Healthy {
ds.Rejection = fmt.Sprintf("Not healthy: %v", ds.State.Error)
rejects = append(rejects, ds)
continue
}
ds.Rejection = fmt.Sprintf("%s is preferred", pick.Name)
alternates = append(alternates, ds)
}
}
klog.Infof("Picked: %+v", pick)
klog.Infof("Alternatives: %+v", alternates)
klog.Infof("Rejects: %+v", rejects)
return pick, alternates, rejects
}
// Status returns the status of a driver
func Status(name string) registry.DriverState {
d := registry.Driver(name)
return registry.DriverState{
Name: d.Name,
Priority: d.Priority,
State: registry.Status(name),
}
}
// IsAlias checks if an alias belongs to provided driver by name.
func IsAlias(name, alias string) bool {
d := registry.Driver(name)
for _, da := range d.Alias {
if da == alias {
return true
}
}
return false
}
// SetLibvirtURI sets the URI to perform libvirt health checks against
func SetLibvirtURI(v string) {
klog.Infof("Setting default libvirt URI to %s", v)
os.Setenv("LIBVIRT_DEFAULT_URI", v)
}
// MachineName returns the name of the machine, as seen by the hypervisor given the cluster and node names
func MachineName(cc config.ClusterConfig, n config.Node) string {
// For single node cluster, default to back to old naming
if len(cc.Nodes) == 1 || n.ControlPlane {
return cc.Name
}
return fmt.Sprintf("%s-%s", cc.Name, n.Name)
}
// IndexFromMachineName returns the order of the container based on it is name
func IndexFromMachineName(machineName string) int {
// minikube-m02
sp := strings.Split(machineName, "-")
m := strings.Trim(sp[len(sp)-1], "m") // m02
i, err := strconv.Atoi(m)
if err != nil {
return 1
}
return i
}
| [
"\"WSL_DISTRO_NAME\"",
"\"WSLPATH\"",
"\"WSLENV\""
]
| []
| [
"WSL_DISTRO_NAME",
"WSLPATH",
"WSLENV"
]
| [] | ["WSL_DISTRO_NAME", "WSLPATH", "WSLENV"] | go | 3 | 0 | |
common/Base.go | package common
import (
"flag"
"fmt"
"log"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/spf13/viper"
)
var env string = "dev"
func init() {
viper.SetDefault("envType", env)
// 获取当前环境变量
if realEnv := strings.ToLower(os.Getenv("envType")); realEnv != "" {
env = realEnv
viper.SetDefault("envType", env)
}
path, _ := filepath.Abs(filepath.Dir("")) // 获取当前路径
conf := path + "/config/config_" + env + ".toml" // 拼接配置文件
// fmt.Println(conf)
configFile := flag.String("c", conf, "配置文件路径") // 手动置顶配置文件
flag.Parse()
viper.SetConfigFile(*configFile) // 读取配置文件
fmt.Println("Loading config file " + *configFile)
if err := viper.ReadInConfig(); err != nil { //是否读取成功
log.Fatalln("打开配置文件失败", err)
}
}
type Base struct {
C *gin.Context
}
// Flush Flush
func (bm *Base) Flush() bool {
return bm.C.GetBool("_flush")
// return false
}
// Debug debug
func (bm *Base) Debug() bool {
return bm.C.GetBool("_debug")
}
// SetDebug 设置debug
func (bm *Base) SetDebug(depth int, message string, a ...interface{}) {
if !bm.C.GetBool("_debug") {
return
}
if depth == 0 {
depth = 1
}
_, file, line, _ := runtime.Caller(depth)
path := strings.LastIndexByte(file, '/')
info := fmt.Sprintf(message, a...)
tmp := string([]byte(file)[path+1:]) + "(line " + strconv.Itoa(line) + "): " + info
debug := bm.C.GetStringSlice("debug")
bm.C.Set("debug", append(debug, tmp))
}
// TimeCost 计算花费时间
func (bm *Base) TimeCost(key string) string {
cost := ""
if start := bm.C.GetTime(key); start.IsZero() {
bm.C.Set(key, time.Now())
} else {
tc := time.Since(start)
cost = fmt.Sprintf("%v", tc)
}
return cost
}
| [
"\"envType\""
]
| []
| [
"envType"
]
| [] | ["envType"] | go | 1 | 0 | |
hwcconfig/application_host_config.go | package hwcconfig
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"text/template"
)
var globalModules = []map[string]string{
{"Name": "UriCacheModule", "Image": `%windir%\System32\inetsrv\cachuri.dll`},
{"Name": "FileCacheModule", "Image": `%windir%\System32\inetsrv\cachfile.dll`},
{"Name": "TokenCacheModule", "Image": `%windir%\System32\inetsrv\cachtokn.dll`},
{"Name": "HttpCacheModule", "Image": `%windir%\System32\inetsrv\cachhttp.dll`},
{"Name": "StaticCompressionModule", "Image": `%windir%\System32\inetsrv\compstat.dll`},
{"Name": "DefaultDocumentModule", "Image": `%windir%\System32\inetsrv\defdoc.dll`},
{"Name": "DirectoryListingModule", "Image": `%windir%\System32\inetsrv\dirlist.dll`},
{"Name": "ProtocolSupportModule", "Image": `%windir%\System32\inetsrv\protsup.dll`},
{"Name": "StaticFileModule", "Image": `%windir%\System32\inetsrv\static.dll`},
{"Name": "AnonymousAuthenticationModule", "Image": `%windir%\System32\inetsrv\authanon.dll`},
{"Name": "RequestFilteringModule", "Image": `%windir%\System32\inetsrv\modrqflt.dll`},
{"Name": "CustomErrorModule", "Image": `%windir%\System32\inetsrv\custerr.dll`},
{"Name": "HttpLoggingModule", "Image": `%windir%\System32\inetsrv\loghttp.dll`},
{"Name": "RequestMonitorModule", "Image": `%windir%\System32\inetsrv\iisreqs.dll`},
{"Name": "IsapiModule", "Image": `%windir%\System32\inetsrv\isapi.dll`},
{"Name": "IsapiFilterModule", "Image": `%windir%\System32\inetsrv\filter.dll`},
{"Name": "ConfigurationValidationModule", "Image": `%windir%\System32\inetsrv\validcfg.dll`},
// {"Name": "ManagedEngine64", "Image": `%windir%\Microsoft.NET\Framework64\v2.0.50727\webengine.dll`, "PreCondition": "integratedMode,runtimeVersionv2.0,bitness64"},
// {"Name": "ManagedEngine", "Image": `%windir%\Microsoft.NET\Framework\v2.0.50727\webengine.dll`, "PreCondition": "integratedMode,runtimeVersionv2.0,bitness32"},
{"Name": "ManagedEngineV4.0_32bit", "Image": `%windir%\Microsoft.NET\Framework\v4.0.30319\webengine4.dll`, "PreCondition": "integratedMode,runtimeVersionv4.0,bitness32"},
{"Name": "ManagedEngineV4.0_64bit", "Image": `%windir%\Microsoft.NET\Framework64\v4.0.30319\webengine4.dll`, "PreCondition": "integratedMode,runtimeVersionv4.0,bitness64"},
{"Name": "CustomLoggingModule", "Image": `%windir%\System32\inetsrv\logcust.dll`},
{"Name": "TracingModule", "Image": `%windir%\System32\inetsrv\iisetw.dll`},
{"Name": "FailedRequestsTracingModule", "Image": `%windir%\System32\inetsrv\iisfreb.dll`},
{"Name": "WebSocketModule", "Image": `%windir%\System32\inetsrv\iiswsock.dll`},
{"Name": "DynamicCompressionModule", "Image": `%windir%\System32\inetsrv\compdyn.dll`},
{"Name": "HttpRedirectionModule", "Image": `%windir%\System32\inetsrv\redirect.dll`},
{"Name": "CertificateMappingAuthenticationModule", "Image": `%windir%\System32\inetsrv\authcert.dll`},
{"Name": "UrlAuthorizationModule", "Image": `%windir%\System32\inetsrv\urlauthz.dll`},
{"Name": "WindowsAuthenticationModule", "Image": `%windir%\System32\inetsrv\authsspi.dll`},
{"Name": "DigestAuthenticationModule", "Image": `%windir%\System32\inetsrv\authmd5.dll`},
{"Name": "IISCertificateMappingAuthenticationModule", "Image": `%windir%\System32\inetsrv\authmap.dll`},
{"Name": "IpRestrictionModule", "Image": `%windir%\System32\inetsrv\iprestr.dll`},
{"Name": "DynamicIpRestrictionModule", "Image": `%windir%\System32\inetsrv\diprestr.dll`},
}
func (c *HwcConfig) generateApplicationHostConfig() error {
missing := []string{}
for _, v := range globalModules {
imagePath := os.ExpandEnv(strings.Replace(v["Image"], `%windir%`, `${windir}`, -1))
_, err := os.Stat(imagePath)
if os.IsNotExist(err) {
missing = append(missing, imagePath)
} else if err != nil {
return err
}
}
if len(missing) > 0 {
return errors.New(fmt.Sprintf("Missing required DLLs:\n%s", strings.Join(missing, ",\n")))
}
rewrite := false
rewritePath := filepath.Join(os.Getenv("WINDIR"), "system32", "inetsrv", "rewrite.dll")
_, err := os.Stat(rewritePath)
if err == nil {
globalModules = append(globalModules, map[string]string{"Name": "RewriteModule", "Image": `%windir%\system32\inetsrv\rewrite.dll`})
rewrite = true
} else if !os.IsNotExist(err) {
return err
}
file, err := os.Create(c.ApplicationHostConfigPath)
if err != nil {
return err
}
defer file.Close()
type templateInput struct {
Config *HwcConfig
GlobalModules []map[string]string
Rewrite bool
}
t := templateInput{
Config: c,
GlobalModules: globalModules,
Rewrite: rewrite,
}
var tmpl = template.Must(template.New("applicationhost").Parse(applicationHostConfigTemplate))
if err := tmpl.Execute(file, t); err != nil {
return err
}
return nil
}
const applicationHostConfigTemplate = `<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<configSections>
<sectionGroup name="system.applicationHost">
<section name="applicationPools" allowDefinition="AppHostOnly" overrideModeDefault="Deny" />
<section name="configHistory" allowDefinition="AppHostOnly" overrideModeDefault="Deny" />
<section name="customMetadata" allowDefinition="AppHostOnly" overrideModeDefault="Deny" />
<section name="listenerAdapters" allowDefinition="AppHostOnly" overrideModeDefault="Deny" />
<section name="log" allowDefinition="AppHostOnly" overrideModeDefault="Deny" />
<section name="serviceAutoStartProviders" allowDefinition="AppHostOnly" overrideModeDefault="Deny" />
<section name="sites" allowDefinition="AppHostOnly" overrideModeDefault="Deny" />
<section name="webLimits" allowDefinition="AppHostOnly" overrideModeDefault="Deny" />
</sectionGroup>
<sectionGroup name="system.webServer">
<section name="asp" overrideModeDefault="Deny" />
<section name="caching" overrideModeDefault="Allow" />
<section name="cgi" overrideModeDefault="Deny" />
<section name="defaultDocument" overrideModeDefault="Allow" />
<section name="directoryBrowse" overrideModeDefault="Allow" />
<section name="fastCgi" allowDefinition="AppHostOnly" overrideModeDefault="Deny" />
<section name="globalModules" allowDefinition="AppHostOnly" overrideModeDefault="Deny" />
<section name="handlers" overrideModeDefault="Allow" />
<section name="httpCompression" allowDefinition="AppHostOnly" overrideModeDefault="Deny" />
<section name="httpErrors" overrideModeDefault="Allow" />
<section name="httpLogging" overrideModeDefault="Deny" />
<section name="httpProtocol" overrideModeDefault="Allow" />
<section name="httpRedirect" overrideModeDefault="Allow" />
<section name="httpTracing" overrideModeDefault="Allow" />
<section name="isapiFilters" allowDefinition="MachineToApplication" overrideModeDefault="Deny" />
<section name="modules" allowDefinition="MachineToApplication" overrideModeDefault="Allow" />
<section name="odbcLogging" overrideModeDefault="Deny" />
<sectionGroup name="security">
<section name="access" overrideModeDefault="Deny" />
<section name="applicationDependencies" overrideModeDefault="Deny" />
<sectionGroup name="authentication">
<section name="anonymousAuthentication" overrideModeDefault="Deny" />
<section name="basicAuthentication" overrideModeDefault="Deny" />
<section name="clientCertificateMappingAuthentication" overrideModeDefault="Deny" />
<section name="digestAuthentication" overrideModeDefault="Deny" />
<section name="iisClientCertificateMappingAuthentication" overrideModeDefault="Deny" />
<section name="windowsAuthentication" overrideModeDefault="Allow" />
</sectionGroup>
<section name="authorization" overrideModeDefault="Allow" />
<section name="ipSecurity" overrideModeDefault="Deny" />
<section name="isapiCgiRestriction" allowDefinition="AppHostOnly" overrideModeDefault="Deny" />
<section name="requestFiltering" overrideModeDefault="Allow" />
</sectionGroup>
<section name="serverRuntime" overrideModeDefault="Deny" />
<section name="serverSideInclude" overrideModeDefault="Deny" />
<section name="staticContent" overrideModeDefault="Allow" />
<sectionGroup name="tracing">
<section name="traceFailedRequests" overrideModeDefault="Allow" />
<section name="traceProviderDefinitions" overrideModeDefault="Allow" />
</sectionGroup>
<section name="urlCompression" overrideModeDefault="Allow" />
<section name="validation" overrideModeDefault="Allow" />
<sectionGroup name="webdav">
<section name="globalSettings" overrideModeDefault="Deny" />
<section name="authoring" overrideModeDefault="Deny" />
<section name="authoringRules" overrideModeDefault="Deny" />
</sectionGroup>
<sectionGroup name="wdeploy">
<section name="backup" overrideModeDefault="Deny" allowDefinition="MachineToApplication" />
</sectionGroup>
<section name="webSocket" overrideModeDefault="Deny" />
{{if .Rewrite}}
<sectionGroup name="rewrite">
<section name="rules" overrideModeDefault="Allow" />
<section name="globalRules" overrideModeDefault="Deny" allowDefinition="AppHostOnly" />
<section name="outboundRules" overrideModeDefault="Allow" />
<section name="providers" overrideModeDefault="Allow" />
<section name="rewriteMaps" overrideModeDefault="Allow" />
<section name="allowedServerVariables" overrideModeDefault="Deny" />
</sectionGroup>
{{end}}
</sectionGroup>
</configSections>
<system.applicationHost>
<applicationPools>
<add name="AppPool{{.Config.Port}}" managedRuntimeVersion="v4.0" managedPipelineMode="Integrated" CLRConfigFile="{{.Config.AspnetConfigPath}}" autoStart="true" startMode="AlwaysRunning" />
</applicationPools>
<listenerAdapters>
<add name="http" />
</listenerAdapters>
<sites>
<siteDefaults>
<logFile logFormat="W3C" logExtFileFlags="Date, Time, ClientIP, UserName, ServerIP, Method, UriStem, UriQuery, Cookie, HttpStatus, Win32Status, TimeTaken, ServerPort, UserAgent, Referer, Host, HttpSubStatus" directory="{{.Config.TempDirectory}}\LogFiles" />
<traceFailedRequestsLogging enabled="false" />
</siteDefaults>
<applicationDefaults applicationPool="AppPool{{.Config.Port}}" />
<virtualDirectoryDefaults allowSubDirConfig="true" />
<site name="IronFoundrySite{{.Config.Port}}" id="{{.Config.Port}}" serverAutoStart="true">
{{ range .Config.Applications }}
<application path="{{.Path}}" applicationPool="AppPool{{$.Config.Port}}">
<virtualDirectory path="/" physicalPath="{{.PhysicalPath}}" />
</application>
{{ end }}
<bindings>
<binding protocol="http" bindingInformation="*:{{.Config.Port}}:" />
</bindings>
</site>
</sites>
<webLimits />
</system.applicationHost>
<system.webServer>
<asp>
<cache diskTemplateCacheDirectory="{{.Config.ASPCompiledTemplatesDirectory}}" />
</asp>
<caching enabled="true" enableKernelCache="true">
</caching>
<cgi />
<defaultDocument enabled="true">
<files>
<add value="Default.htm" />
<add value="Default.asp" />
<add value="index.htm" />
<add value="index.html" />
<add value="iisstart.htm" />
<add value="default.aspx" />
</files>
</defaultDocument>
<directoryBrowse enabled="false" />
<fastCgi />
<globalModules>
{{range .GlobalModules}}
<add name="{{ index . "Name" }}" image="{{ index . "Image" }}" {{ if index . "PreCondition" }} preCondition="{{ index . "PreCondition" }}" {{end}} />
{{end}}
</globalModules>
<httpCompression directory="{{.Config.IISCompressedFilesDirectory}}">
<scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" />
<scheme name="deflate" dll="%Windir%\system32\inetsrv\gzip.dll" />
<staticTypes>
<add mimeType="text/*" enabled="true" />
<add mimeType="message/*" enabled="true" />
<add mimeType="application/x-javascript" enabled="true" />
<add mimeType="application/javascript" enabled="true" />
<add mimeType="application/atom+xml" enabled="true" />
<add mimeType="application/xaml+xml" enabled="true" />
<add mimeType="*/*" enabled="false" />
<add mimeType="image/svg+xml" enabled="true" />
<add mimeType="application/rss+xml" enabled="true" />
<add mimeType="application/json" enabled="true" />
</staticTypes>
<dynamicTypes>
<add mimeType="text/*" enabled="true" />
<add mimeType="message/*" enabled="true" />
<add mimeType="application/x-javascript" enabled="true" />
<add mimeType="application/javascript" enabled="true" />
<add mimeType="*/*" enabled="false" />
<add mimeType="application/atom+xml" enabled="true" />
<add mimeType="application/xaml+xml" enabled="true" />
<add mimeType="application/rss+xml" enabled="true" />
<add mimeType="application/json" enabled="true" />
</dynamicTypes>
</httpCompression>
<httpErrors lockAttributes="allowAbsolutePathsWhenDelegated,defaultPath">
<error statusCode="401" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="401.htm" />
<error statusCode="403" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="403.htm" />
<error statusCode="404" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="404.htm" />
<error statusCode="405" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="405.htm" />
<error statusCode="406" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="406.htm" />
<error statusCode="412" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="412.htm" />
<error statusCode="500" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="500.htm" />
<error statusCode="501" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="501.htm" />
<error statusCode="502" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="502.htm" />
</httpErrors>
<httpLogging dontLog="true" />
<httpProtocol>
<customHeaders>
<clear />
</customHeaders>
<redirectHeaders>
<clear />
</redirectHeaders>
</httpProtocol>
<httpRedirect />
<httpTracing />
<isapiFilters>
<filter name="ASP.Net_2.0.50727-64" path="%windir%\Microsoft.NET\Framework64\v2.0.50727\aspnet_filter.dll" enableCache="true" preCondition="bitness64,runtimeVersionv2.0" />
<filter name="ASP.Net_2.0.50727.0" path="%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_filter.dll" enableCache="true" preCondition="bitness32,runtimeVersionv2.0" />
<filter name="ASP.Net_2.0_for_v1.1" path="%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_filter.dll" enableCache="true" preCondition="runtimeVersionv1.1" />
<filter name="ASP.Net_4.0_32bit" path="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_filter.dll" enableCache="true" preCondition="bitness32,runtimeVersionv4.0" />
<filter name="ASP.Net_4.0_64bit" path="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_filter.dll" enableCache="true" preCondition="bitness64,runtimeVersionv4.0" />
</isapiFilters>
<odbcLogging />
<security>
<access sslFlags="None" />
<applicationDependencies />
<authentication>
<anonymousAuthentication enabled="true" userName="IUSR" />
<basicAuthentication />
<clientCertificateMappingAuthentication />
<digestAuthentication />
<iisClientCertificateMappingAuthentication />
<windowsAuthentication enabled="true">
<providers>
<add value="NTLM" />
<add value="Negotiate" />
</providers>
</windowsAuthentication>
</authentication>
<authorization>
<add accessType="Allow" users="*" />
</authorization>
<ipSecurity />
<isapiCgiRestriction>
<add path="%windir%\system32\inetsrv\asp.dll" allowed="true" groupId="ASP" description="Active Server Pages" />
<add path="%windir%\Microsoft.NET\Framework64\v2.0.50727\aspnet_isapi.dll" allowed="true" groupId="ASP.NET v2.0.50727" description="ASP.NET v2.0.50727" />
<add path="%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll" allowed="true" groupId="ASP.NET v2.0.50727" description="ASP.NET v2.0.50727" />
<add path="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" allowed="false" groupId="ASP.NET v4.0.30319" description="ASP.NET v4.0.30319" />
<add path="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" allowed="true" groupId="ASP.NET v4.0.30319" description="ASP.NET v4.0.30319" />
</isapiCgiRestriction>
<requestFiltering allowDoubleEscaping='false' allowHighBitCharacters='false'>
<denyUrlSequences>
<add sequence='..' />
<add sequence='./' />
<add sequence='\' />
<add sequence=':' />
<add sequence='%' />
<add sequence='&' />
</denyUrlSequences>
<fileExtensions allowUnlisted="true" applyToWebDAV="true">
<add fileExtension=".asa" allowed="false" />
<add fileExtension=".asax" allowed="false" />
<add fileExtension=".ascx" allowed="false" />
<add fileExtension=".master" allowed="false" />
<add fileExtension=".skin" allowed="false" />
<add fileExtension=".browser" allowed="false" />
<add fileExtension=".sitemap" allowed="false" />
<add fileExtension=".config" allowed="false" />
<add fileExtension=".cs" allowed="false" />
<add fileExtension=".csproj" allowed="false" />
<add fileExtension=".vb" allowed="false" />
<add fileExtension=".vbproj" allowed="false" />
<add fileExtension=".webinfo" allowed="false" />
<add fileExtension=".licx" allowed="false" />
<add fileExtension=".resx" allowed="false" />
<add fileExtension=".resources" allowed="false" />
<add fileExtension=".mdb" allowed="false" />
<add fileExtension=".vjsproj" allowed="false" />
<add fileExtension=".java" allowed="false" />
<add fileExtension=".jsl" allowed="false" />
<add fileExtension=".ldb" allowed="false" />
<add fileExtension=".dsdgm" allowed="false" />
<add fileExtension=".ssdgm" allowed="false" />
<add fileExtension=".lsad" allowed="false" />
<add fileExtension=".ssmap" allowed="false" />
<add fileExtension=".cd" allowed="false" />
<add fileExtension=".dsprototype" allowed="false" />
<add fileExtension=".lsaprototype" allowed="false" />
<add fileExtension=".sdm" allowed="false" />
<add fileExtension=".sdmDocument" allowed="false" />
<add fileExtension=".mdf" allowed="false" />
<add fileExtension=".ldf" allowed="false" />
<add fileExtension=".ad" allowed="false" />
<add fileExtension=".dd" allowed="false" />
<add fileExtension=".ldd" allowed="false" />
<add fileExtension=".sd" allowed="false" />
<add fileExtension=".adprototype" allowed="false" />
<add fileExtension=".lddprototype" allowed="false" />
<add fileExtension=".exclude" allowed="false" />
<add fileExtension=".refresh" allowed="false" />
<add fileExtension=".compiled" allowed="false" />
<add fileExtension=".msgx" allowed="false" />
<add fileExtension=".vsdisco" allowed="false" />
<add fileExtension=".rules" allowed="false" />
</fileExtensions>
<requestLimits maxAllowedContentLength='2097152' maxUrl='260' maxQueryString='2048' />
<verbs allowUnlisted="true" applyToWebDAV="true" />
<hiddenSegments applyToWebDAV="true">
<add segment="web.config" />
<add segment="bin" />
<add segment="App_code" />
<add segment="App_GlobalResources" />
<add segment="App_LocalResources" />
<add segment="App_WebReferences" />
<add segment="App_Data" />
<add segment="App_Browsers" />
<add segment=".iishost" />
</hiddenSegments>
</requestFiltering>
</security>
<serverRuntime />
<serverSideInclude />
<staticContent lockAttributes="isDocFooterFileName">
<mimeMap fileExtension=".323" mimeType="text/h323" />
<mimeMap fileExtension=".3g2" mimeType="video/3gpp2" />
<mimeMap fileExtension=".3gp2" mimeType="video/3gpp2" />
<mimeMap fileExtension=".3gp" mimeType="video/3gpp" />
<mimeMap fileExtension=".3gpp" mimeType="video/3gpp" />
<mimeMap fileExtension=".aac" mimeType="audio/aac" />
<mimeMap fileExtension=".aaf" mimeType="application/octet-stream" />
<mimeMap fileExtension=".aca" mimeType="application/octet-stream" />
<mimeMap fileExtension=".accdb" mimeType="application/msaccess" />
<mimeMap fileExtension=".accde" mimeType="application/msaccess" />
<mimeMap fileExtension=".accdt" mimeType="application/msaccess" />
<mimeMap fileExtension=".acx" mimeType="application/internet-property-stream" />
<mimeMap fileExtension=".adt" mimeType="audio/vnd.dlna.adts" />
<mimeMap fileExtension=".adts" mimeType="audio/vnd.dlna.adts" />
<mimeMap fileExtension=".afm" mimeType="application/octet-stream" />
<mimeMap fileExtension=".ai" mimeType="application/postscript" />
<mimeMap fileExtension=".aif" mimeType="audio/x-aiff" />
<mimeMap fileExtension=".aifc" mimeType="audio/aiff" />
<mimeMap fileExtension=".aiff" mimeType="audio/aiff" />
<mimeMap fileExtension=".application" mimeType="application/x-ms-application" />
<mimeMap fileExtension=".art" mimeType="image/x-jg" />
<mimeMap fileExtension=".asd" mimeType="application/octet-stream" />
<mimeMap fileExtension=".asf" mimeType="video/x-ms-asf" />
<mimeMap fileExtension=".asi" mimeType="application/octet-stream" />
<mimeMap fileExtension=".asm" mimeType="text/plain" />
<mimeMap fileExtension=".asr" mimeType="video/x-ms-asf" />
<mimeMap fileExtension=".asx" mimeType="video/x-ms-asf" />
<mimeMap fileExtension=".atom" mimeType="application/atom+xml" />
<mimeMap fileExtension=".au" mimeType="audio/basic" />
<mimeMap fileExtension=".avi" mimeType="video/x-msvideo" />
<mimeMap fileExtension=".axs" mimeType="application/olescript" />
<mimeMap fileExtension=".bas" mimeType="text/plain" />
<mimeMap fileExtension=".bcpio" mimeType="application/x-bcpio" />
<mimeMap fileExtension=".bin" mimeType="application/octet-stream" />
<mimeMap fileExtension=".bmp" mimeType="image/bmp" />
<mimeMap fileExtension=".c" mimeType="text/plain" />
<mimeMap fileExtension=".cab" mimeType="application/vnd.ms-cab-compressed" />
<mimeMap fileExtension=".calx" mimeType="application/vnd.ms-office.calx" />
<mimeMap fileExtension=".cat" mimeType="application/vnd.ms-pki.seccat" />
<mimeMap fileExtension=".cdf" mimeType="application/x-cdf" />
<mimeMap fileExtension=".chm" mimeType="application/octet-stream" />
<mimeMap fileExtension=".class" mimeType="application/x-java-applet" />
<mimeMap fileExtension=".clp" mimeType="application/x-msclip" />
<mimeMap fileExtension=".cmx" mimeType="image/x-cmx" />
<mimeMap fileExtension=".cnf" mimeType="text/plain" />
<mimeMap fileExtension=".cod" mimeType="image/cis-cod" />
<mimeMap fileExtension=".cpio" mimeType="application/x-cpio" />
<mimeMap fileExtension=".cpp" mimeType="text/plain" />
<mimeMap fileExtension=".crd" mimeType="application/x-mscardfile" />
<mimeMap fileExtension=".crl" mimeType="application/pkix-crl" />
<mimeMap fileExtension=".crt" mimeType="application/x-x509-ca-cert" />
<mimeMap fileExtension=".csh" mimeType="application/x-csh" />
<mimeMap fileExtension=".css" mimeType="text/css" />
<mimeMap fileExtension=".csv" mimeType="application/octet-stream" />
<mimeMap fileExtension=".cur" mimeType="application/octet-stream" />
<mimeMap fileExtension=".dcr" mimeType="application/x-director" />
<mimeMap fileExtension=".deploy" mimeType="application/octet-stream" />
<mimeMap fileExtension=".der" mimeType="application/x-x509-ca-cert" />
<mimeMap fileExtension=".dib" mimeType="image/bmp" />
<mimeMap fileExtension=".dir" mimeType="application/x-director" />
<mimeMap fileExtension=".disco" mimeType="text/xml" />
<mimeMap fileExtension=".dll" mimeType="application/x-msdownload" />
<mimeMap fileExtension=".dll.config" mimeType="text/xml" />
<mimeMap fileExtension=".dlm" mimeType="text/dlm" />
<mimeMap fileExtension=".doc" mimeType="application/msword" />
<mimeMap fileExtension=".docm" mimeType="application/vnd.ms-word.document.macroEnabled.12" />
<mimeMap fileExtension=".docx" mimeType="application/vnd.openxmlformats-officedocument.wordprocessingml.document" />
<mimeMap fileExtension=".dot" mimeType="application/msword" />
<mimeMap fileExtension=".dotm" mimeType="application/vnd.ms-word.template.macroEnabled.12" />
<mimeMap fileExtension=".dotx" mimeType="application/vnd.openxmlformats-officedocument.wordprocessingml.template" />
<mimeMap fileExtension=".dsp" mimeType="application/octet-stream" />
<mimeMap fileExtension=".dtd" mimeType="text/xml" />
<mimeMap fileExtension=".dvi" mimeType="application/x-dvi" />
<mimeMap fileExtension=".dvr-ms" mimeType="video/x-ms-dvr" />
<mimeMap fileExtension=".dwf" mimeType="drawing/x-dwf" />
<mimeMap fileExtension=".dwp" mimeType="application/octet-stream" />
<mimeMap fileExtension=".dxr" mimeType="application/x-director" />
<mimeMap fileExtension=".eml" mimeType="message/rfc822" />
<mimeMap fileExtension=".emz" mimeType="application/octet-stream" />
<mimeMap fileExtension=".eot" mimeType="application/vnd.ms-fontobject" />
<mimeMap fileExtension=".eps" mimeType="application/postscript" />
<mimeMap fileExtension=".etx" mimeType="text/x-setext" />
<mimeMap fileExtension=".evy" mimeType="application/envoy" />
<mimeMap fileExtension=".exe" mimeType="application/octet-stream" />
<mimeMap fileExtension=".exe.config" mimeType="text/xml" />
<mimeMap fileExtension=".fdf" mimeType="application/vnd.fdf" />
<mimeMap fileExtension=".fif" mimeType="application/fractals" />
<mimeMap fileExtension=".fla" mimeType="application/octet-stream" />
<mimeMap fileExtension=".flr" mimeType="x-world/x-vrml" />
<mimeMap fileExtension=".flv" mimeType="video/x-flv" />
<mimeMap fileExtension=".gif" mimeType="image/gif" />
<mimeMap fileExtension=".gtar" mimeType="application/x-gtar" />
<mimeMap fileExtension=".gz" mimeType="application/x-gzip" />
<mimeMap fileExtension=".h" mimeType="text/plain" />
<mimeMap fileExtension=".hdf" mimeType="application/x-hdf" />
<mimeMap fileExtension=".hdml" mimeType="text/x-hdml" />
<mimeMap fileExtension=".hhc" mimeType="application/x-oleobject" />
<mimeMap fileExtension=".hhk" mimeType="application/octet-stream" />
<mimeMap fileExtension=".hhp" mimeType="application/octet-stream" />
<mimeMap fileExtension=".hlp" mimeType="application/winhlp" />
<mimeMap fileExtension=".hqx" mimeType="application/mac-binhex40" />
<mimeMap fileExtension=".hta" mimeType="application/hta" />
<mimeMap fileExtension=".htc" mimeType="text/x-component" />
<mimeMap fileExtension=".htm" mimeType="text/html" />
<mimeMap fileExtension=".html" mimeType="text/html" />
<mimeMap fileExtension=".htt" mimeType="text/webviewhtml" />
<mimeMap fileExtension=".hxt" mimeType="text/html" />
<mimeMap fileExtension=".ical" mimeType="text/calendar" />
<mimeMap fileExtension=".icalendar" mimeType="text/calendar" />
<mimeMap fileExtension=".ico" mimeType="image/x-icon" />
<mimeMap fileExtension=".ics" mimeType="text/calendar" />
<mimeMap fileExtension=".ief" mimeType="image/ief" />
<mimeMap fileExtension=".ifb" mimeType="text/calendar" />
<mimeMap fileExtension=".iii" mimeType="application/x-iphone" />
<mimeMap fileExtension=".inf" mimeType="application/octet-stream" />
<mimeMap fileExtension=".ins" mimeType="application/x-internet-signup" />
<mimeMap fileExtension=".isp" mimeType="application/x-internet-signup" />
<mimeMap fileExtension=".IVF" mimeType="video/x-ivf" />
<mimeMap fileExtension=".jar" mimeType="application/java-archive" />
<mimeMap fileExtension=".java" mimeType="application/octet-stream" />
<mimeMap fileExtension=".jck" mimeType="application/liquidmotion" />
<mimeMap fileExtension=".jcz" mimeType="application/liquidmotion" />
<mimeMap fileExtension=".jfif" mimeType="image/pjpeg" />
<mimeMap fileExtension=".jpb" mimeType="application/octet-stream" />
<mimeMap fileExtension=".jpe" mimeType="image/jpeg" />
<mimeMap fileExtension=".jpeg" mimeType="image/jpeg" />
<mimeMap fileExtension=".jpg" mimeType="image/jpeg" />
<mimeMap fileExtension=".js" mimeType="application/javascript" />
<mimeMap fileExtension=".json" mimeType="application/json" />
<mimeMap fileExtension=".jsx" mimeType="text/jscript" />
<mimeMap fileExtension=".latex" mimeType="application/x-latex" />
<mimeMap fileExtension=".lit" mimeType="application/x-ms-reader" />
<mimeMap fileExtension=".lpk" mimeType="application/octet-stream" />
<mimeMap fileExtension=".lsf" mimeType="video/x-la-asf" />
<mimeMap fileExtension=".lsx" mimeType="video/x-la-asf" />
<mimeMap fileExtension=".lzh" mimeType="application/octet-stream" />
<mimeMap fileExtension=".m13" mimeType="application/x-msmediaview" />
<mimeMap fileExtension=".m14" mimeType="application/x-msmediaview" />
<mimeMap fileExtension=".m1v" mimeType="video/mpeg" />
<mimeMap fileExtension=".m2ts" mimeType="video/vnd.dlna.mpeg-tts" />
<mimeMap fileExtension=".m3u" mimeType="audio/x-mpegurl" />
<mimeMap fileExtension=".m4a" mimeType="audio/mp4" />
<mimeMap fileExtension=".m4v" mimeType="video/mp4" />
<mimeMap fileExtension=".man" mimeType="application/x-troff-man" />
<mimeMap fileExtension=".manifest" mimeType="application/x-ms-manifest" />
<mimeMap fileExtension=".map" mimeType="text/plain" />
<mimeMap fileExtension=".mdb" mimeType="application/x-msaccess" />
<mimeMap fileExtension=".mdp" mimeType="application/octet-stream" />
<mimeMap fileExtension=".me" mimeType="application/x-troff-me" />
<mimeMap fileExtension=".mht" mimeType="message/rfc822" />
<mimeMap fileExtension=".mhtml" mimeType="message/rfc822" />
<mimeMap fileExtension=".mid" mimeType="audio/mid" />
<mimeMap fileExtension=".midi" mimeType="audio/mid" />
<mimeMap fileExtension=".mix" mimeType="application/octet-stream" />
<mimeMap fileExtension=".mmf" mimeType="application/x-smaf" />
<mimeMap fileExtension=".mno" mimeType="text/xml" />
<mimeMap fileExtension=".mny" mimeType="application/x-msmoney" />
<mimeMap fileExtension=".mov" mimeType="video/quicktime" />
<mimeMap fileExtension=".movie" mimeType="video/x-sgi-movie" />
<mimeMap fileExtension=".mp2" mimeType="video/mpeg" />
<mimeMap fileExtension=".mp3" mimeType="audio/mpeg" />
<mimeMap fileExtension=".mp4" mimeType="video/mp4" />
<mimeMap fileExtension=".mp4v" mimeType="video/mp4" />
<mimeMap fileExtension=".mpa" mimeType="video/mpeg" />
<mimeMap fileExtension=".mpe" mimeType="video/mpeg" />
<mimeMap fileExtension=".mpeg" mimeType="video/mpeg" />
<mimeMap fileExtension=".mpg" mimeType="video/mpeg" />
<mimeMap fileExtension=".mpp" mimeType="application/vnd.ms-project" />
<mimeMap fileExtension=".mpv2" mimeType="video/mpeg" />
<mimeMap fileExtension=".ms" mimeType="application/x-troff-ms" />
<mimeMap fileExtension=".msi" mimeType="application/octet-stream" />
<mimeMap fileExtension=".mso" mimeType="application/octet-stream" />
<mimeMap fileExtension=".mvb" mimeType="application/x-msmediaview" />
<mimeMap fileExtension=".mvc" mimeType="application/x-miva-compiled" />
<mimeMap fileExtension=".nc" mimeType="application/x-netcdf" />
<mimeMap fileExtension=".nsc" mimeType="video/x-ms-asf" />
<mimeMap fileExtension=".nws" mimeType="message/rfc822" />
<mimeMap fileExtension=".ocx" mimeType="application/octet-stream" />
<mimeMap fileExtension=".oda" mimeType="application/oda" />
<mimeMap fileExtension=".odc" mimeType="text/x-ms-odc" />
<mimeMap fileExtension=".ods" mimeType="application/oleobject" />
<mimeMap fileExtension=".oga" mimeType="audio/ogg" />
<mimeMap fileExtension=".ogg" mimeType="video/ogg" />
<mimeMap fileExtension=".ogv" mimeType="video/ogg" />
<mimeMap fileExtension=".ogx" mimeType="application/ogg" />
<mimeMap fileExtension=".one" mimeType="application/onenote" />
<mimeMap fileExtension=".onea" mimeType="application/onenote" />
<mimeMap fileExtension=".onetoc" mimeType="application/onenote" />
<mimeMap fileExtension=".onetoc2" mimeType="application/onenote" />
<mimeMap fileExtension=".onetmp" mimeType="application/onenote" />
<mimeMap fileExtension=".onepkg" mimeType="application/onenote" />
<mimeMap fileExtension=".osdx" mimeType="application/opensearchdescription+xml" />
<mimeMap fileExtension=".otf" mimeType="font/otf" />
<mimeMap fileExtension=".p10" mimeType="application/pkcs10" />
<mimeMap fileExtension=".p12" mimeType="application/x-pkcs12" />
<mimeMap fileExtension=".p7b" mimeType="application/x-pkcs7-certificates" />
<mimeMap fileExtension=".p7c" mimeType="application/pkcs7-mime" />
<mimeMap fileExtension=".p7m" mimeType="application/pkcs7-mime" />
<mimeMap fileExtension=".p7r" mimeType="application/x-pkcs7-certreqresp" />
<mimeMap fileExtension=".p7s" mimeType="application/pkcs7-signature" />
<mimeMap fileExtension=".pbm" mimeType="image/x-portable-bitmap" />
<mimeMap fileExtension=".pcx" mimeType="application/octet-stream" />
<mimeMap fileExtension=".pcz" mimeType="application/octet-stream" />
<mimeMap fileExtension=".pdf" mimeType="application/pdf" />
<mimeMap fileExtension=".pfb" mimeType="application/octet-stream" />
<mimeMap fileExtension=".pfm" mimeType="application/octet-stream" />
<mimeMap fileExtension=".pfx" mimeType="application/x-pkcs12" />
<mimeMap fileExtension=".pgm" mimeType="image/x-portable-graymap" />
<mimeMap fileExtension=".pko" mimeType="application/vnd.ms-pki.pko" />
<mimeMap fileExtension=".pma" mimeType="application/x-perfmon" />
<mimeMap fileExtension=".pmc" mimeType="application/x-perfmon" />
<mimeMap fileExtension=".pml" mimeType="application/x-perfmon" />
<mimeMap fileExtension=".pmr" mimeType="application/x-perfmon" />
<mimeMap fileExtension=".pmw" mimeType="application/x-perfmon" />
<mimeMap fileExtension=".png" mimeType="image/png" />
<mimeMap fileExtension=".pnm" mimeType="image/x-portable-anymap" />
<mimeMap fileExtension=".pnz" mimeType="image/png" />
<mimeMap fileExtension=".pot" mimeType="application/vnd.ms-powerpoint" />
<mimeMap fileExtension=".potm" mimeType="application/vnd.ms-powerpoint.template.macroEnabled.12" />
<mimeMap fileExtension=".potx" mimeType="application/vnd.openxmlformats-officedocument.presentationml.template" />
<mimeMap fileExtension=".ppam" mimeType="application/vnd.ms-powerpoint.addin.macroEnabled.12" />
<mimeMap fileExtension=".ppm" mimeType="image/x-portable-pixmap" />
<mimeMap fileExtension=".pps" mimeType="application/vnd.ms-powerpoint" />
<mimeMap fileExtension=".ppsm" mimeType="application/vnd.ms-powerpoint.slideshow.macroEnabled.12" />
<mimeMap fileExtension=".ppsx" mimeType="application/vnd.openxmlformats-officedocument.presentationml.slideshow" />
<mimeMap fileExtension=".ppt" mimeType="application/vnd.ms-powerpoint" />
<mimeMap fileExtension=".pptm" mimeType="application/vnd.ms-powerpoint.presentation.macroEnabled.12" />
<mimeMap fileExtension=".pptx" mimeType="application/vnd.openxmlformats-officedocument.presentationml.presentation" />
<mimeMap fileExtension=".prf" mimeType="application/pics-rules" />
<mimeMap fileExtension=".prm" mimeType="application/octet-stream" />
<mimeMap fileExtension=".prx" mimeType="application/octet-stream" />
<mimeMap fileExtension=".ps" mimeType="application/postscript" />
<mimeMap fileExtension=".psd" mimeType="application/octet-stream" />
<mimeMap fileExtension=".psm" mimeType="application/octet-stream" />
<mimeMap fileExtension=".psp" mimeType="application/octet-stream" />
<mimeMap fileExtension=".pub" mimeType="application/x-mspublisher" />
<mimeMap fileExtension=".qt" mimeType="video/quicktime" />
<mimeMap fileExtension=".qtl" mimeType="application/x-quicktimeplayer" />
<mimeMap fileExtension=".qxd" mimeType="application/octet-stream" />
<mimeMap fileExtension=".ra" mimeType="audio/x-pn-realaudio" />
<mimeMap fileExtension=".ram" mimeType="audio/x-pn-realaudio" />
<mimeMap fileExtension=".rar" mimeType="application/octet-stream" />
<mimeMap fileExtension=".ras" mimeType="image/x-cmu-raster" />
<mimeMap fileExtension=".rf" mimeType="image/vnd.rn-realflash" />
<mimeMap fileExtension=".rgb" mimeType="image/x-rgb" />
<mimeMap fileExtension=".rm" mimeType="application/vnd.rn-realmedia" />
<mimeMap fileExtension=".rmi" mimeType="audio/mid" />
<mimeMap fileExtension=".roff" mimeType="application/x-troff" />
<mimeMap fileExtension=".rpm" mimeType="audio/x-pn-realaudio-plugin" />
<mimeMap fileExtension=".rtf" mimeType="application/rtf" />
<mimeMap fileExtension=".rtx" mimeType="text/richtext" />
<mimeMap fileExtension=".scd" mimeType="application/x-msschedule" />
<mimeMap fileExtension=".sct" mimeType="text/scriptlet" />
<mimeMap fileExtension=".sea" mimeType="application/octet-stream" />
<mimeMap fileExtension=".setpay" mimeType="application/set-payment-initiation" />
<mimeMap fileExtension=".setreg" mimeType="application/set-registration-initiation" />
<mimeMap fileExtension=".sgml" mimeType="text/sgml" />
<mimeMap fileExtension=".sh" mimeType="application/x-sh" />
<mimeMap fileExtension=".shar" mimeType="application/x-shar" />
<mimeMap fileExtension=".sit" mimeType="application/x-stuffit" />
<mimeMap fileExtension=".sldm" mimeType="application/vnd.ms-powerpoint.slide.macroEnabled.12" />
<mimeMap fileExtension=".sldx" mimeType="application/vnd.openxmlformats-officedocument.presentationml.slide" />
<mimeMap fileExtension=".smd" mimeType="audio/x-smd" />
<mimeMap fileExtension=".smi" mimeType="application/octet-stream" />
<mimeMap fileExtension=".smx" mimeType="audio/x-smd" />
<mimeMap fileExtension=".smz" mimeType="audio/x-smd" />
<mimeMap fileExtension=".snd" mimeType="audio/basic" />
<mimeMap fileExtension=".snp" mimeType="application/octet-stream" />
<mimeMap fileExtension=".spc" mimeType="application/x-pkcs7-certificates" />
<mimeMap fileExtension=".spl" mimeType="application/futuresplash" />
<mimeMap fileExtension=".spx" mimeType="audio/ogg" />
<mimeMap fileExtension=".src" mimeType="application/x-wais-source" />
<mimeMap fileExtension=".ssm" mimeType="application/streamingmedia" />
<mimeMap fileExtension=".sst" mimeType="application/vnd.ms-pki.certstore" />
<mimeMap fileExtension=".stl" mimeType="application/vnd.ms-pki.stl" />
<mimeMap fileExtension=".sv4cpio" mimeType="application/x-sv4cpio" />
<mimeMap fileExtension=".sv4crc" mimeType="application/x-sv4crc" />
<mimeMap fileExtension=".svg" mimeType="image/svg+xml" />
<mimeMap fileExtension=".svgz" mimeType="image/svg+xml" />
<mimeMap fileExtension=".swf" mimeType="application/x-shockwave-flash" />
<mimeMap fileExtension=".t" mimeType="application/x-troff" />
<mimeMap fileExtension=".tar" mimeType="application/x-tar" />
<mimeMap fileExtension=".tcl" mimeType="application/x-tcl" />
<mimeMap fileExtension=".tex" mimeType="application/x-tex" />
<mimeMap fileExtension=".texi" mimeType="application/x-texinfo" />
<mimeMap fileExtension=".texinfo" mimeType="application/x-texinfo" />
<mimeMap fileExtension=".tgz" mimeType="application/x-compressed" />
<mimeMap fileExtension=".thmx" mimeType="application/vnd.ms-officetheme" />
<mimeMap fileExtension=".thn" mimeType="application/octet-stream" />
<mimeMap fileExtension=".tif" mimeType="image/tiff" />
<mimeMap fileExtension=".tiff" mimeType="image/tiff" />
<mimeMap fileExtension=".toc" mimeType="application/octet-stream" />
<mimeMap fileExtension=".tr" mimeType="application/x-troff" />
<mimeMap fileExtension=".trm" mimeType="application/x-msterminal" />
<mimeMap fileExtension=".ts" mimeType="video/vnd.dlna.mpeg-tts" />
<mimeMap fileExtension=".tsv" mimeType="text/tab-separated-values" />
<mimeMap fileExtension=".ttf" mimeType="application/octet-stream" />
<mimeMap fileExtension=".tts" mimeType="video/vnd.dlna.mpeg-tts" />
<mimeMap fileExtension=".txt" mimeType="text/plain" />
<mimeMap fileExtension=".u32" mimeType="application/octet-stream" />
<mimeMap fileExtension=".uls" mimeType="text/iuls" />
<mimeMap fileExtension=".ustar" mimeType="application/x-ustar" />
<mimeMap fileExtension=".vbs" mimeType="text/vbscript" />
<mimeMap fileExtension=".vcf" mimeType="text/x-vcard" />
<mimeMap fileExtension=".vcs" mimeType="text/plain" />
<mimeMap fileExtension=".vdx" mimeType="application/vnd.ms-visio.viewer" />
<mimeMap fileExtension=".vml" mimeType="text/xml" />
<mimeMap fileExtension=".vsd" mimeType="application/vnd.visio" />
<mimeMap fileExtension=".vss" mimeType="application/vnd.visio" />
<mimeMap fileExtension=".vst" mimeType="application/vnd.visio" />
<mimeMap fileExtension=".vsto" mimeType="application/x-ms-vsto" />
<mimeMap fileExtension=".vsw" mimeType="application/vnd.visio" />
<mimeMap fileExtension=".vsx" mimeType="application/vnd.visio" />
<mimeMap fileExtension=".vtx" mimeType="application/vnd.visio" />
<mimeMap fileExtension=".wav" mimeType="audio/wav" />
<mimeMap fileExtension=".wax" mimeType="audio/x-ms-wax" />
<mimeMap fileExtension=".wbmp" mimeType="image/vnd.wap.wbmp" />
<mimeMap fileExtension=".wcm" mimeType="application/vnd.ms-works" />
<mimeMap fileExtension=".wdb" mimeType="application/vnd.ms-works" />
<mimeMap fileExtension=".webm" mimeType="video/webm" />
<mimeMap fileExtension=".wks" mimeType="application/vnd.ms-works" />
<mimeMap fileExtension=".wm" mimeType="video/x-ms-wm" />
<mimeMap fileExtension=".wma" mimeType="audio/x-ms-wma" />
<mimeMap fileExtension=".wmd" mimeType="application/x-ms-wmd" />
<mimeMap fileExtension=".wmf" mimeType="application/x-msmetafile" />
<mimeMap fileExtension=".wml" mimeType="text/vnd.wap.wml" />
<mimeMap fileExtension=".wmlc" mimeType="application/vnd.wap.wmlc" />
<mimeMap fileExtension=".wmls" mimeType="text/vnd.wap.wmlscript" />
<mimeMap fileExtension=".wmlsc" mimeType="application/vnd.wap.wmlscriptc" />
<mimeMap fileExtension=".wmp" mimeType="video/x-ms-wmp" />
<mimeMap fileExtension=".wmv" mimeType="video/x-ms-wmv" />
<mimeMap fileExtension=".wmx" mimeType="video/x-ms-wmx" />
<mimeMap fileExtension=".wmz" mimeType="application/x-ms-wmz" />
<mimeMap fileExtension=".woff" mimeType="font/x-woff" />
<mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />
<mimeMap fileExtension=".wps" mimeType="application/vnd.ms-works" />
<mimeMap fileExtension=".wri" mimeType="application/x-mswrite" />
<mimeMap fileExtension=".wrl" mimeType="x-world/x-vrml" />
<mimeMap fileExtension=".wrz" mimeType="x-world/x-vrml" />
<mimeMap fileExtension=".wsdl" mimeType="text/xml" />
<mimeMap fileExtension=".wtv" mimeType="video/x-ms-wtv" />
<mimeMap fileExtension=".wvx" mimeType="video/x-ms-wvx" />
<mimeMap fileExtension=".x" mimeType="application/directx" />
<mimeMap fileExtension=".xaf" mimeType="x-world/x-vrml" />
<mimeMap fileExtension=".xaml" mimeType="application/xaml+xml" />
<mimeMap fileExtension=".xap" mimeType="application/x-silverlight-app" />
<mimeMap fileExtension=".xbap" mimeType="application/x-ms-xbap" />
<mimeMap fileExtension=".xbm" mimeType="image/x-xbitmap" />
<mimeMap fileExtension=".xdr" mimeType="text/plain" />
<mimeMap fileExtension=".xht" mimeType="application/xhtml+xml" />
<mimeMap fileExtension=".xhtml" mimeType="application/xhtml+xml" />
<mimeMap fileExtension=".xla" mimeType="application/vnd.ms-excel" />
<mimeMap fileExtension=".xlam" mimeType="application/vnd.ms-excel.addin.macroEnabled.12" />
<mimeMap fileExtension=".xlc" mimeType="application/vnd.ms-excel" />
<mimeMap fileExtension=".xlm" mimeType="application/vnd.ms-excel" />
<mimeMap fileExtension=".xls" mimeType="application/vnd.ms-excel" />
<mimeMap fileExtension=".xlsb" mimeType="application/vnd.ms-excel.sheet.binary.macroEnabled.12" />
<mimeMap fileExtension=".xlsm" mimeType="application/vnd.ms-excel.sheet.macroEnabled.12" />
<mimeMap fileExtension=".xlsx" mimeType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />
<mimeMap fileExtension=".xlt" mimeType="application/vnd.ms-excel" />
<mimeMap fileExtension=".xltm" mimeType="application/vnd.ms-excel.template.macroEnabled.12" />
<mimeMap fileExtension=".xltx" mimeType="application/vnd.openxmlformats-officedocument.spreadsheetml.template" />
<mimeMap fileExtension=".xlw" mimeType="application/vnd.ms-excel" />
<mimeMap fileExtension=".xml" mimeType="text/xml" />
<mimeMap fileExtension=".xof" mimeType="x-world/x-vrml" />
<mimeMap fileExtension=".xpm" mimeType="image/x-xpixmap" />
<mimeMap fileExtension=".xps" mimeType="application/vnd.ms-xpsdocument" />
<mimeMap fileExtension=".xsd" mimeType="text/xml" />
<mimeMap fileExtension=".xsf" mimeType="text/xml" />
<mimeMap fileExtension=".xsl" mimeType="text/xml" />
<mimeMap fileExtension=".xslt" mimeType="text/xml" />
<mimeMap fileExtension=".xsn" mimeType="application/octet-stream" />
<mimeMap fileExtension=".xtp" mimeType="application/octet-stream" />
<mimeMap fileExtension=".xwd" mimeType="image/x-xwindowdump" />
<mimeMap fileExtension=".z" mimeType="application/x-compress" />
<mimeMap fileExtension=".zip" mimeType="application/x-zip-compressed" />
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="30.00:00:00" />
</staticContent>
<tracing>
<traceProviderDefinitions>
<add name="ASPNET" guid="{AFF081FE-0247-4275-9C4E-021F3DC1DA35}">
<areas>
<add name="Infrastructure" value="1" />
<add name="Module" value="2" />
<add name="Page" value="4" />
<add name="AppServices" value="8" />
</areas>
</add>
<add name="WWW Server" guid="{3a2a4e84-4c21-4981-ae10-3fda0d9b0f83}">
<areas>
<clear />
<add name="Authentication" value="2" />
<add name="Security" value="4" />
<add name="Filter" value="8" />
<add name="StaticFile" value="16" />
<add name="CGI" value="32" />
<add name="Compression" value="64" />
<add name="Cache" value="128" />
<add name="RequestNotifications" value="256" />
<add name="Module" value="512" />
<add name="FastCGI" value="4096" />
</areas>
</add>
<add name="ASP" guid="{06b94d9a-b15e-456e-a4ef-37c984a2cb4b}">
<areas>
<clear />
</areas>
</add>
<add name="ISAPI Extension" guid="{a1c2040e-8840-4c31-ba11-9871031a19ea}">
<areas>
<clear />
</areas>
</add>
</traceProviderDefinitions>
<traceFailedRequests>
<add path="*">
<traceAreas>
<add provider="ASP" verbosity="Verbose" />
<add provider="ASPNET" areas="Infrastructure,Module,Page,AppServices" verbosity="Verbose" />
<add provider="ISAPI Extension" verbosity="Verbose" />
<add provider="WWW Server" areas="Authentication,Security,Filter,StaticFile,CGI,Compression,Cache,RequestNotifications,Module" verbosity="Verbose" />
</traceAreas>
<failureDefinitions statusCodes="200-999" />
</add>
</traceFailedRequests>
</tracing>
<urlCompression />
<validation />
</system.webServer>
<system.webServer>
<modules>
<add name="HttpCacheModule" lockItem="true" />
<add name="StaticCompressionModule" lockItem="true" />
<add name="DefaultDocumentModule" lockItem="true" />
<add name="DirectoryListingModule" lockItem="true" />
<add name="IsapiFilterModule" lockItem="true" />
<add name="ProtocolSupportModule" lockItem="true" />
<add name="StaticFileModule" lockItem="true" />
<add name="AnonymousAuthenticationModule" lockItem="true" />
<add name="WindowsAuthenticationModule" lockItem="true" />
<add name="RequestFilteringModule" lockItem="true" />
<add name="CustomErrorModule" lockItem="true" />
<add name="IsapiModule" lockItem="true" />
<add name="HttpLoggingModule" lockItem="true" />
<add name="ConfigurationValidationModule" lockItem="true" />
<add name="OutputCache" type="System.Web.Caching.OutputCacheModule" preCondition="managedHandler" />
<add name="Session" type="System.Web.SessionState.SessionStateModule" preCondition="managedHandler" />
<add name="WindowsAuthentication" type="System.Web.Security.WindowsAuthenticationModule" preCondition="managedHandler" />
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />
<add name="DefaultAuthentication" type="System.Web.Security.DefaultAuthenticationModule" preCondition="managedHandler" />
<add name="RoleManager" type="System.Web.Security.RoleManagerModule" preCondition="managedHandler" />
<add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule" preCondition="managedHandler" />
<add name="FileAuthorization" type="System.Web.Security.FileAuthorizationModule" preCondition="managedHandler" />
<add name="AnonymousIdentification" type="System.Web.Security.AnonymousIdentificationModule" preCondition="managedHandler" />
<add name="Profile" type="System.Web.Profile.ProfileModule" preCondition="managedHandler" />
<add name="UrlMappingsModule" type="System.Web.UrlMappingsModule" preCondition="managedHandler" />
<add name="ServiceModel" type="System.ServiceModel.Activation.HttpModule, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler,runtimeVersionv2.0" />
<add name="ServiceModel-4.0" type="System.ServiceModel.Activation.ServiceHttpModule, System.ServiceModel.Activation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" preCondition="managedHandler,runtimeVersionv4.0" />
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="managedHandler,runtimeVersionv4.0" />
<add name="ScriptModule-4.0" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" preCondition="managedHandler,runtimeVersionv4.0" />
<add name="CustomLoggingModule" lockItem="true" />
<add name="FailedRequestsTracingModule" lockItem="true" />
<add name="WebSocketModule" lockItem="true" />
<add name="HttpRedirectionModule" lockItem="true" />
<add name="CertificateMappingAuthenticationModule" lockItem="true" />
<add name="UrlAuthorizationModule" lockItem="true" />
<add name="DigestAuthenticationModule" lockItem="true" />
<add name="IISCertificateMappingAuthenticationModule" lockItem="true" />
<add name="IpRestrictionModule" lockItem="true" />
{{if .Rewrite}}
<add name="RewriteModule" />
{{end}}
</modules>
<handlers accessPolicy="Read, Script">
<add name="ASP Classic" path="*.asp" verb="GET,HEAD,POST" modules="IsapiModule" scriptProcessor="%windir%\system32\inetsrv\asp.dll" resourceType="File" />
<add name="ISAPI-dll" path="*.dll" verb="*" modules="IsapiModule" resourceType="File" requireAccess="Execute" allowPathInfo="true" />
<add name="AXD-ISAPI-4.0_32bit" path="*.axd" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="PageHandlerFactory-ISAPI-4.0_32bit" path="*.aspx" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="SimpleHandlerFactory-ISAPI-4.0_32bit" path="*.ashx" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="WebServiceHandlerFactory-ISAPI-4.0_32bit" path="*.asmx" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="HttpRemotingHandlerFactory-rem-ISAPI-4.0_32bit" path="*.rem" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="HttpRemotingHandlerFactory-soap-ISAPI-4.0_32bit" path="*.soap" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="svc-ISAPI-4.0_32bit" path="*.svc" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="rules-ISAPI-4.0_32bit" path="*.rules" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="xoml-ISAPI-4.0_32bit" path="*.xoml" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="xamlx-ISAPI-4.0_32bit" path="*.xamlx" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="aspq-ISAPI-4.0_32bit" path="*.aspq" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="cshtm-ISAPI-4.0_32bit" path="*.cshtm" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="cshtml-ISAPI-4.0_32bit" path="*.cshtml" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="vbhtm-ISAPI-4.0_32bit" path="*.vbhtm" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="vbhtml-ISAPI-4.0_32bit" path="*.vbhtml" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="AXD-ISAPI-4.0_64bit" path="*.axd" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="PageHandlerFactory-ISAPI-4.0_64bit" path="*.aspx" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="SimpleHandlerFactory-ISAPI-4.0_64bit" path="*.ashx" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="WebServiceHandlerFactory-ISAPI-4.0_64bit" path="*.asmx" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="HttpRemotingHandlerFactory-rem-ISAPI-4.0_64bit" path="*.rem" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="HttpRemotingHandlerFactory-soap-ISAPI-4.0_64bit" path="*.soap" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="svc-ISAPI-4.0_64bit" path="*.svc" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="rules-ISAPI-4.0_64bit" path="*.rules" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="xoml-ISAPI-4.0_64bit" path="*.xoml" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="xamlx-ISAPI-4.0_64bit" path="*.xamlx" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="aspq-ISAPI-4.0_64bit" path="*.aspq" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="cshtm-ISAPI-4.0_64bit" path="*.cshtm" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="cshtml-ISAPI-4.0_64bit" path="*.cshtml" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="vbhtm-ISAPI-4.0_64bit" path="*.vbhtm" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="vbhtml-ISAPI-4.0_64bit" path="*.vbhtml" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="TraceHandler-Integrated-4.0" path="trace.axd" verb="GET,HEAD,POST,DEBUG" type="System.Web.Handlers.TraceHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="WebAdminHandler-Integrated-4.0" path="WebAdmin.axd" verb="GET,DEBUG" type="System.Web.Handlers.WebAdminHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="AssemblyResourceLoader-Integrated-4.0" path="WebResource.axd" verb="GET,DEBUG" type="System.Web.Handlers.AssemblyResourceLoader" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="PageHandlerFactory-Integrated-4.0" path="*.aspx" verb="GET,HEAD,POST,DEBUG" type="System.Web.UI.PageHandlerFactory" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="SimpleHandlerFactory-Integrated-4.0" path="*.ashx" verb="GET,HEAD,POST,DEBUG" type="System.Web.UI.SimpleHandlerFactory" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="WebServiceHandlerFactory-Integrated-4.0" path="*.asmx" verb="GET,HEAD,POST,DEBUG" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="HttpRemotingHandlerFactory-rem-Integrated-4.0" path="*.rem" verb="GET,HEAD,POST,DEBUG" type="System.Runtime.Remoting.Channels.Http.HttpRemotingHandlerFactory, System.Runtime.Remoting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="HttpRemotingHandlerFactory-soap-Integrated-4.0" path="*.soap" verb="GET,HEAD,POST,DEBUG" type="System.Runtime.Remoting.Channels.Http.HttpRemotingHandlerFactory, System.Runtime.Remoting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="svc-Integrated-4.0" path="*.svc" verb="*" type="System.ServiceModel.Activation.ServiceHttpHandlerFactory, System.ServiceModel.Activation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="rules-Integrated-4.0" path="*.rules" verb="*" type="System.ServiceModel.Activation.ServiceHttpHandlerFactory, System.ServiceModel.Activation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="xoml-Integrated-4.0" path="*.xoml" verb="*" type="System.ServiceModel.Activation.ServiceHttpHandlerFactory, System.ServiceModel.Activation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="xamlx-Integrated-4.0" path="*.xamlx" verb="GET,HEAD,POST,DEBUG" type="System.Xaml.Hosting.XamlHttpHandlerFactory, System.Xaml.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="aspq-Integrated-4.0" path="*.aspq" verb="GET,HEAD,POST,DEBUG" type="System.Web.HttpForbiddenHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="cshtm-Integrated-4.0" path="*.cshtm" verb="GET,HEAD,POST,DEBUG" type="System.Web.HttpForbiddenHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="cshtml-Integrated-4.0" path="*.cshtml" verb="GET,HEAD,POST,DEBUG" type="System.Web.HttpForbiddenHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="vbhtm-Integrated-4.0" path="*.vbhtm" verb="GET,HEAD,POST,DEBUG" type="System.Web.HttpForbiddenHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="vbhtml-Integrated-4.0" path="*.vbhtml" verb="GET,HEAD,POST,DEBUG" type="System.Web.HttpForbiddenHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="ScriptHandlerFactoryAppServices-Integrated-4.0" path="*_AppService.axd" verb="*" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="ScriptResourceIntegrated-4.0" path="ScriptResource.axd" verb="GET,HEAD" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="TraceHandler-Integrated" path="trace.axd" verb="GET,HEAD,POST,DEBUG" type="System.Web.Handlers.TraceHandler" preCondition="integratedMode" />
<add name="WebAdminHandler-Integrated" path="WebAdmin.axd" verb="GET,DEBUG" type="System.Web.Handlers.WebAdminHandler" preCondition="integratedMode" />
<add name="AssemblyResourceLoader-Integrated" path="WebResource.axd" verb="GET,DEBUG" type="System.Web.Handlers.AssemblyResourceLoader" preCondition="integratedMode" />
<add name="PageHandlerFactory-Integrated" path="*.aspx" verb="GET,HEAD,POST,DEBUG" type="System.Web.UI.PageHandlerFactory" preCondition="integratedMode" />
<add name="SimpleHandlerFactory-Integrated" path="*.ashx" verb="GET,HEAD,POST,DEBUG" type="System.Web.UI.SimpleHandlerFactory" preCondition="integratedMode" />
<add name="WebServiceHandlerFactory-Integrated" path="*.asmx" verb="GET,HEAD,POST,DEBUG" type="System.Web.Services.Protocols.WebServiceHandlerFactory, System.Web.Services, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" preCondition="integratedMode,runtimeVersionv2.0" />
<add name="HttpRemotingHandlerFactory-rem-Integrated" path="*.rem" verb="GET,HEAD,POST,DEBUG" type="System.Runtime.Remoting.Channels.Http.HttpRemotingHandlerFactory, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="integratedMode,runtimeVersionv2.0" />
<add name="HttpRemotingHandlerFactory-soap-Integrated" path="*.soap" verb="GET,HEAD,POST,DEBUG" type="System.Runtime.Remoting.Channels.Http.HttpRemotingHandlerFactory, System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="integratedMode,runtimeVersionv2.0" />
<add name="AXD-ISAPI-2.0" path="*.axd" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv2.0,bitness32" responseBufferLimit="0" />
<add name="PageHandlerFactory-ISAPI-2.0" path="*.aspx" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv2.0,bitness32" responseBufferLimit="0" />
<add name="SimpleHandlerFactory-ISAPI-2.0" path="*.ashx" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv2.0,bitness32" responseBufferLimit="0" />
<add name="WebServiceHandlerFactory-ISAPI-2.0" path="*.asmx" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv2.0,bitness32" responseBufferLimit="0" />
<add name="HttpRemotingHandlerFactory-rem-ISAPI-2.0" path="*.rem" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv2.0,bitness32" responseBufferLimit="0" />
<add name="HttpRemotingHandlerFactory-soap-ISAPI-2.0" path="*.soap" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv2.0,bitness32" responseBufferLimit="0" />
<add name="AXD-ISAPI-2.0-64" path="*.axd" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v2.0.50727\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv2.0,bitness64" responseBufferLimit="0" />
<add name="PageHandlerFactory-ISAPI-2.0-64" path="*.aspx" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v2.0.50727\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv2.0,bitness64" responseBufferLimit="0" />
<add name="SimpleHandlerFactory-ISAPI-2.0-64" path="*.ashx" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v2.0.50727\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv2.0,bitness64" responseBufferLimit="0" />
<add name="WebServiceHandlerFactory-ISAPI-2.0-64" path="*.asmx" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v2.0.50727\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv2.0,bitness64" responseBufferLimit="0" />
<add name="HttpRemotingHandlerFactory-rem-ISAPI-2.0-64" path="*.rem" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v2.0.50727\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv2.0,bitness64" responseBufferLimit="0" />
<add name="HttpRemotingHandlerFactory-soap-ISAPI-2.0-64" path="*.soap" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v2.0.50727\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv2.0,bitness64" responseBufferLimit="0" />
<add name="TRACEVerbHandler" path="*" verb="TRACE" modules="ProtocolSupportModule" requireAccess="None" />
<add name="OPTIONSVerbHandler" path="*" verb="OPTIONS" modules="ProtocolSupportModule" requireAccess="None" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="StaticFile" path="*" verb="*" modules="StaticFileModule,DefaultDocumentModule,DirectoryListingModule" resourceType="Either" requireAccess="Read" />
</handlers>
</system.webServer>
</configuration>
`
| [
"\"WINDIR\""
]
| []
| [
"WINDIR"
]
| [] | ["WINDIR"] | go | 1 | 0 | |
application/cmd/insolar/main.go | // Copyright 2020 Insolar Network Ltd.
// All rights reserved.
// This material is licensed under the Insolar License version 1.0,
// available at https://github.com/insolar/mainnet/blob/master/LICENSE.md.
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"github.com/insolar/insolar/insolar/secrets"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/insolar/mainnet/application/sdk"
"github.com/insolar/insolar/api/requester"
"github.com/insolar/insolar/insolar"
"github.com/insolar/insolar/instrumentation/inslogger"
"github.com/insolar/insolar/platformpolicy"
"github.com/insolar/insolar/version"
"github.com/insolar/mainnet/application/cmd/insolar/insolarcmd"
)
var (
verbose bool
)
func main() {
var sendURL, adminURL string
addURLFlag := func(fs *pflag.FlagSet) {
fs.StringVarP(&sendURL, "url", "u", defaultURL(), "API URL")
fs.StringVarP(&adminURL, "admin-url", "a", defaultAdminURL(), "ADMIN URL")
}
var rootCmd = &cobra.Command{
Use: "insolar",
Short: "insolar is the command line client for Insolar Platform",
}
rootCmd.Flags().BoolVarP(&verbose, "verbose", "v", false, "be verbose (default false)")
var versionCmd = &cobra.Command{
Use: "version",
Short: "Print the version number",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println(version.GetFullVersion())
},
}
rootCmd.AddCommand(versionCmd)
var infoCmd = &cobra.Command{
Use: "get-info",
Short: "info about root member, root domain",
Run: func(cmd *cobra.Command, args []string) {
getInfo(sendURL)
},
}
addURLFlag(infoCmd.Flags())
rootCmd.AddCommand(infoCmd)
var logLevel string
var createMemberCmd = &cobra.Command{
Use: "create-member",
Short: "creates member with random keys pair",
Args: cobra.ExactArgs(1), // username
Run: func(cmd *cobra.Command, args []string) {
createMember(sendURL, args[0], logLevel)
},
}
createMemberCmd.Flags().StringVarP(
&logLevel, "log-level-server", "L", "", "log level passed on server via request")
addURLFlag(createMemberCmd.Flags())
rootCmd.AddCommand(createMemberCmd)
var targetValue string
var genKeysPairCmd = &cobra.Command{
Use: "gen-key-pair",
Short: "generates public/private keys pair",
Run: func(cmd *cobra.Command, args []string) {
generateKeysPair(targetValue)
},
}
genKeysPairCmd.Flags().StringVarP(
&targetValue, "target", "t", "", "target for whom need to generate keys (possible values: node, user)")
rootCmd.AddCommand(genKeysPairCmd)
var addresses int
var genMigrationAddressesCmd = &cobra.Command{
Use: "gen-migration-addresses",
Short: "generates fake migration addresses",
Run: func(cmd *cobra.Command, args []string) {
err := insolarcmd.GenerateMigrationAddresses(os.Stdout, addresses)
check("failed to generate addresses:", err)
},
}
genMigrationAddressesCmd.Flags().IntVarP(
&addresses, "count", "c", 40000, "how many addresses to generate")
rootCmd.AddCommand(genMigrationAddressesCmd)
var rootKeysFile string
var (
paramsPath string
rootAsCaller bool
maAsCaller bool
)
var sendRequestCmd = &cobra.Command{
Use: "send-request",
Short: "sends request",
Run: func(cmd *cobra.Command, args []string) {
sendRequest(sendURL, adminURL, rootKeysFile, paramsPath, rootAsCaller, maAsCaller)
},
}
addURLFlag(sendRequestCmd.Flags())
sendRequestCmd.Flags().StringVarP(
&rootKeysFile, "root-keys", "k", "config.json", "path to json with root key pair")
sendRequestCmd.Flags().StringVarP(
¶msPath, "params", "p", "", "path to params file (default params.json)")
sendRequestCmd.Flags().BoolVarP(
&rootAsCaller, "root-caller", "r", false, "use root member as caller")
sendRequestCmd.Flags().BoolVarP(
&maAsCaller, "migration-admin-caller", "m", false, "use migration admin member as caller")
rootCmd.AddCommand(sendRequestCmd)
var (
role string
reuseKeys bool
keysFile string
certFile string
)
var certgenCmd = &cobra.Command{
Use: "certgen",
Short: "generates keys and cerificate by root config",
Run: func(cmd *cobra.Command, args []string) {
genCertificate(rootKeysFile, role, sendURL, keysFile, certFile, reuseKeys)
},
}
addURLFlag(certgenCmd.Flags())
certgenCmd.Flags().StringVarP(
&rootKeysFile, "root-keys", "k", "", "Config that contains public/private keys of root member")
certgenCmd.Flags().StringVarP(
&role, "role", "r", "virtual", "The role of the new node")
certgenCmd.Flags().BoolVarP(
&reuseKeys, "reuse-keys", "", false, "Read keys from file instead og generating of new ones")
certgenCmd.Flags().StringVarP(
&keysFile,
"node-keys",
"",
"keys.json",
"The OUT/IN ( depends on 'reuse-keys' ) file for public/private keys of the node",
)
certgenCmd.Flags().StringVarP(
&certFile, "node-cert", "c", "cert.json", "The OUT file the node certificate")
rootCmd.AddCommand(certgenCmd)
rootCmd.AddCommand(bootstrapCommand())
var (
configsOutputDir string
)
var generateDefaultConfigs = &cobra.Command{
Use: "generate-config",
Short: "generate default configs for bootstrap, node and pulsar",
Run: func(cmd *cobra.Command, args []string) {
writePulsarConfig(configsOutputDir)
writeBootstrapConfig(configsOutputDir)
writeNodeConfig(configsOutputDir)
writePulseWatcher(configsOutputDir)
},
}
generateDefaultConfigs.Flags().StringVarP(&configsOutputDir, "output_dir", "o", "", "path to output directory")
rootCmd.AddCommand(generateDefaultConfigs)
var (
alertLevel int
shardsCount int
migrationAdminKeys string
)
var freeMigrationCountCmd = &cobra.Command{
Use: "free-migration-count",
Run: func(cmd *cobra.Command, args []string) {
getfreeMigrationCount([]string{adminURL}, []string{sendURL}, migrationAdminKeys, shardsCount, alertLevel)
},
}
addURLFlag(freeMigrationCountCmd.Flags())
freeMigrationCountCmd.Flags().StringVarP(
&migrationAdminKeys, "migration-admin-keys", "k", "",
"Config that contains public/private keys of root member",
)
freeMigrationCountCmd.Flags().IntVarP(
&alertLevel, "alert-level", "l", 0,
"If one of shard have less free addresses than this value, command will print alert message",
)
freeMigrationCountCmd.Flags().IntVarP(
&shardsCount, "shards-count", "s", 10,
"Count of shards at platform (must be a multiple of ten)",
)
rootCmd.AddCommand(freeMigrationCountCmd)
var addressesDir string
var addMigrationAddressesCmd = &cobra.Command{
Use: "add-migration-addresses",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("generate random migration addresses")
err := insolarcmd.AddMigrationAddresses([]string{adminURL}, []string{sendURL}, migrationAdminKeys, addressesDir)
check("", err)
fmt.Println("All addresses were added successfully")
},
}
addURLFlag(addMigrationAddressesCmd.Flags())
addMigrationAddressesCmd.Flags().StringVarP(
&migrationAdminKeys, "migration-admin-keys", "k", "",
"Dir with config that contains public/private keys of admin member",
)
addMigrationAddressesCmd.Flags().StringVarP(
&addressesDir, "addresses-dir", "d", "",
"Path to dir with address files. We expect files will be match generator utility output (from insolar/migrationAddressGenerator)",
)
rootCmd.AddCommand(addMigrationAddressesCmd)
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func defaultURL() string {
if u := os.Getenv("INSOLAR_API_URL"); u != "" {
return u
}
return "http://localhost:19101/api/rpc"
}
func defaultAdminURL() string {
if u := os.Getenv("INSOLAR_ADMIN_URL"); u != "" {
return u
}
return "http://localhost:19001/admin-api/rpc"
}
type mixedConfig struct {
PrivateKey string `json:"private_key"`
PublicKey string `json:"public_key"`
Caller string `json:"caller"`
}
func createMember(sendURL string, userName string, serverLogLevel string) {
logLevelInsolar, err := insolar.ParseLevel(serverLogLevel)
check("Failed to parse logging level", err)
privKey, err := secrets.GeneratePrivateKeyEthereum()
check("Problems with generating of private key:", err)
privKeyStr, err := secrets.ExportPrivateKeyPEM(privKey)
check("Problems with serialization of private key:", err)
pubKeyStr, err := secrets.ExportPublicKeyPEM(secrets.ExtractPublicKey(privKey))
check("Problems with serialization of public key:", err)
cfg := mixedConfig{
PrivateKey: string(privKeyStr),
PublicKey: string(pubKeyStr),
}
info, err := sdk.Info(sendURL)
check("Problems with obtaining info", err)
ucfg, err := requester.CreateUserConfig(info.RootMember, cfg.PrivateKey, cfg.PublicKey)
check("Problems with creating user config:", err)
ctx := inslogger.ContextWithTrace(context.Background(), "insolarUtility")
params := requester.Params{
CallSite: "member.create",
CallParams: []interface{}{userName, cfg.PublicKey},
PublicKey: ucfg.PublicKey,
LogLevel: logLevelInsolar.String(),
}
r, err := requester.Send(ctx, sendURL, ucfg, ¶ms)
check("Problems with sending request", err)
var rStruct struct {
Result string `json:"result"`
}
err = json.Unmarshal(r, &rStruct)
check("Problems with understanding result", err)
cfg.Caller = rStruct.Result
result, err := json.MarshalIndent(cfg, "", " ")
check("Problems with marshaling config:", err)
mustWrite(os.Stdout, string(result))
}
func verboseInfo(msg string) {
if verbose {
fmt.Fprintln(os.Stderr, msg)
}
}
func mustWrite(out io.Writer, data string) {
_, err := out.Write([]byte(data))
check("Can't write data to output", err)
}
func generateKeysPair(targetValue string) {
switch targetValue {
case "node":
generateKeysPairFast()
return
case "user":
generateKeysPairEthereum()
return
default:
fmt.Fprintln(os.Stderr, "Unknown target. Possible values: node, user.")
os.Exit(1)
}
}
func generateKeysPairFast() {
ks := platformpolicy.NewKeyProcessor()
privKey, err := ks.GeneratePrivateKey()
check("Problems with generating of private key:", err)
privKeyStr, err := ks.ExportPrivateKeyPEM(privKey)
check("Problems with serialization of private key:", err)
pubKeyStr, err := ks.ExportPublicKeyPEM(ks.ExtractPublicKey(privKey))
check("Problems with serialization of public key:", err)
result, err := json.MarshalIndent(map[string]interface{}{
"private_key": string(privKeyStr),
"public_key": string(pubKeyStr),
}, "", " ")
check("Problems with marshaling keys:", err)
mustWrite(os.Stdout, string(result))
}
func generateKeysPairEthereum() {
privKey, err := secrets.GeneratePrivateKeyEthereum()
check("Problems with generating of private key:", err)
privKeyStr, err := secrets.ExportPrivateKeyPEM(privKey)
check("Problems with serialization of private key:", err)
pubKeyStr, err := secrets.ExportPublicKeyPEM(secrets.ExtractPublicKey(privKey))
check("Problems with serialization of public key:", err)
result, err := json.MarshalIndent(map[string]interface{}{
"private_key": string(privKeyStr),
"public_key": string(pubKeyStr),
}, "", " ")
check("Problems with marshaling keys:", err)
mustWrite(os.Stdout, string(result))
}
func sendRequest(sendURL string, adminURL, rootKeysFile string, paramsPath string, rootAsCaller bool, maAsCaller bool) {
requester.SetVerbose(verbose)
userCfg, err := requester.ReadUserConfigFromFile(rootKeysFile)
check("[ sendRequest ]", err)
pPath := paramsPath
if len(pPath) == 0 {
pPath = rootKeysFile
}
reqCfg, err := requester.ReadRequestParamsFromFile(pPath)
check("[ sendRequest ]", err)
if !insolar.IsObjectReferenceString(userCfg.Caller) && insolar.IsObjectReferenceString(reqCfg.Reference) {
userCfg.Caller = reqCfg.Reference
}
if userCfg.Caller == "" {
info, err := sdk.Info(adminURL)
check("[ sendRequest ]", err)
if rootAsCaller {
userCfg.Caller = info.RootMember
}
if maAsCaller {
userCfg.Caller = info.MigrationAdminMember
reqCfg.PublicKey = userCfg.PublicKey
}
}
verboseInfo(fmt.Sprintln("User Config: ", userCfg))
verboseInfo(fmt.Sprintln("Requester Config: ", reqCfg))
ctx := inslogger.ContextWithTrace(context.Background(), "insolarUtility")
response, err := requester.Send(ctx, sendURL, userCfg, reqCfg)
check("[ sendRequest ]", err)
mustWrite(os.Stdout, string(response))
}
func getInfo(url string) {
info, err := sdk.Info(url)
check("[ sendRequest ]", err)
fmt.Printf("TraceID : %s\n", info.TraceID)
fmt.Printf("RootMember : %s\n", info.RootMember)
fmt.Printf("NodeDomain : %s\n", info.NodeDomain)
fmt.Printf("RootDomain : %s\n", info.RootDomain)
}
func check(msg string, err error) {
if err != nil {
fmt.Fprintln(os.Stderr, msg, err)
os.Exit(1)
}
}
| [
"\"INSOLAR_API_URL\"",
"\"INSOLAR_ADMIN_URL\""
]
| []
| [
"INSOLAR_ADMIN_URL",
"INSOLAR_API_URL"
]
| [] | ["INSOLAR_ADMIN_URL", "INSOLAR_API_URL"] | go | 2 | 0 | |
contrib/devtools/github-merge.py | #!/usr/bin/env python3
# Copyright (c) 2016-2017 Bull Core Developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# This script will locally construct a merge commit for a pull request on a
# github repository, inspect it, sign it and optionally push it.
# The following temporary branches are created/overwritten and deleted:
# * pull/$PULL/base (the current master we're merging onto)
# * pull/$PULL/head (the current state of the remote pull request)
# * pull/$PULL/merge (github's merge)
# * pull/$PULL/local-merge (our merge)
# In case of a clean merge that is accepted by the user, the local branch with
# name $BRANCH is overwritten with the merged result, and optionally pushed.
from __future__ import division,print_function,unicode_literals
import os
from sys import stdin,stdout,stderr
import argparse
import hashlib
import subprocess
import sys
import json,codecs
try:
from urllib.request import Request,urlopen
except:
from urllib2 import Request,urlopen
# External tools (can be overridden using environment)
GIT = os.getenv('GIT','git')
BASH = os.getenv('BASH','bash')
# OS specific configuration for terminal attributes
ATTR_RESET = ''
ATTR_PR = ''
COMMIT_FORMAT = '%h %s (%an)%d'
if os.name == 'posix': # if posix, assume we can use basic terminal escapes
ATTR_RESET = '\033[0m'
ATTR_PR = '\033[1;36m'
COMMIT_FORMAT = '%C(bold blue)%h%Creset %s %C(cyan)(%an)%Creset%C(green)%d%Creset'
def git_config_get(option, default=None):
'''
Get named configuration option from git repository.
'''
try:
return subprocess.check_output([GIT,'config','--get',option]).rstrip().decode('utf-8')
except subprocess.CalledProcessError as e:
return default
def retrieve_pr_info(repo,pull):
'''
Retrieve pull request information from github.
Return None if no title can be found, or an error happens.
'''
try:
req = Request("https://api.github.com/repos/"+repo+"/pulls/"+pull)
result = urlopen(req)
reader = codecs.getreader('utf-8')
obj = json.load(reader(result))
return obj
except Exception as e:
print('Warning: unable to retrieve pull information from github: %s' % e)
return None
def ask_prompt(text):
print(text,end=" ",file=stderr)
stderr.flush()
reply = stdin.readline().rstrip()
print("",file=stderr)
return reply
def get_symlink_files():
files = sorted(subprocess.check_output([GIT, 'ls-tree', '--full-tree', '-r', 'HEAD']).splitlines())
ret = []
for f in files:
if (int(f.decode('utf-8').split(" ")[0], 8) & 0o170000) == 0o120000:
ret.append(f.decode('utf-8').split("\t")[1])
return ret
def tree_sha512sum(commit='HEAD'):
# request metadata for entire tree, recursively
files = []
blob_by_name = {}
for line in subprocess.check_output([GIT, 'ls-tree', '--full-tree', '-r', commit]).splitlines():
name_sep = line.index(b'\t')
metadata = line[:name_sep].split() # perms, 'blob', blobid
assert(metadata[1] == b'blob')
name = line[name_sep+1:]
files.append(name)
blob_by_name[name] = metadata[2]
files.sort()
# open connection to git-cat-file in batch mode to request data for all blobs
# this is much faster than launching it per file
p = subprocess.Popen([GIT, 'cat-file', '--batch'], stdout=subprocess.PIPE, stdin=subprocess.PIPE)
overall = hashlib.sha512()
for f in files:
blob = blob_by_name[f]
# request blob
p.stdin.write(blob + b'\n')
p.stdin.flush()
# read header: blob, "blob", size
reply = p.stdout.readline().split()
assert(reply[0] == blob and reply[1] == b'blob')
size = int(reply[2])
# hash the blob data
intern = hashlib.sha512()
ptr = 0
while ptr < size:
bs = min(65536, size - ptr)
piece = p.stdout.read(bs)
if len(piece) == bs:
intern.update(piece)
else:
raise IOError('Premature EOF reading git cat-file output')
ptr += bs
dig = intern.hexdigest()
assert(p.stdout.read(1) == b'\n') # ignore LF that follows blob data
# update overall hash with file hash
overall.update(dig.encode("utf-8"))
overall.update(" ".encode("utf-8"))
overall.update(f)
overall.update("\n".encode("utf-8"))
p.stdin.close()
if p.wait():
raise IOError('Non-zero return value executing git cat-file')
return overall.hexdigest()
def print_merge_details(pull, title, branch, base_branch, head_branch):
print('%s#%s%s %s %sinto %s%s' % (ATTR_RESET+ATTR_PR,pull,ATTR_RESET,title,ATTR_RESET+ATTR_PR,branch,ATTR_RESET))
subprocess.check_call([GIT,'log','--graph','--topo-order','--pretty=format:'+COMMIT_FORMAT,base_branch+'..'+head_branch])
def parse_arguments():
epilog = '''
In addition, you can set the following git configuration variables:
githubmerge.repository (mandatory),
user.signingkey (mandatory),
githubmerge.host (default: [email protected]),
githubmerge.branch (no default),
githubmerge.testcmd (default: none).
'''
parser = argparse.ArgumentParser(description='Utility to merge, sign and push github pull requests',
epilog=epilog)
parser.add_argument('pull', metavar='PULL', type=int, nargs=1,
help='Pull request ID to merge')
parser.add_argument('branch', metavar='BRANCH', type=str, nargs='?',
default=None, help='Branch to merge against (default: githubmerge.branch setting, or base branch for pull, or \'master\')')
return parser.parse_args()
def main():
# Extract settings from git repo
repo = git_config_get('githubmerge.repository')
host = git_config_get('githubmerge.host','[email protected]')
opt_branch = git_config_get('githubmerge.branch',None)
testcmd = git_config_get('githubmerge.testcmd')
signingkey = git_config_get('user.signingkey')
if repo is None:
print("ERROR: No repository configured. Use this command to set:", file=stderr)
print("git config githubmerge.repository <owner>/<repo>", file=stderr)
sys.exit(1)
if signingkey is None:
print("ERROR: No GPG signing key set. Set one using:",file=stderr)
print("git config --global user.signingkey <key>",file=stderr)
sys.exit(1)
host_repo = host+":"+repo # shortcut for push/pull target
# Extract settings from command line
args = parse_arguments()
pull = str(args.pull[0])
# Receive pull information from github
info = retrieve_pr_info(repo,pull)
if info is None:
sys.exit(1)
title = info['title'].strip()
body = info['body'].strip()
# precedence order for destination branch argument:
# - command line argument
# - githubmerge.branch setting
# - base branch for pull (as retrieved from github)
# - 'master'
branch = args.branch or opt_branch or info['base']['ref'] or 'master'
# Initialize source branches
head_branch = 'pull/'+pull+'/head'
base_branch = 'pull/'+pull+'/base'
merge_branch = 'pull/'+pull+'/merge'
local_merge_branch = 'pull/'+pull+'/local-merge'
devnull = open(os.devnull,'w')
try:
subprocess.check_call([GIT,'checkout','-q',branch])
except subprocess.CalledProcessError as e:
print("ERROR: Cannot check out branch %s." % (branch), file=stderr)
sys.exit(3)
try:
subprocess.check_call([GIT,'fetch','-q',host_repo,'+refs/pull/'+pull+'/*:refs/heads/pull/'+pull+'/*',
'+refs/heads/'+branch+':refs/heads/'+base_branch])
except subprocess.CalledProcessError as e:
print("ERROR: Cannot find pull request #%s or branch %s on %s." % (pull,branch,host_repo), file=stderr)
sys.exit(3)
try:
subprocess.check_call([GIT,'log','-q','-1','refs/heads/'+head_branch], stdout=devnull, stderr=stdout)
except subprocess.CalledProcessError as e:
print("ERROR: Cannot find head of pull request #%s on %s." % (pull,host_repo), file=stderr)
sys.exit(3)
try:
subprocess.check_call([GIT,'log','-q','-1','refs/heads/'+merge_branch], stdout=devnull, stderr=stdout)
except subprocess.CalledProcessError as e:
print("ERROR: Cannot find merge of pull request #%s on %s." % (pull,host_repo), file=stderr)
sys.exit(3)
subprocess.check_call([GIT,'checkout','-q',base_branch])
subprocess.call([GIT,'branch','-q','-D',local_merge_branch], stderr=devnull)
subprocess.check_call([GIT,'checkout','-q','-b',local_merge_branch])
try:
# Go up to the repository's root.
toplevel = subprocess.check_output([GIT,'rev-parse','--show-toplevel']).strip()
os.chdir(toplevel)
# Create unsigned merge commit.
if title:
firstline = 'Merge #%s: %s' % (pull,title)
else:
firstline = 'Merge #%s' % (pull,)
message = firstline + '\n\n'
message += subprocess.check_output([GIT,'log','--no-merges','--topo-order','--pretty=format:%h %s (%an)',base_branch+'..'+head_branch]).decode('utf-8')
message += '\n\nPull request description:\n\n ' + body.replace('\n', '\n ') + '\n'
try:
subprocess.check_call([GIT,'merge','-q','--commit','--no-edit','--no-ff','-m',message.encode('utf-8'),head_branch])
except subprocess.CalledProcessError as e:
print("ERROR: Cannot be merged cleanly.",file=stderr)
subprocess.check_call([GIT,'merge','--abort'])
sys.exit(4)
logmsg = subprocess.check_output([GIT,'log','--pretty=format:%s','-n','1']).decode('utf-8')
if logmsg.rstrip() != firstline.rstrip():
print("ERROR: Creating merge failed (already merged?).",file=stderr)
sys.exit(4)
symlink_files = get_symlink_files()
for f in symlink_files:
print("ERROR: File %s was a symlink" % f)
if len(symlink_files) > 0:
sys.exit(4)
# Put tree SHA512 into the message
try:
first_sha512 = tree_sha512sum()
message += '\n\nTree-SHA512: ' + first_sha512
except subprocess.CalledProcessError as e:
print("ERROR: Unable to compute tree hash")
sys.exit(4)
try:
subprocess.check_call([GIT,'commit','--amend','-m',message.encode('utf-8')])
except subprocess.CalledProcessError as e:
print("ERROR: Cannot update message.", file=stderr)
sys.exit(4)
print_merge_details(pull, title, branch, base_branch, head_branch)
print()
# Run test command if configured.
if testcmd:
if subprocess.call(testcmd,shell=True):
print("ERROR: Running %s failed." % testcmd,file=stderr)
sys.exit(5)
# Show the created merge.
diff = subprocess.check_output([GIT,'diff',merge_branch+'..'+local_merge_branch])
subprocess.check_call([GIT,'diff',base_branch+'..'+local_merge_branch])
if diff:
print("WARNING: merge differs from github!",file=stderr)
reply = ask_prompt("Type 'ignore' to continue.")
if reply.lower() == 'ignore':
print("Difference with github ignored.",file=stderr)
else:
sys.exit(6)
else:
# Verify the result manually.
print("Dropping you on a shell so you can try building/testing the merged source.",file=stderr)
print("Run 'git diff HEAD~' to show the changes being merged.",file=stderr)
print("Type 'exit' when done.",file=stderr)
if os.path.isfile('/etc/debian_version'): # Show pull number on Debian default prompt
os.putenv('debian_chroot',pull)
subprocess.call([BASH,'-i'])
second_sha512 = tree_sha512sum()
if first_sha512 != second_sha512:
print("ERROR: Tree hash changed unexpectedly",file=stderr)
sys.exit(8)
# Sign the merge commit.
print_merge_details(pull, title, branch, base_branch, head_branch)
while True:
reply = ask_prompt("Type 's' to sign off on the above merge, or 'x' to reject and exit.").lower()
if reply == 's':
try:
subprocess.check_call([GIT,'commit','-q','--gpg-sign','--amend','--no-edit'])
break
except subprocess.CalledProcessError as e:
print("Error while signing, asking again.",file=stderr)
elif reply == 'x':
print("Not signing off on merge, exiting.",file=stderr)
sys.exit(1)
# Put the result in branch.
subprocess.check_call([GIT,'checkout','-q',branch])
subprocess.check_call([GIT,'reset','-q','--hard',local_merge_branch])
finally:
# Clean up temporary branches.
subprocess.call([GIT,'checkout','-q',branch])
subprocess.call([GIT,'branch','-q','-D',head_branch],stderr=devnull)
subprocess.call([GIT,'branch','-q','-D',base_branch],stderr=devnull)
subprocess.call([GIT,'branch','-q','-D',merge_branch],stderr=devnull)
subprocess.call([GIT,'branch','-q','-D',local_merge_branch],stderr=devnull)
# Push the result.
while True:
reply = ask_prompt("Type 'push' to push the result to %s, branch %s, or 'x' to exit without pushing." % (host_repo,branch)).lower()
if reply == 'push':
subprocess.check_call([GIT,'push',host_repo,'refs/heads/'+branch])
break
elif reply == 'x':
sys.exit(1)
if __name__ == '__main__':
main()
| []
| []
| [
"GIT",
"BASH"
]
| [] | ["GIT", "BASH"] | python | 2 | 0 | |
pkg/operation/create.go | /*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package operation
import (
"encoding/json"
"github.com/pkg/errors"
"github.com/trustbloc/sidetree-core-go/pkg/api/batch"
"github.com/trustbloc/sidetree-core-go/pkg/api/protocol"
"github.com/trustbloc/sidetree-core-go/pkg/docutil"
"github.com/trustbloc/sidetree-core-go/pkg/restapi/model"
)
// ParseCreateOperation will parse create operation
func ParseCreateOperation(request []byte, protocol protocol.Protocol) (*batch.Operation, error) {
schema, err := parseCreateRequest(request)
if err != nil {
return nil, err
}
code := protocol.HashAlgorithmInMultiHashCode
suffixData, err := ParseSuffixData(schema.SuffixData, code)
if err != nil {
return nil, err
}
delta, err := ParseDelta(schema.Delta, code)
if err != nil {
return nil, err
}
uniqueSuffix, err := docutil.CalculateUniqueSuffix(schema.SuffixData, code)
if err != nil {
return nil, err
}
return &batch.Operation{
OperationBuffer: request,
Type: batch.OperationTypeCreate,
UniqueSuffix: uniqueSuffix,
Delta: delta,
EncodedDelta: schema.Delta,
SuffixData: suffixData,
EncodedSuffixData: schema.SuffixData,
}, nil
}
func parseCreateRequest(payload []byte) (*model.CreateRequest, error) {
schema := &model.CreateRequest{}
err := json.Unmarshal(payload, schema)
if err != nil {
return nil, err
}
if err := validateCreateRequest(schema); err != nil {
return nil, err
}
return schema, nil
}
// ParseDelta parses encoded delta string into delta model
func ParseDelta(encoded string, code uint) (*model.DeltaModel, error) {
bytes, err := docutil.DecodeString(encoded)
if err != nil {
return nil, err
}
schema := &model.DeltaModel{}
err = json.Unmarshal(bytes, schema)
if err != nil {
return nil, err
}
if err := validateDelta(schema, code); err != nil {
return nil, err
}
return schema, nil
}
// ParseSuffixData parses encoded suffix data into suffix data model
func ParseSuffixData(encoded string, code uint) (*model.SuffixDataModel, error) {
bytes, err := docutil.DecodeString(encoded)
if err != nil {
return nil, err
}
schema := &model.SuffixDataModel{}
err = json.Unmarshal(bytes, schema)
if err != nil {
return nil, err
}
if err := validateSuffixData(schema, code); err != nil {
return nil, err
}
return schema, nil
}
func validateDelta(delta *model.DeltaModel, code uint) error {
if len(delta.Patches) == 0 {
return errors.New("missing patches")
}
for _, p := range delta.Patches {
if err := p.Validate(); err != nil {
return err
}
}
if !docutil.IsComputedUsingHashAlgorithm(delta.UpdateCommitment, uint64(code)) {
return errors.New("next update commitment hash is not computed with the latest supported hash algorithm")
}
return nil
}
func validateSuffixData(suffixData *model.SuffixDataModel, code uint) error {
if !docutil.IsComputedUsingHashAlgorithm(suffixData.RecoveryCommitment, uint64(code)) {
return errors.New("next recovery commitment hash is not computed with the latest supported hash algorithm")
}
if !docutil.IsComputedUsingHashAlgorithm(suffixData.DeltaHash, uint64(code)) {
return errors.New("patch data hash is not computed with the latest supported hash algorithm")
}
return nil
}
func validateCreateRequest(create *model.CreateRequest) error {
if create.Delta == "" {
return errors.New("missing delta")
}
if create.SuffixData == "" {
return errors.New("missing suffix data")
}
return nil
}
| []
| []
| []
| [] | [] | go | null | null | null |
pkg/cmd/variables/variables_test.go | package variables_test
import (
"context"
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"
"github.com/jenkins-x-plugins/jx-gitops/pkg/cmd/variables"
"github.com/jenkins-x-plugins/jx-gitops/pkg/fakerunners"
scmfake "github.com/jenkins-x/go-scm/scm/driver/fake"
jxcore "github.com/jenkins-x/jx-api/v4/pkg/apis/core/v4beta1"
jxfake "github.com/jenkins-x/jx-api/v4/pkg/client/clientset/versioned/fake"
"github.com/jenkins-x/jx-helpers/v3/pkg/files"
"github.com/jenkins-x/jx-helpers/v3/pkg/kube/jxenv"
"github.com/jenkins-x/jx-helpers/v3/pkg/testhelpers"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes/fake"
"sigs.k8s.io/yaml"
)
func TestCmdVariables(t *testing.T) {
// lets skip this test if inside a goreleaser when we've got the env vars defined
chartEnv := os.Getenv("JX_CHART_REPOSITORY")
if chartEnv != "" {
t.Skipf("skipping test as $JX_CHART_REPOSITORY = %s\n", chartEnv)
return
}
tmpDir, err := ioutil.TempDir("", "")
require.NoError(t, err, "failed to create temp dir")
testDir := filepath.Join("test_data", "tests")
fs, err := ioutil.ReadDir(testDir)
require.NoError(t, err, "failed to read test dir %s", testDir)
for _, f := range fs {
if f == nil || !f.IsDir() {
continue
}
name := f.Name()
if strings.HasPrefix(name, ".") {
continue
}
srcDir := filepath.Join(testDir, name)
runDir := filepath.Join(tmpDir, name)
err := files.CopyDirOverwrite(srcDir, runDir)
require.NoError(t, err, "failed to copy from %s to %s", srcDir, runDir)
t.Logf("running test %s in dir %s\n", name, runDir)
version := "1.2.3"
versionFile := filepath.Join(runDir, "VERSION")
err = ioutil.WriteFile(versionFile, []byte(version), files.DefaultFileWritePermissions)
require.NoError(t, err, "failed to write file %s", versionFile)
ns := "jx"
devEnv := jxenv.CreateDefaultDevEnvironment(ns)
devEnv.Namespace = ns
devEnv.Spec.Source.URL = "https://github.com/jx3-gitops-repositories/jx3-kubernetes.git"
if name == "nokube" {
devEnv.Spec.Source.URL = "https://github.com/jx3-gitops-repositories/jx3-github.git"
} else {
requirements := jxcore.NewRequirementsConfig()
requirements.Spec.Cluster.ChartRepository = "http://bucketrepo/bucketrepo/charts/"
data, err := yaml.Marshal(requirements)
require.NoError(t, err, "failed to marshal requirements")
devEnv.Spec.TeamSettings.BootRequirements = string(data)
}
runner := fakerunners.NewFakeRunnerWithGitClone()
jxClient := jxfake.NewSimpleClientset(devEnv)
scmFake, _ := scmfake.NewDefault()
_, o := variables.NewCmdVariables()
o.Dir = runDir
o.CommandRunner = runner.Run
o.JXClient = jxClient
o.Namespace = ns
o.BuildNumber = "5"
o.KubeClient = fake.NewSimpleClientset(
&corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: o.ConfigMapName,
Namespace: ns,
},
Data: map[string]string{
"docker.registry": "my-registry.com",
"kaniko.flags": "cheese",
"PUSH_CONTAINER_REGISTRY": "localhost:5000",
},
},
)
o.Options.Owner = "MyOwner"
o.Options.Repository = "myrepo"
o.Options.Branch = "PR-23"
o.Options.SourceURL = "https://github.com/" + o.Options.Owner + "/" + o.Options.Repository
o.Options.ScmClient = scmFake
err = o.Run()
require.NoError(t, err, "failed to run the command")
f := filepath.Join(runDir, o.File)
require.FileExists(t, f, "should have generated file")
t.Logf("generated file %s\n", f)
testhelpers.AssertTextFilesEqual(t, filepath.Join(runDir, "expected.sh"), f, "generated file")
}
}
func TestFindBuildNumber(t *testing.T) {
kubeClient := fake.NewSimpleClientset()
jxClient := jxfake.NewSimpleClientset()
ns := "jx"
buildID := "123456"
owner := "myowner"
repository := "myrepo"
branch := "PR-23"
createOptions := func() *variables.Options {
_, o := variables.NewCmdVariables()
o.JXClient = jxClient
o.KubeClient = kubeClient
o.Namespace = ns
o.BuildID = buildID
o.Options.Owner = owner
o.Options.Repository = repository
o.Options.Branch = branch
o.Options.SourceURL = "https://github.com/" + owner + "/" + repository
return o
}
o := createOptions()
buildNumber, err := o.FindBuildNumber(buildID)
require.NoError(t, err, "failed to find build number")
assert.Equal(t, "1", buildNumber, "should have created build number")
t.Logf("generated build number %s", buildNumber)
resources, err := jxClient.JenkinsV1().PipelineActivities(ns).List(context.TODO(), metav1.ListOptions{})
require.NoError(t, err, "failed to list PipelineActivities")
require.Len(t, resources.Items, 1, "should have found 1 PipelineActivity")
pa := resources.Items[0]
assert.Equal(t, "1", pa.Spec.Build, "PipelineActivity should have Spec.Build")
assert.Equal(t, o.Options.Owner, pa.Spec.GitOwner, "PipelineActivity should have Spec.GitOwner")
assert.Equal(t, o.Options.Repository, pa.Spec.GitRepository, "PipelineActivity should have Spec.GitRepository")
assert.Equal(t, o.Options.Branch, pa.Spec.GitBranch, "PipelineActivity should have Spec.GitRepository")
assert.Equal(t, o.BuildID, pa.Labels["buildID"], "PipelineActivity should have Labels['buildID'] but has labels %#v", pa.Labels)
o = createOptions()
buildNumber, err = o.FindBuildNumber(buildID)
require.NoError(t, err, "failed to find build number")
assert.Equal(t, "1", buildNumber, "should have created build number")
resources, err = jxClient.JenkinsV1().PipelineActivities(ns).List(context.TODO(), metav1.ListOptions{})
require.NoError(t, err, "failed to list PipelineActivities")
require.Len(t, resources.Items, 1, "should have found 1 PipelineActivity")
}
func TestDockerfilePath(t *testing.T) {
testCases := []struct {
dir string
expected string
}{
{
dir: "just_dockerfile",
expected: "Dockerfile",
},
{
dir: "has_preview_dockerfile",
expected: "Dockerfile-preview",
},
}
for _, tc := range testCases {
dir := tc.dir
_, o := variables.NewCmdVariables()
o.Branch = "PR-123"
o.Dir = filepath.Join("test_data", dir)
actual, err := o.FindDockerfilePath()
require.NoError(t, err, "failed to find Dockerfile path for dir %s", dir)
assert.Equal(t, tc.expected, actual, "found Dockerfile path for dir %s", dir)
t.Logf("for dir %s we found dockerfile path %s\n", dir, actual)
}
}
| [
"\"JX_CHART_REPOSITORY\""
]
| []
| [
"JX_CHART_REPOSITORY"
]
| [] | ["JX_CHART_REPOSITORY"] | go | 1 | 0 | |
workout/asgi.py | """
ASGI config for workout project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "workout.settings")
application = get_asgi_application()
| []
| []
| []
| [] | [] | python | 0 | 0 | |
pod042_bot/config.py | """
Создает конфигурацию из переменных окружения.
"""
import os
import sys
try:
DATABASE_URL = os.environ['DATABASE_URL']
"""Адрес базы данных."""
BOT_TOKEN = os.environ['BOT_TOKEN']
"""Токен бота, получать у @BotFather."""
PRODUCTION = bool(os.getenv('PRODUCTION', False))
"""True, если бот размещен на Heroku."""
if PRODUCTION:
HEROKU_APP_NAME = os.environ['HEROKU_APP_NAME']
"""Имя приложения Heroku."""
PORT = int(os.environ['PORT'])
"""Какой порт слушать боту (выставляет сам Heroku)."""
VK_LOGIN = os.environ['VK_LOGIN']
"""Логин ВКонтакте (лучше телефон)."""
VK_PASSWORD = os.environ['VK_PASSWORD']
"""Пароль ВКонтакте."""
except KeyError as e:
sys.stderr.write('Приложение не сконфигурировано, проверьте необходимые переменные окружения в config.py!\n'
f'Не хватает переменной "{e.args[0]}"\n')
sys.exit(-1)
THREADS_NUM = int(os.getenv('THREADS_NUM', 8))
"""Количество потоков."""
LOG_FORMAT = os.getenv('LOG_FORMAT', '%(asctime)s [%(levelname)s] P%(process)d <%(filename)s:%(lineno)d'
', %(funcName)s()> %(name)s: %(message)s')
"""
Формат лога, см.
https://docs.python.org/3/library/logging.html#logrecord-attributes
"""
LOG_LEVEL = os.getenv('LOG_LEVEL', 'DEBUG')
"""Подробность лога."""
ORM_ECHO = bool(os.getenv('ORM_ECHO', 0))
"""Вывод всех SQL-запросов в консоль. Полезно только при отладке."""
PROXY_HOST = os.getenv('PROXY_HOST')
"""Имя хоста SOCKS5 прокси-сервера."""
PROXY_PORT = os.getenv('PROXY_PORT')
"""Порт прокси-сервера."""
PROXY_USER = os.getenv('PROXY_USER')
"""Пользователь прокси-сервера (опционально)."""
PROXY_PASSWORD = os.getenv('PROXY_PASSWORD')
"""Пароль прокси-сервера (опционально)."""
| []
| []
| [
"PORT",
"LOG_FORMAT",
"PROXY_PASSWORD",
"PRODUCTION",
"PROXY_HOST",
"ORM_ECHO",
"LOG_LEVEL",
"DATABASE_URL",
"VK_PASSWORD",
"HEROKU_APP_NAME",
"PROXY_USER",
"BOT_TOKEN",
"PROXY_PORT",
"VK_LOGIN",
"THREADS_NUM"
]
| [] | ["PORT", "LOG_FORMAT", "PROXY_PASSWORD", "PRODUCTION", "PROXY_HOST", "ORM_ECHO", "LOG_LEVEL", "DATABASE_URL", "VK_PASSWORD", "HEROKU_APP_NAME", "PROXY_USER", "BOT_TOKEN", "PROXY_PORT", "VK_LOGIN", "THREADS_NUM"] | python | 15 | 0 | |
manage.py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Tester.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| []
| []
| []
| [] | [] | python | 0 | 0 | |
manage.py | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Polls.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
| []
| []
| []
| [] | [] | python | 0 | 0 | |
bluelog/settings.py | import os
import sys
basedir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
# SQLite URI compatible
WIN = sys.platform.startswith('win')
if WIN:
prefix = 'sqlite:///'
else:
prefix = 'sqlite:////'
class BaseConfig(object):
SECRET_KEY = os.getenv('SECRET_KEY', 'dev key')
DEBUG_TB_INTERCEPT_REDIRECTS = False
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_RECORD_QUERIES = True
CKEDITOR_ENABLE_CSRF = True
CKEDITOR_FILE_UPLOADER = 'admin.upload_image'
MAIL_PORT = 465
MAIL_USE_SSL = True
# MAIL_SERVER = os.getenv('MAIL_SERVER')
# MAIL_USERNAME = os.getenv('MAIL_USERNAME')
# MAIL_PASSWORD = os.getenv('MAIL_PASSWORD')
MAIL_SERVER = 'smtp.163.com'
MAIL_USERNAME = '[email protected]'
MAIL_PASSWORD = 'ltf1997'
MAIL_DEFAULT_SENDER = ('Bluelog Admin ltf', MAIL_USERNAME)
BLUELOG_EMAIL = os.getenv('BLUELOG_EMAIL')
BLUELOG_POST_PER_PAGE = 10
BLUELOG_MANAGE_POST_PER_PAGE = 15
BLUELOG_COMMENT_PER_PAGE = 15
# ('theme name', 'display name')
BLUELOG_THEMES = {'perfect_blue': '清新蓝', 'black_swan': '黑天鹅'}
BLUELOG_SLOW_QUERY_THRESHOLD = 1
BLUELOG_UPLOAD_PATH = os.path.join(basedir, 'uploads')
BLUELOG_ALLOWED_IMAGE_EXTENSIONS = ['png', 'jpg', 'jpeg', 'gif']
class DevelopmentConfig(BaseConfig):
SQLALCHEMY_DATABASE_URI = prefix + os.path.join(basedir, 'data-dev.db')
class TestingConfig(BaseConfig):
TESTING = True
WTF_CSRF_ENABLED = False
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:' # in-memory database
class ProductionConfig(BaseConfig):
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL', prefix + os.path.join(basedir, 'data.db'))
config = {
'development': DevelopmentConfig,
'testing': TestingConfig,
'production': ProductionConfig
}
| []
| []
| [
"MAIL_SERVER",
"MAIL_PASSWORD",
"DATABASE_URL",
"BLUELOG_EMAIL",
"SECRET_KEY",
"MAIL_USERNAME"
]
| [] | ["MAIL_SERVER", "MAIL_PASSWORD", "DATABASE_URL", "BLUELOG_EMAIL", "SECRET_KEY", "MAIL_USERNAME"] | python | 6 | 0 | |
fastpass.py | # import time
import os
from datetime import datetime, timedelta, timezone, date
from dateutil import parser
import html
import json
import subprocess
from urllib.parse import urlparse
import requests
import redis
from ftfy import fix_text
from flask import Flask, jsonify, request, redirect
from jinja2 import Environment, FileSystemLoader
from flask_cors import CORS
from bs4 import BeautifulSoup
from youtube import YoutubeBroadcasts
from slack import SlackMessenger
from icalevents.icalevents import events
def _setup_appflags():
url = 'https://wdwnt.com/wp-json/wp/v2/appflag'
try:
response = requests.get(url, headers=WP_HEADER)
response_data = response.json()
result = dict([(x['id'], x['slug']) for x in response_data])
return result
except Exception:
return {}
CACHE_EXPIRE_SECONDS = os.getenv('FASTPASS_CACHE_EXPIRE_SECONDS', 180)
CACHE_SYSTEM = os.getenv('FASTPASS_CACHE_SYSTEM', 'memory')
TIMEOUT_SECONDS = os.getenv('FASTPASS_TIMEOUT_SECONDS', 5)
SERVER_PORT = os.getenv('FASTPASS_HOST_PORT', 5000)
REDIS_HOST = os.getenv('FASTPASS_REDIS_HOST', '127.0.0.1')
REDIS_PORT = os.getenv('FASTPASS_REDIS_PORT', 36379)
REDIS_PASSWORD = os.getenv('FASTPASS_REDIS_PASSWORD', '')
REDIS_USE_SSL = os.getenv('FASTPASS_REDIS_USE_SSL', False)
YOUTUBE_VIDS_PER_PAGE = os.getenv('FASTPASS_YOUTUBE_VIDS_PER_PAGE', 30)
YOUTUBE_API_KEY = os.getenv('FASTPASS_YOUTUBE_API_KEY', None)
YOUTUBE_PLAYLIST_ID = os.getenv('FASTPASS_YOUTUBE_PLAYLIST_ID', None)
YOUTUBE_EXPIRE_SECONDS = os.getenv('FASTPASS_YOUTUBE_EXPIRE_SECONDS', CACHE_EXPIRE_SECONDS)
YOUTUBE_THUMBNAIL_QUALITY = os.getenv('FASTPASS_YOUTUBE_THUMBNAIL_QUALITY', 'default')
UNLISTED_VIDEO_EXPIRE_SECONDS = os.getenv('FASTPASS_UNLISTED_VIDEO_EXPIRE_SECONDS', 300)
BROADCAST_CLIENT_ID = os.getenv('FASTPASS_BROADCAST_CLIENT_ID', '')
BROADCAST_CLIENT_SECRET = os.getenv('FASTPASS_BROADCAST_CLIENT_SECRET', '')
BROADCAST_REFRESH_TOKEN = os.getenv('FASTPASS_BROADCAST_REFRESH_TOKEN', '')
BROADCAST_UPNT_CLIENT_ID = os.getenv('FASTPASS_BROADCAST_UPNT_CLIENT_ID', '')
BROADCAST_UPNT_CLIENT_SECRET = os.getenv('FASTPASS_BROADCAST_UPNT_CLIENT_SECRET', '')
BROADCAST_UPNT_REFRESH_TOKEN = os.getenv('FASTPASS_BROADCAST_UPNT_REFRESH_TOKEN', '')
BROADCAST_ENTERTAINMENT_CLIENT_ID = os.getenv('FASTPASS_BROADCAST_ENTERTAINMENT_CLIENT_ID', '')
BROADCAST_ENTERTAINMENT_CLIENT_SECRET = os.getenv('FASTPASS_BROADCAST_ENTERTAINMENT_CLIENT_SECRET', '')
BROADCAST_ENTERTAINMENT_REFRESH_TOKEN = os.getenv('FASTPASS_BROADCAST_ENTERTAINMENT_REFRESH_TOKEN', '')
BROADCAST_EXPIRE_SECONDS = os.getenv('FASTPASS_BROADCAST_EXPIRE_SECONDS', 600)
INSTAGRAM_EXPIRE_SECONDS = os.getenv('FASTPASS_INSTAGRAM_EXPIRE_SECONDS', 450)
LIVE365_EXPIRE_SECONDS = os.getenv('FASTPASS_LIVE365_EXPIRE_SECONDS', 30)
NTUNES_AUDIO_URL = os.getenv('FASTPASS_NTUNES_AUDIO_URL', '')
PUBLIC_CALENDAR_URL = os.getenv('FASTPASS_PUBLIC_CALENDAR_URL', 'https://calendar.google.com/calendar/ical'
'/wdwnt.com_4ukclkbeeicaoj26l0n2ris2l4%40'
'group.calendar.google.com'
'/private-0902710935cbdd0adadb829bbc515b82/basic.ics')
GIT_COMMIT = os.getenv('HEROKU_SLUG_COMMIT', None)
GIT_RELEASE_AT = os.getenv('HEROKU_RELEASE_CREATED_AT', None)
GIT_DESCRIPTION = os.getenv('HEROKU_SLUG_DESCRIPTION', None)
WP_HEADER = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) '
'AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/50.0.2661.102 Safari/537.36'}
WP_APPFLAGS = _setup_appflags()
POSTS_PER_PAGE = os.getenv('FASTPASS_POSTS_PER_PAGE', 30)
app = Flask(__name__, static_folder='static/')
CORS(app)
err_env = Environment(loader=FileSystemLoader(searchpath='./error_responses'))
err_env.filters['jsonify'] = json.dumps
mem_cache = {}
redis_db = redis.StrictRedis(host=REDIS_HOST,
port=REDIS_PORT,
password=REDIS_PASSWORD,
ssl=REDIS_USE_SSL)
def format_airtime(in_data):
result = {'current': {}, 'currentShow': [], 'next': {}}
for field in ('ends', 'type'):
result['current'][field] = in_data.get('current', {}).get(field)
for song in ('current', 'next'):
md_block = {}
for field in ('track_title', 'artist_name', 'length'):
raw_text = in_data.get(song, {}).get('metadata', {}).get(field)
md_block[field] = fix_text(raw_text) if raw_text else raw_text
result[song]['metadata'] = md_block
if len(in_data.get('currentShow', [])):
show_data = in_data['currentShow'][0]
show_block = {}
for field in ('name', 'image_path'):
raw_text = show_data.get(field)
show_block[field] = fix_text(raw_text) if raw_text else raw_text
result['currentShow'].append(show_block)
return result
def format_live365(in_data):
result = {'current-track': {}, 'last-played': []}
track_fields = ('start', 'end', 'artist', 'title', 'art', 'duration', 'sync_offset')
for field in track_fields:
result['current-track'][field] = in_data.get('current-track', {}).get(field)
for song in in_data.get('last-played', []):
song_data = {}
for field in track_fields:
song_data[field] = song.get(field)
result['last-played'].append(song_data)
result['stream-urls'] = in_data.get('stream-urls', [])
result['live_dj_on'] = in_data.get('live_dj_on', False)
result['listeners'] = in_data.get('listeners', 0)
return result
def format_wp(in_data, with_content=False, with_player=True):
result = []
for post in in_data:
raw_url = urlparse(post.get('guid', {}).get('rendered', ''))
obj = dict(author={})
obj['id'] = post.get('id')
obj['short_URL'] = 'https://{}/?p={}'.format(raw_url.netloc, obj['id'])
obj['title'] = html.unescape(post.get('title', {}).get('rendered', ''))
obj['date'] = post.get('date_gmt')
authors = post.get('_embedded', {}).get('author', [])
obj['author']['name'] = ','.join([x.get('name', '') for x in authors])
media = post.get('_embedded', {}).get('wp:featuredmedia', [])
if media:
obj['featured_image'] = media[0].get('source_url')
else:
obj['featured_image'] = ''
term = post.get('_embedded', {}).get('wp:term', [])
if term:
try:
term_val = term[0][0].get('name', '')
obj['category'] = html.unescape(term_val)
except KeyError:
obj['category'] = ''
else:
obj['category'] = ''
if with_content:
raw_content = post.get('content', {}).get('rendered', '')
if with_player:
obj['content'] = raw_content
else:
content, media_url = remove_player(raw_content)
obj['content'] = content
obj['media_url'] = media_url
result.append(obj)
return result
def remove_player(wp_content):
soup = BeautifulSoup(wp_content, "html.parser")
download_url = soup.find('a', class_='powerpress_link_d').get('href', '')
for tag in soup.select('div.powerpress_player'):
tag.decompose()
for tag in soup.select('p.powerpress_links'):
tag.decompose()
return str(soup), download_url
def format_wp_single_post(in_data, with_player=True, with_icon=False):
obj = dict(author=[])
obj['id'] = in_data.get('id')
obj['title'] = html.unescape(in_data.get('title', {}).get('rendered', ''))
term = in_data.get('_embedded', {}).get('wp:term', [])
if term:
try:
term_val = term[0][0].get('name', '')
obj['category'] = html.unescape(term_val)
except (KeyError, IndexError):
obj['category'] = ''
else:
obj['category'] = ''
obj['date'] = in_data.get('date_gmt')
raw_text = in_data.get('content', {}).get('rendered', '')
if with_player:
obj['text'] = raw_text
else:
content, media_url = remove_player(raw_text)
obj['text'] = content
obj['media_url'] = media_url
media = in_data.get('_embedded', {}).get('wp:featuredmedia', [])
if media:
obj['featured_image'] = media[0].get('source_url')
else:
obj['featured_image'] = ''
authors = in_data.get('_embedded', {}).get('author', [])
author_list = []
for x in authors:
author_data = {'avatar_urls': {}}
for f in ('id', 'name', 'description'):
author_data[f] = x.get(f)
author_data['avatar_urls']['96'] = x.get('avatar_urls', {}).get('96')
author_list.append(author_data)
obj['author'] = author_list
if with_icon:
app_menu_icon = in_data.get('acf', {}).get('app_menu_icon', '')
obj['acf'] = {'app_menu_icon': app_menu_icon}
jrps = in_data.get('jetpack-related-posts', [])
jrp_list = []
for x in jrps:
jrp_data = {}
for f in ('id', 'title', 'img'):
jrp_data[f] = x.get(f)
jrp_list.append(jrp_data)
obj['jetpack-related-posts'] = jrp_list
return obj
def format_notifications(in_data):
result = []
for n in in_data:
note_obj = {}
for x in ('id', 'type', 'date'):
f = 'date_gmt' if x == 'date' else x
note_obj[x] = n.get(f)
for x in ('title', 'text'):
f = 'excerpt' if x == 'text' else x
note_obj[x] = html.unescape(n.get(f, {}).get('rendered', '')),
for x in ('app_notification_category', 'app_notification_type'):
note_obj[x] = n.get(x, [])
result.append(note_obj)
return result
def format_youtube(in_data):
tnq = YOUTUBE_THUMBNAIL_QUALITY
result = {'items': [], 'nextPageToken': in_data.get('nextPageToken'),
'prevPageToken': in_data.get('prevPageToken')}
for x in in_data.get('items', []):
obj = dict(snippet=dict(resourceId={}, thumbnails={'default': {}}))
obj['snippet']['resourceId']['videoId'] = \
x.get('snippet', {}).get('resourceId', {}).get('videoId')
obj['snippet']['thumbnails']['default']['url'] = \
x.get('snippet', {}).get('thumbnails', {}).get(tnq, {}).get('url')
obj['snippet']['title'] = x.get('snippet', {}).get('title')
result['items'].append(obj)
return result
def _store_in_cache(url, data, expire_time=None,
expire_seconds=CACHE_EXPIRE_SECONDS):
if not expire_time:
expiry = datetime.utcnow() + timedelta(seconds=expire_seconds)
expiry = expiry.replace(tzinfo=timezone.utc)
else:
expiry = expire_time
if CACHE_SYSTEM == 'redis':
redis_db.set(url, data, expire_seconds)
else:
val = {
'data': data,
'expire_at': expiry.timestamp(),
}
mem_cache[url] = val
def _get_from_cache(url, include_old=False):
now = datetime.utcnow()
now = now.replace(tzinfo=timezone.utc)
if CACHE_SYSTEM == 'redis':
redis_db.get(url)
else:
if url not in mem_cache:
return None
if mem_cache[url]['expire_at'] >= now.timestamp() or include_old:
return mem_cache[url]['data']
else:
del mem_cache[url]
return None
def _get_error_json(path, cache_time=CACHE_EXPIRE_SECONDS):
file_path = f'{path[1:]}.json'
end_dt = datetime.utcnow() + timedelta(seconds=cache_time)
end_dt = end_dt.replace(tzinfo=timezone.utc)
start_dt = datetime.utcnow()
start_dt = start_dt.replace(tzinfo=timezone.utc)
page = {
'start': start_dt,
'end': end_dt,
'duration': cache_time
}
try:
template = err_env.get_template(file_path)
data = json.loads(template.render(page=page))
except Exception as e:
data = {}
return data
def _clear_cache(status):
if status == 'NOT_FULL_OF_SHIT':
if CACHE_SYSTEM == 'redis':
redis_db.flushall()
return True
else:
mem_cache.clear()
return True
return False
def _clear_posts(status):
prefix = 'https://wdwnt.com/wp-json/wp/v2/posts'
if status == 'NOT_FULL_OF_SHIT':
if CACHE_SYSTEM == 'redis':
for key in redis_db.scan_iter(prefix + '*'):
redis_db.delete(key)
return True
else:
to_del = set()
for k in mem_cache.keys():
if k.startswith(prefix):
to_del.add(k)
for l in to_del:
mem_cache.pop(l)
return True
return False
def _unlisted_videos(site_code: str, client_id: str, client_secret: str, refresh_token: str):
in_delta_minutes = int(request.args.get('delta_minutes', UNLISTED_VIDEO_EXPIRE_SECONDS / 60))
if not (client_id and client_secret and refresh_token):
return jsonify({})
response_list = _get_from_cache(f'unlisted_videos_{site_code}')
if not response_list:
yb = YoutubeBroadcasts(client_id, client_secret, refresh_token)
response_list = yb.get_unlisted_videos(in_delta_minutes)
_store_in_cache(f'unlisted_videos_{site_code}', response_list, expire_seconds=UNLISTED_VIDEO_EXPIRE_SECONDS)
sm = SlackMessenger()
for video in response_list:
slack_msg = 'A new video has been uploaded to the {} YouTube Channel and may need a cover image.' \
' {} https://www.youtube.com/watch?v={}'
msg = slack_msg.format(site_code.upper(), video['title'], video['id'])
sm.send(msg, f'youtube-{site_code}', 'YouTube Unlisted FastPass ZapBot', ':youtube:')
return jsonify(response_list)
def _broadcasts(site_code: str, client_id: str, client_secret: str, refresh_token: str):
if not (client_id and client_secret and refresh_token):
return jsonify({})
response_dict = _get_from_cache(f'broadcasts_{site_code}')
if not response_dict:
yb = YoutubeBroadcasts(client_id, client_secret, refresh_token)
response_dict = yb.get_broadcasts()
old_response = _get_from_cache(f'broadcasts_{site_code}', include_old=True)
old_response = {} if old_response is None else old_response
all_upcoming = response_dict['upcoming'] + old_response.get('upcoming', [])
response_dict['upcoming'] = list({v['id']: v for v in all_upcoming if v['id'] not in
[x['id'] for x in response_dict['live']]}.values())
_store_in_cache(f'broadcasts_{site_code}', response_dict, expire_seconds=BROADCAST_EXPIRE_SECONDS)
return jsonify(response_dict)
# Video
@app.route('/youtube')
def youtube():
max_results = request.args.get('maxResults', YOUTUBE_VIDS_PER_PAGE)
page_token = request.args.get('page_token', None)
if not (YOUTUBE_API_KEY and YOUTUBE_PLAYLIST_ID):
return jsonify({})
url = 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet' \
'&maxResults={}&playlistId={}&key={}'.format(max_results,
YOUTUBE_PLAYLIST_ID,
YOUTUBE_API_KEY)
if page_token:
url += '&pageToken={}'.format(page_token)
response_dict = _get_from_cache(url)
if not response_dict:
response = requests.get(url)
response_dict = format_youtube(response.json())
_store_in_cache(url, response_dict)
return jsonify(response_dict)
@app.route('/broadcasts', strict_slashes=False)
def broadcasts():
return redirect('/wdwnt/broadcasts')
@app.route('/wdwnt/broadcasts', strict_slashes=False)
def wdwnt_broadcasts():
return _broadcasts('wdwnt', BROADCAST_CLIENT_ID, BROADCAST_CLIENT_SECRET, BROADCAST_REFRESH_TOKEN)
@app.route('/upnt/broadcasts', strict_slashes=False)
def upnt_broadcasts():
return _broadcasts('upnt', BROADCAST_UPNT_CLIENT_ID, BROADCAST_UPNT_CLIENT_SECRET, BROADCAST_UPNT_REFRESH_TOKEN)
@app.route('/entertainment/broadcasts', strict_slashes=False)
def entertainment_broadcasts():
return _broadcasts('entertainment', BROADCAST_ENTERTAINMENT_CLIENT_ID, BROADCAST_ENTERTAINMENT_CLIENT_SECRET,
BROADCAST_ENTERTAINMENT_REFRESH_TOKEN)
@app.route('/broadcasts/wigs', strict_slashes=False)
def wigs_broadcasts():
if not (BROADCAST_CLIENT_ID and BROADCAST_CLIENT_SECRET and BROADCAST_REFRESH_TOKEN):
return jsonify({})
response_dict = _get_from_cache('broadcasts/unlisted')
if not response_dict:
yb = YoutubeBroadcasts(BROADCAST_CLIENT_ID, BROADCAST_CLIENT_SECRET, BROADCAST_REFRESH_TOKEN)
response_dict = yb.get_broadcasts(show_unlisted=True)
old_response = _get_from_cache('broadcasts', include_old=True)
old_response = {} if old_response is None else old_response
all_upcoming = response_dict['upcoming'] + old_response.get('upcoming', [])
response_dict['upcoming'] = list({v['id']: v for v in all_upcoming if v['id'] not in
[x['id'] for x in response_dict['live']]}.values())
_store_in_cache('broadcasts/unlisted', response_dict, expire_seconds=BROADCAST_EXPIRE_SECONDS)
return jsonify(response_dict)
@app.route('/broadcasts/debug', strict_slashes=False)
def debug_broadcasts():
if not (BROADCAST_CLIENT_ID and BROADCAST_CLIENT_SECRET and BROADCAST_REFRESH_TOKEN):
return jsonify({})
yb = YoutubeBroadcasts(BROADCAST_CLIENT_ID, BROADCAST_CLIENT_SECRET, BROADCAST_REFRESH_TOKEN)
response_dict = yb.get_broadcasts(show_unlisted=True, debug=True)
return jsonify(response_dict)
@app.route('/unlisted_videos', strict_slashes=False)
def unlisted_videos():
return redirect('/wdwnt/unlisted_videos')
@app.route('/wdwnt/unlisted_videos', strict_slashes=False)
def wdwnt_unlisted_videos():
return _unlisted_videos('wdwnt', BROADCAST_CLIENT_ID, BROADCAST_CLIENT_SECRET, BROADCAST_REFRESH_TOKEN)
@app.route('/upnt/unlisted_videos', strict_slashes=False)
def upnt_unilisted_videos():
return _unlisted_videos('upnt', BROADCAST_UPNT_CLIENT_ID, BROADCAST_UPNT_CLIENT_SECRET,
BROADCAST_UPNT_REFRESH_TOKEN)
@app.route('/entertainment/unlisted_videos', strict_slashes=False)
def entertainment_unlisted_videos():
return _unlisted_videos('entertainment', BROADCAST_ENTERTAINMENT_CLIENT_ID, BROADCAST_ENTERTAINMENT_CLIENT_SECRET,
BROADCAST_ENTERTAINMENT_REFRESH_TOKEN)
# Podcasts
@app.route('/podcasts', strict_slashes=False)
def podcasts():
in_per_page = request.args.get('per_page', POSTS_PER_PAGE)
in_page = request.args.get('page', 1)
with_content = 'nocontent' not in request.args
with_player = 'noplayer' not in request.args
url = 'https://podcasts.wdwnt.com/wp-json/wp/v2/posts?per_page={}&page={}&_embed'
url = url.format(in_per_page, in_page)
cache_url = '{}|{}|{}'.format('WithContent' if with_content else 'NoContent',
'WithPlayer' if with_player else 'NoPlayer', url)
# TODO - use cache data with content/player to populate NoContent/NoPlayer
# print(url)
response_dict = _get_from_cache(cache_url)
if not response_dict:
response = requests.get(url, headers=WP_HEADER)
response_dict = format_wp(response.json(), with_content=with_content, with_player=with_player)
_store_in_cache(cache_url, response_dict)
return jsonify(response_dict)
@app.route('/podcasts/<int:post_id>')
def single_podcast(post_id):
# Do something with page_id
url = 'https://podcasts.wdwnt.com/wp-json/wp/v2/posts/{}?_embed'
url = url.format(post_id)
# print(url)
with_player = 'noplayer' not in request.args
cache_url = '{}|{}'.format('WithPlayer' if with_player else 'NoPlayer', url)
response_dict = _get_from_cache(cache_url)
if not response_dict:
response = requests.get(url, headers=WP_HEADER)
response_dict = format_wp_single_post(response.json(), with_player=with_player)
_store_in_cache(cache_url, response_dict)
return jsonify(response_dict)
# Blog posts, pages, and utilities
@app.route('/posts', strict_slashes=False)
def posts():
in_per_page = request.args.get('per_page', POSTS_PER_PAGE)
in_page = request.args.get('page', 1)
in_slug = request.args.get('slug', '')
in_categories = request.args.get('categories', '')
in_search = request.args.get('search', '')
add_to_cache = True
if in_slug:
url = 'https://wdwnt.com/wp-json/wp/v2/posts?slug={}&_embed'
url = url.format(in_slug)
elif in_categories:
url = 'https://wdwnt.com/wp-json/wp/v2/posts?categories={}&per_page={}&page={}&_embed'
url = url.format(in_categories, in_per_page, in_page)
elif in_search:
url = 'https://wdwnt.com/wp-json/wp/v2/posts?search={}&per_page={}&page={}&_embed'
url = url.format(in_search, in_per_page, in_page)
add_to_cache = False
else:
url = 'https://wdwnt.com/wp-json/wp/v2/posts?per_page={}&page={}&_embed'
url = url.format(in_per_page, in_page)
# print(url)
response_dict = _get_from_cache(url)
if not response_dict:
response = requests.get(url, headers=WP_HEADER)
response_dict = format_wp(response.json())
if add_to_cache:
_store_in_cache(url, response_dict)
return jsonify(response_dict)
@app.route('/cpt/<cpt_type>', strict_slashes=False)
@app.route('/cpt/<cpt_type>/<int:cpt_id>', strict_slashes=False)
def cpt(cpt_type, cpt_id=None):
if not cpt_type:
return jsonify({})
in_per_page = request.args.get('per_page', POSTS_PER_PAGE)
in_page = request.args.get('page', 1)
if cpt_id:
url = f'https://wdwnt.com/wp-json/wp/v2/{cpt_type}/{cpt_id}?_embed'
else:
url = f'https://wdwnt.com/wp-json/wp/v2/{cpt_type}?per_page={in_per_page}&page={in_page}&_embed'
response_dict = _get_from_cache(url)
if not response_dict:
response = requests.get(url, headers=WP_HEADER)
if response.status_code == 404:
response_dict = {}
elif cpt_id:
response_dict = format_wp_single_post(response.json())
else:
response_dict = format_wp(response.json())
_store_in_cache(url, response_dict)
return jsonify(response_dict)
@app.route('/posts/<int:post_id>')
def single_post(post_id):
# Do something with page_id
url = 'https://wdwnt.com/wp-json/wp/v2/posts/{}?_embed'
url = url.format(post_id)
# print(url)
response_dict = _get_from_cache(url)
if not response_dict:
response = requests.get(url, headers=WP_HEADER)
response_dict = format_wp_single_post(response.json())
_store_in_cache(url, response_dict)
return jsonify(response_dict)
@app.route('/pages', strict_slashes=False)
def pages():
in_per_page = request.args.get('per_page', POSTS_PER_PAGE)
in_page = request.args.get('page', 1)
in_slug = request.args.get('slug', '')
if in_slug:
url = 'https://wdwnt.com/wp-json/wp/v2/pages?slug={}&_embed'
url = url.format(in_slug)
else:
url = 'https://wdwnt.com/wp-json/wp/v2/pages?per_page={}&page={}&_embed'
url = url.format(in_per_page, in_page)
# print(url)
response_dict = _get_from_cache(url)
if not response_dict:
response = requests.get(url, headers=WP_HEADER)
response_dict = format_wp(response.json())
_store_in_cache(url, response_dict)
return jsonify(response_dict)
@app.route('/pages/<int:post_id>')
def single_page(post_id):
# Do something with page_id
url = 'https://wdwnt.com/wp-json/wp/v2/pages/{}?_embed'
url = url.format(post_id)
# print(url)
response_dict = _get_from_cache(url)
if not response_dict:
response = requests.get(url, headers=WP_HEADER)
response_dict = format_wp_single_post(response.json())
_store_in_cache(url, response_dict)
return jsonify(response_dict)
@app.route('/announcements', strict_slashes=False)
def announcements():
# url = 'https://wdwnt.com/wp-json/wp/v2/announcements?appflag=7566,7568'
# https://wdwnt.com/wp-json/wp/v2/appflag?include=7566,7568
url = 'https://wdwnt.com/wp-json/wp/v2/announcements?_embed'
response_dict = _get_from_cache(url)
if not response_dict:
response = requests.get(url, headers=WP_HEADER)
response_dict = {}
for a_id, slug in WP_APPFLAGS.items():
response_dict[slug] = [format_wp_single_post(x, with_icon=True)
for x in response.json()
if x['appflag'][0] == a_id]
_store_in_cache(url, response_dict)
return jsonify(response_dict)
@app.route('/notifications', strict_slashes=False)
def notifications():
in_per_page = request.args.get('per_page', POSTS_PER_PAGE)
in_page = request.args.get('page', 1)
url = 'https://wdwnt.com/wp-json/wp/v2/app_notification?per_page={}&page={}'
url = url.format(in_per_page, in_page)
response_dict = _get_from_cache(url)
if not response_dict:
response = requests.get(url, headers=WP_HEADER)
response_dict = format_notifications(response.json())
_store_in_cache(url, response_dict)
return jsonify(response_dict)
# Instagram via RSSHub
@app.route('/instagram/<string:username>', strict_slashes=False)
def instagram(username):
url = 'https://rsshub.app/picuki/profile/{}'
url = url.format(username)
response_string = _get_from_cache(url)
if not response_string:
response = requests.get(url)
response_string = response.text
_store_in_cache(url, response_string, expire_seconds=INSTAGRAM_EXPIRE_SECONDS)
return response_string
# Live365
@app.route('/live365')
def live365():
url = 'https://api.live365.com/station/a31769'
response_dict = _get_from_cache(url)
if not response_dict:
response = requests.get(url, timeout=TIMEOUT_SECONDS)
try:
response.raise_for_status()
response_dict = format_live365(response.json())
except requests.exceptions.HTTPError:
err_resp = _get_error_json(request.path)
_store_in_cache(url, err_resp, expire_seconds=LIVE365_EXPIRE_SECONDS)
return jsonify(err_resp)
calc_end_time = datetime.utcnow() + timedelta(seconds=LIVE365_EXPIRE_SECONDS)
calc_end_time = calc_end_time.replace(tzinfo=timezone.utc)
if response_dict['live_dj_on']:
response_dict['current-track']['end'] = calc_end_time.isoformat()
response_dict['current-track']['duration'] = str(timedelta(seconds=LIVE365_EXPIRE_SECONDS))
_store_in_cache(url, response_dict)
else:
if response_dict['current-track'].get('end') is None:
ending = calc_end_time
response_dict['current-track']['end'] = calc_end_time.isoformat()
else:
track_end = parser.parse(response_dict['current-track']['end'])
if track_end < calc_end_time:
ending = track_end
else:
ending = calc_end_time
# Replace ending so that it checks more frequently.
response_dict['current-track']['end'] = calc_end_time.isoformat()
_store_in_cache(url, response_dict, expire_time=ending)
return jsonify(response_dict)
@app.route('/ntunes')
def ntunes():
response_dict = {'url': NTUNES_AUDIO_URL}
return jsonify(response_dict)
def event_to_retval(event):
return {
'showName': event.summary,
'showTime': event.start,
'showUrl': None,
'showTitle': None
}
@app.route('/calendar')
def calendar():
page = int(request.args.get('page', default='0'))
count = int(request.args.get('count', default='20'))
first_event = page * count
last_event = first_event + count
# get calendar (PUBLIC_CALENDAR_URL) from cache if available
response_string = _get_from_cache(PUBLIC_CALENDAR_URL)
if not response_string:
response = requests.get(PUBLIC_CALENDAR_URL)
response_string = response.text
_store_in_cache(PUBLIC_CALENDAR_URL, response_string, expire_seconds=INSTAGRAM_EXPIRE_SECONDS)
es = events(string_content=response_string.encode(), start=date.today())
es.sort(key=lambda event: event.start)
selected_events = es[first_event:last_event]
retval = list(map(event_to_retval, selected_events))
return jsonify({
'shows': retval
})
# Internal Utilities
@app.route('/clear', methods=['POST'])
def clear_cache():
data = request.json
if data is not None:
status = data.get('status')
else:
status = ''
resp = _clear_cache(status)
return ('', 204) if resp else (jsonify({'status': 'Invalid status'}), 401)
@app.route('/refresh_posts', methods=['POST'])
def clear_posts():
data = request.json
if data is not None:
status = data.get('status')
else:
status = ''
resp = _clear_posts(status)
return ('', 204) if resp else (jsonify({'status': 'Invalid status'}), 401)
@app.route('/settings')
def settings_call():
if GIT_COMMIT:
ver = GIT_COMMIT
else:
ver = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'])
ver = ver.decode().rstrip()
# TODO - Expand with more settings like environment variables.
return jsonify({
'version': ver,
'description': GIT_DESCRIPTION,
'deployed_at': GIT_RELEASE_AT,
'mem_cache': mem_cache
})
@app.route('/')
def root_page():
return app.send_static_file('index.html')
if __name__ == '__main__':
app.run(debug=True, port=SERVER_PORT)
| []
| []
| [
"FASTPASS_NTUNES_AUDIO_URL",
"HEROKU_RELEASE_CREATED_AT",
"FASTPASS_CACHE_SYSTEM",
"FASTPASS_REDIS_HOST",
"FASTPASS_BROADCAST_UPNT_CLIENT_SECRET",
"HEROKU_SLUG_DESCRIPTION",
"FASTPASS_POSTS_PER_PAGE",
"FASTPASS_TIMEOUT_SECONDS",
"FASTPASS_HOST_PORT",
"FASTPASS_BROADCAST_CLIENT_ID",
"FASTPASS_BROADCAST_REFRESH_TOKEN",
"FASTPASS_YOUTUBE_API_KEY",
"FASTPASS_BROADCAST_EXPIRE_SECONDS",
"FASTPASS_BROADCAST_ENTERTAINMENT_CLIENT_SECRET",
"FASTPASS_BROADCAST_UPNT_REFRESH_TOKEN",
"FASTPASS_PUBLIC_CALENDAR_URL",
"FASTPASS_LIVE365_EXPIRE_SECONDS",
"FASTPASS_YOUTUBE_PLAYLIST_ID",
"FASTPASS_REDIS_PORT",
"FASTPASS_REDIS_USE_SSL",
"FASTPASS_BROADCAST_UPNT_CLIENT_ID",
"HEROKU_SLUG_COMMIT",
"FASTPASS_YOUTUBE_VIDS_PER_PAGE",
"FASTPASS_YOUTUBE_EXPIRE_SECONDS",
"FASTPASS_BROADCAST_CLIENT_SECRET",
"FASTPASS_BROADCAST_ENTERTAINMENT_CLIENT_ID",
"FASTPASS_BROADCAST_ENTERTAINMENT_REFRESH_TOKEN",
"FASTPASS_CACHE_EXPIRE_SECONDS",
"FASTPASS_UNLISTED_VIDEO_EXPIRE_SECONDS",
"FASTPASS_INSTAGRAM_EXPIRE_SECONDS",
"FASTPASS_REDIS_PASSWORD",
"FASTPASS_YOUTUBE_THUMBNAIL_QUALITY"
]
| [] | ["FASTPASS_NTUNES_AUDIO_URL", "HEROKU_RELEASE_CREATED_AT", "FASTPASS_CACHE_SYSTEM", "FASTPASS_REDIS_HOST", "FASTPASS_BROADCAST_UPNT_CLIENT_SECRET", "HEROKU_SLUG_DESCRIPTION", "FASTPASS_POSTS_PER_PAGE", "FASTPASS_TIMEOUT_SECONDS", "FASTPASS_HOST_PORT", "FASTPASS_BROADCAST_CLIENT_ID", "FASTPASS_BROADCAST_REFRESH_TOKEN", "FASTPASS_YOUTUBE_API_KEY", "FASTPASS_BROADCAST_EXPIRE_SECONDS", "FASTPASS_BROADCAST_ENTERTAINMENT_CLIENT_SECRET", "FASTPASS_BROADCAST_UPNT_REFRESH_TOKEN", "FASTPASS_PUBLIC_CALENDAR_URL", "FASTPASS_LIVE365_EXPIRE_SECONDS", "FASTPASS_YOUTUBE_PLAYLIST_ID", "FASTPASS_REDIS_PORT", "FASTPASS_REDIS_USE_SSL", "FASTPASS_BROADCAST_UPNT_CLIENT_ID", "HEROKU_SLUG_COMMIT", "FASTPASS_YOUTUBE_VIDS_PER_PAGE", "FASTPASS_YOUTUBE_EXPIRE_SECONDS", "FASTPASS_BROADCAST_CLIENT_SECRET", "FASTPASS_BROADCAST_ENTERTAINMENT_CLIENT_ID", "FASTPASS_BROADCAST_ENTERTAINMENT_REFRESH_TOKEN", "FASTPASS_CACHE_EXPIRE_SECONDS", "FASTPASS_UNLISTED_VIDEO_EXPIRE_SECONDS", "FASTPASS_INSTAGRAM_EXPIRE_SECONDS", "FASTPASS_REDIS_PASSWORD", "FASTPASS_YOUTUBE_THUMBNAIL_QUALITY"] | python | 32 | 0 | |
FORTISApp.bak.py | from flask import Flask, render_template, flash, redirect, url_for, request, g, session, abort, send_from_directory
from wtforms import Form, validators, StringField, TextAreaField, SelectField, PasswordField
from werkzeug.utils import secure_filename
from passlib.hash import sha256_crypt
from functools import wraps
import os
import pandas as pd
from flask_sqlalchemy import SQLAlchemy
import boto3
from random import randint
import json
import sys
import dropbox
import mammoth
app = Flask(__name__)
# Set config variables:
assert "APP_SETTINGS" in os.environ, "APP_SETTINGS environment variable not set"
assert "SECRET_KEY" in os.environ, "SECRET_KEY environment variable not set"
assert "ADMIN_PWD" in os.environ, "ADMIN_PWD environment variable not set"
assert "DATABASE_URL" in os.environ, "DATABASE_URL environment variable not set"
assert "S3_OR_DBX" in os.environ, "S3_OR_DBX environment variable not set"
if os.environ['S3_OR_DBX'] == 'S3':
assert "AWS_ACCESS_KEY_ID" in os.environ, "AWS_ACCESS_KEY_ID environment variable not set"
assert "AWS_SECRET_ACCESS_KEY" in os.environ, "AWS_SECRET_ACCESS_KEY environment variable not set"
assert "S3_BUCKET" in os.environ, "S3_BUCKET environment variable not set"
elif os.environ['S3_OR_DBX'] == 'DBX':
assert "DROPBOX_KEY" in os.environ, "DROPBOX_KEY environment variable not set"
else:
sys.exit("Variable S3_OR_DBX not set correctly")
app.config.from_object(os.environ['APP_SETTINGS'])
# Configure postgresql database:
db = SQLAlchemy(app)
from models import Trainees, Trainers, Workshops, Files, Timetables, Folders
# ######### GLOBAL VARIABLES ##########
typeDict = {
'lectures1': 'Day 1 / Lectures / ',
'practicals1': 'Day 1 / Practical 1 /',
'practicals2-1': 'Day 1 / Practical 2 / ',
'lectures2': 'Day 2 / Lectures / ',
'practicals2': 'Day 2 / Practical 1 / ',
'practicals2-2': 'Day 2 / Practical 2 / ',
'lectures3': 'Day 3 / Lectures / ',
'practicals3': 'Day 3 / Practical 1 / ',
'practicals2-3': 'Day 3 / Practical 2 / ',
'lectures4': 'Day 4 / Lectures / ',
'practicals4': 'Day 4 / Practical 1 / ',
'practicals2-4': 'Day 4 / Practical 2 / ',
'lectures5': 'Day 5 / Lectures / ',
'practicals5': 'Day 5 / Practical 1 / ',
'other': 'Other'
}
######################################
# ######### PSQL FUNCTIONS ##########
def psql_to_pandas(query):
df = pd.read_sql(query.statement, db.session.bind)
return df
def psql_insert(row):
db.session.add(row)
db.session.commit()
return row.id
def psql_delete(row):
db.session.delete(row)
db.session.commit()
return
####################################
# ######### S3 FUNCTIONS/ROUTES ##########
def delete_file_from_s3(filename):
bucket_name = app.config['S3_BUCKET']
s3 = boto3.resource('s3', 'eu-west-2')
s3.Object(bucket_name, filename).delete()
return
@app.route('/sign_s3/')
def sign_s3():
bucket_name = app.config['S3_BUCKET']
filename_orig = request.args.get('file_name')
filename_s3 = str(randint(10000, 99999)) + '_' + \
secure_filename(filename_orig)
file_type = request.args.get('file_type')
s3 = boto3.client('s3', 'eu-west-2')
presigned_post = s3.generate_presigned_post(
Bucket=bucket_name,
Key=filename_s3,
Fields={"acl": "private", "Content-Type": file_type},
Conditions=[
{"acl": "private"},
{"Content-Type": file_type}
],
ExpiresIn=3600
)
return json.dumps({
'data': presigned_post,
'url': 'https://%s.s3.eu-west-2.amazonaws.com/%s' % (bucket_name, filename_s3)
})
@app.route('/sign_s3_download_timetable/')
def sign_s3_download_timetable():
bucket_name = app.config['S3_BUCKET']
id = request.args.get('id')
# Retrieve s3 filename from DB:
db_entry = Timetables.query.filter_by(id=id).first()
filename_s3 = db_entry.filename
# Access granting:
if not 'logged_in' in session:
abort(403)
# Create and return pre-signed url:
s3 = boto3.client('s3', 'eu-west-2')
presigned_url = s3.generate_presigned_url(
'get_object',
Params={'Bucket': bucket_name, 'Key': filename_s3},
ExpiresIn=3600
)
return json.dumps({
'url': presigned_url,
})
@app.route('/sign_s3_download_file/')
def sign_s3_download_file():
bucket_name = app.config['S3_BUCKET']
id = request.args.get('id')
# Retrieve s3 filename from DB:
db_entry = Files.query.filter_by(id=id).first()
filename_s3 = db_entry.filename
# Access granting:
who = db_entry.who
if not 'logged_in' in session:
abort(403)
if who == 'trainers' and session['usertype'] == 'trainee':
abort(403)
# Create and return pre-signed url:
s3 = boto3.client('s3', 'eu-west-2')
presigned_url = s3.generate_presigned_url(
'get_object',
Params={'Bucket': bucket_name, 'Key': filename_s3},
ExpiresIn=3600
)
return json.dumps({
'url': presigned_url,
})
##################################
# ######### DROPBOX FUNCTIONS ##########
def upload_file_to_dbx(file, filename):
dbx = dropbox.Dropbox(app.config['DROPBOX_KEY'])
response = dbx.files_upload(file.read(), '/' + filename, mute=True)
def download_file_from_dbx(filename):
dbx = dropbox.Dropbox(app.config['DROPBOX_KEY'])
response = dbx.files_download_to_file('/tmp/' + filename, '/' + filename)
def delete_file_from_dbx(filename):
dbx = dropbox.Dropbox(app.config['DROPBOX_KEY'])
response = dbx.files_delete('/' + filename)
##################################
# ######### LOGGED-IN FUNCTIONS ##########
# Check if user is logged in
def is_logged_in(f):
@wraps(f)
def wrap(*args, **kwargs):
if 'logged_in' in session:
return f(*args, **kwargs)
else:
flash('Unauthorised, please login', 'danger')
return redirect(url_for('index'))
return wrap
# Check if user is logged in as a trainer/admin
def is_logged_in_as_trainer(f):
@wraps(f)
def wrap(*args, **kwargs):
if 'logged_in' in session and (session['usertype'] == 'trainer' or session['usertype'] == 'admin'):
return f(*args, **kwargs)
else:
flash('Unauthorised, please login as a trainer/admin', 'danger')
return redirect(url_for('index'))
return wrap
# Check if user is logged in as admin
def is_logged_in_as_admin(f):
@wraps(f)
def wrap(*args, **kwargs):
if 'logged_in' in session and session['usertype'] == 'admin':
return f(*args, **kwargs)
else:
flash('Unauthorised, please login as admin', 'danger')
return redirect(url_for('index'))
return wrap
#########################################
########## MISC FUNCTIONS ##########
# Get list of workshops from workshop DB:
def get_workshop_list():
workshopDF = psql_to_pandas(Workshops.query)
workshopList = [('blank', '--Please select--')]
for w in workshopDF['workshop']:
workshopList.append((w, w))
return workshopList
# Get list of types for Upload Form:
def get_type_list(workshop):
typeList = [('blank', '--Please select--')]
# Add default folders:
for key, value in typeDict.items():
typeList.append((key, value))
# Add custom folders:
foldersDF = psql_to_pandas(Folders.query.filter_by(workshop=workshop))
for index, row in foldersDF.iterrows():
key = row['parent'] + '_' + row['name']
value = typeDict[row['parent']] + row['name']
typeList.append((key, value))
# Sort by second element:
typeList = sorted(typeList, key=lambda tup: tup[1])
return typeList
####################################
# ######### FORM CLASSES ##########
class TimetableForm(Form):
workshop = SelectField(u'Select the workshop that this timetable is for',
[validators.NoneOf(('blank'), message='Please select')])
class UploadForm(Form):
title = StringField(u'Title of material', [
validators.required(), validators.Length(min=1, max=50)])
description = TextAreaField(u'Description of material', [
validators.optional(), validators.Length(max=1000)])
type = SelectField('Select the type of material you are uploading',
[validators.NoneOf(('blank'), message='Please select')])
who = SelectField('Is the material for trainees (typically non-editable files, e.g. PDFs) or trainers (typically editable files, e.g. PPTs)',
[validators.NoneOf(('blank'), message='Please select')],
choices=[('blank', '--Please select--'),
('trainees', 'Trainees'),
('trainers', 'Trainers')])
class RegisterForm(Form):
username = StringField('Username',
[validators.Regexp('^BMKG_participant-[0-9]{2}$',
message='Username must be of the form BMKG_participant-XX where XX is a two-digit number')])
password = PasswordField('Password',
[validators.Regexp('^([a-zA-Z0-9]{8,})$',
message='Password must be mimimum 8 characters and contain only uppercase letters, \
lowercase letters and numbers')])
class RegisterTrainerForm(Form):
username = StringField('Username', [validators.Length(min=4, max=25)])
password = PasswordField('Password',
[validators.Regexp('^([a-zA-Z0-9]{8,})$',
message='Password must be mimimum 8 characters and contain only uppercase letters, \
lowercase letters and numbers')])
class ChangePwdForm(Form):
current = PasswordField('Current password',
[validators.DataRequired()])
new = PasswordField('New password',
[validators.Regexp('^([a-zA-Z0-9]{8,})$',
message='Password must be mimimum 8 characters and contain only uppercase letters, \
lowercase letters and numbers')])
confirm = PasswordField('Confirm new password',
[validators.EqualTo('new', message='Passwords do no match')])
##################################
# ####################################
# ######### START OF ROUTES ##########
# ####################################
# Index
@app.route('/', methods=["GET", "POST"])
def index():
if request.method == 'POST':
# Get form fields
username = request.form['username']
password_candidate = request.form['password']
# Check trainee accounts first:
user = Trainees.query.filter_by(username=username).first()
if user is not None:
password = user.password
# Compare passwords
if password_candidate == password:
# Passed
session['logged_in'] = True
session['username'] = username
session['usertype'] = 'trainee'
flash('You are now logged in', 'success')
return redirect(url_for('index'))
else:
flash('Incorrect password', 'danger')
return redirect(url_for('index'))
# Check trainer accounts next:
user = Trainers.query.filter_by(username=username).first()
if user is not None:
password = user.password
# Compare passwords
if sha256_crypt.verify(password_candidate, password):
# Passed
session['logged_in'] = True
session['username'] = username
if username != 'sam_hardy':
session['usertype'] = 'trainer'
flash('You are now logged in', 'success')
elif username == 'sam_hardy':
session['usertype'] = 'admin'
flash('You are now logged in with admin privillages', 'success')
return redirect(url_for('index'))
else:
flash('Incorrect password', 'danger')
return redirect(url_for('index'))
# Finally check admin account:
if username == 'admin':
password = app.config['ADMIN_PWD']
if password_candidate == password:
# Passed
session['logged_in'] = True
session['username'] = 'admin'
session['usertype'] = 'admin'
flash('You are now logged in', 'success')
return redirect(url_for('index'))
else:
flash('Incorrect password', 'danger')
return redirect(url_for('index'))
# Username not found:
flash('Username not found', 'danger')
return redirect(url_for('index'))
return render_template('home.html')
@app.route('/about')
def about():
return render_template('about.html')
@app.route('/timetables', methods=["GET", "POST"])
@is_logged_in
def timetables():
form = TimetableForm(request.form)
form.workshop.choices = get_workshop_list()
timetablesData = psql_to_pandas(Timetables.query)
# If user tries to upload a timetable
if request.method == 'POST':
if form.validate():
if app.config['S3_OR_DBX'] == 'S3': # Get filename only
filename = request.form['filename_s3']
else: # Also get file
file = request.files['file']
filename = str(randint(10000, 99999)) + '_' + \
secure_filename(file.filename)
# Get fields from web-form
workshop = form.workshop.data
author = session['username']
# Delete old timetable if it exists:
timetable = Timetables.query.filter_by(workshop=workshop).first()
if timetable is not None:
old_filename = timetable.filename
# Delete from DB:
psql_delete(timetable)
# Delete from cloud:
try:
if app.config['S3_OR_DBX'] == 'S3':
delete_file_from_s3(old_filename)
else:
delete_file_from_dbx(old_filename)
except:
flash("Unable to delete timetable from cloud", "warning")
# Insert new timetable into database:
db_row = Timetables(filename=filename,
workshop=workshop, author=author)
id = psql_insert(db_row)
if app.config['S3_OR_DBX'] == 'DBX': # Save file to dropbox
upload_file_to_dbx(file, filename)
# flash success message and reload page
flash('Timetable uploaded successfully', 'success')
return redirect(url_for('timetables'))
else:
if app.config['S3_OR_DBX'] == 'S3': # Delete file from S3
filename_s3 = request.form['filename_s3']
delete_file_from_s3(filename_s3)
# Flash error message:
flash('Fix form errors and try again', 'danger')
return render_template('timetables.html', form=form, timetablesData=timetablesData, S3_OR_DBX=app.config['S3_OR_DBX'])
@app.route('/partners')
def partners():
return render_template('partners.html')
@app.route('/contact-us')
def contact_us():
return render_template('contact-us.html')
@app.route('/select-workshop/<string:linkTo>')
@is_logged_in
def select_workshop(linkTo):
workshopsData = psql_to_pandas(Workshops.query)
return render_template('select-workshop.html', workshopsData=workshopsData, linkTo=linkTo)
@app.route('/training-material/<string:workshopID>')
@is_logged_in
def training_material(workshopID):
# Check workshop exists:
result = Workshops.query.filter_by(id=workshopID).first()
if result is None:
abort(404)
workshop = result.workshop
# Subset Files and Folders data:
allFilesData = psql_to_pandas(Files.query)
filesData = allFilesData.loc[allFilesData['workshop'] == workshop]
allfoldersData = psql_to_pandas(Folders.query)
foldersData = allfoldersData.loc[allfoldersData['workshop'] == workshop]
return render_template('material.html', filesData=filesData, foldersData=foldersData,
workshop=workshop, who='trainees', S3_OR_DBX=app.config['S3_OR_DBX'])
@app.route('/trainer-material/<string:workshopID>')
@is_logged_in_as_trainer
def trainer_material(workshopID):
# Check workshop exists:
result = Workshops.query.filter_by(id=workshopID).first()
if result is None:
abort(404)
workshop = result.workshop
# Subset Files and Folders data:
allFilesData = psql_to_pandas(Files.query)
filesData = allFilesData.loc[allFilesData['workshop'] == workshop]
allfoldersData = psql_to_pandas(Folders.query)
foldersData = allfoldersData.loc[allfoldersData['workshop'] == workshop]
return render_template('material.html', filesData=filesData, foldersData=foldersData,
workshop=workshop, who='trainers', S3_OR_DBX=app.config['S3_OR_DBX'])
@app.route('/upload/<string:workshopID>', methods=["GET", "POST"])
@is_logged_in_as_trainer
def upload(workshopID):
# Check workshop exists:
result = Workshops.query.filter_by(id=workshopID).first()
if result is None:
abort(404)
workshop = result.workshop
# Prepare form:
form = UploadForm(request.form)
form.type.choices = get_type_list(workshop)
# If user tries to upload a file
if request.method == 'POST':
if form.validate():
if app.config['S3_OR_DBX'] == 'S3': # Get filename only
filename = request.form['filename_s3']
else: # Also get file
file = request.files['file']
filename = str(randint(10000, 99999)) + '_' + \
secure_filename(file.filename)
# Get fields from web-form
title = form.title.data
description = form.description.data
type = form.type.data
who = form.who.data
author = session['username']
# Insert into files database:
db_row = Files(filename=filename, title=title, description=description,
workshop=workshop, type=type, who=who, author=author)
id = psql_insert(db_row)
if app.config['S3_OR_DBX'] == 'DBX': # Save file to dropbox
upload_file_to_dbx(file, filename)
# flash success message and reload page
flash('File uploaded successfully', 'success')
return redirect(url_for('upload', workshopID=workshopID))
else:
if app.config['S3_OR_DBX'] == 'S3': # Delete file from S3
filename_s3 = request.form['filename_s3']
delete_file_from_s3(filename_s3)
# Flash error message:
flash('Fix form errors and try again', 'danger')
# If user just navigates to page
return render_template('upload.html', form=form, workshop=workshop,
workshopID=workshopID, S3_OR_DBX=app.config['S3_OR_DBX'])
@app.route('/trainee-accounts', methods=["GET", "POST"])
@is_logged_in_as_trainer
def trainee_accounts():
usersData = psql_to_pandas(Trainees.query.order_by(Trainees.username))
form = RegisterForm(request.form)
if request.method == 'POST' and form.validate():
username = form.username.data
# Check username is unique
user = Trainees.query.filter_by(username=username).first()
if user is not None:
flash('Username already exists', 'danger')
return redirect(url_for('trainee_accounts'))
password = form.password.data
db_row = Trainees(username=username, password=password)
id = psql_insert(db_row)
flash('Trainee account added', 'success')
return redirect(url_for('trainee_accounts'))
return render_template('trainee-accounts.html', form=form, usersData=usersData)
@app.route('/trainer-accounts', methods=["GET", "POST"])
@is_logged_in_as_admin
def trainer_accounts():
usersData = psql_to_pandas(Trainers.query)
form = RegisterTrainerForm(request.form)
if request.method == 'POST' and form.validate():
username = form.username.data
# Check username is unique
user = Trainers.query.filter_by(username=username).first()
if user is not None:
flash('Username already exists', 'danger')
return redirect(url_for('trainer_accounts'))
if username == 'admin' or username.startswith('trainee'):
flash('Username not allowed', 'danger')
return redirect(url_for('trainer_accounts'))
password = sha256_crypt.encrypt(str(form.password.data))
db_row = Trainers(username=username, password=password)
id = psql_insert(db_row)
flash('Trainer account added', 'success')
return redirect(url_for('trainer_accounts'))
return render_template('trainer-accounts.html', form=form, usersData=usersData)
@app.route('/change-pwd', methods=["GET", "POST"])
@is_logged_in_as_trainer
def change_pwd():
form = ChangePwdForm(request.form)
if request.method == 'POST' and form.validate():
user = Trainers.query.filter_by(username=session['username']).first()
password = user.password
current = form.current.data
if sha256_crypt.verify(current, password):
user.password = sha256_crypt.encrypt(str(form.new.data))
db.session.commit()
flash('Password changed', 'success')
return redirect(url_for('change_pwd'))
else:
flash('Current password incorrect', 'danger')
return redirect(url_for('change_pwd'))
return render_template('change-pwd.html', form=form)
@app.route('/workshops', methods=["GET", "POST"])
@is_logged_in_as_admin
def workshops():
workshopsData = psql_to_pandas(Workshops.query)
if request.method == 'POST':
workshop = request.form['workshop']
db_row = Workshops(workshop=workshop)
id = psql_insert(db_row)
flash('Workshop added', 'success')
return redirect(url_for('workshops'))
return render_template('workshops.html', workshopsData=workshopsData)
@app.route('/folders/<string:id>')
@is_logged_in_as_admin
def folders(id):
# Retrieve workshop:
result = Workshops.query.filter_by(id=id).first()
if result is None:
abort(404)
allFoldersData = psql_to_pandas(Folders.query)
foldersData = allFoldersData.loc[allFoldersData['workshop']
== result.workshop]
return render_template('folders.html', data=foldersData, workshopName=result.workshop, workshopID=id)
@app.route('/add-folder/<string:id>/<string:parent>', methods=["POST"])
@is_logged_in_as_admin
def add_folder(id, parent):
# Retrieve workshop:
workshop = Workshops.query.filter_by(id=id).first().workshop
name = request.form['folder']
db_row = Folders(workshop=workshop, parent=parent, name=name)
dummy = psql_insert(db_row)
return redirect(url_for('folders', id=id))
@app.route('/delete-folder/<string:id>', methods=["POST"])
@is_logged_in_as_admin
def delete_folder(id):
# Retrieve folder:
folder = Folders.query.filter_by(id=id).first()
if folder is None:
abort(404)
# Retrieve workshop id:
workshop = folder.workshop
workshopID = Workshops.query.filter_by(workshop=workshop).first().id
# Check folder is empty:
type = folder.parent + '_' + folder.name
filesInFolder = Files.query.filter_by(workshop=workshop, type=type).first()
if filesInFolder is not None:
flash("Cannot delete folder until it is empty (check both trainee and trainer material)", "danger")
return redirect(url_for('folders', id=workshopID))
# Delete from DB:
psql_delete(folder)
flash("Folder deleted", "success")
return redirect(url_for('folders', id=workshopID))
@app.route('/edit/<string:id>/<string:S3_OR_DBX>', methods=["POST"])
@is_logged_in_as_trainer
def edit(id, S3_OR_DBX):
result = Files.query.filter_by(id=id).first()
if result is None:
abort(404)
workshop = result.workshop
if 'edit' in request.form:
form = UploadForm()
form.type.choices = get_type_list(workshop)
form.title.data = result.title
form.description.data = result.description
form.type.data = result.type
form.who.data = result.who
return render_template('edit.html', form=form, id=id, S3_OR_DBX=S3_OR_DBX)
else:
form = UploadForm(request.form)
form.type.choices = get_type_list(workshop)
if form.validate():
if app.config['S3_OR_DBX'] == 'S3': # Get filename only
filename = request.form['filename_s3']
else: # Also get file
if 'file' in request.files:
file = request.files['file']
filename = str(randint(10000, 99999)) + \
'_' + secure_filename(file.filename)
else:
filename = ''
# Delete old file if not blank:
if not filename == '':
old_filename = result.filename
if app.config['S3_OR_DBX'] == 'S3':
delete_file_from_s3(old_filename)
else:
delete_file_from_dbx(old_filename)
# Save new file to dropbox:
upload_file_to_dbx(file, filename)
result.filename = filename
# Get form info:
title = form.title.data
description = form.description.data
type = form.type.data
who = form.who.data
# Update DB:
result.title = title
result.description = description
result.type = type
result.who = who
db.session.commit()
flash('File edits successful', 'success')
return redirect(url_for('index'))
else:
# Delete file from S3 if not blank:
if app.config['S3_OR_DBX'] == 'S3':
filename = request.form['filename_s3']
if not filename == "":
delete_file_from_s3(filename)
# Flash error message:
flash('Invalid option selected, please try to edit the file again', 'danger')
return redirect(url_for('index'))
# Download file (Dropbox only)
@app.route('/download-file/<string:id>', methods=['POST'])
@is_logged_in
def download_file(id):
result = Files.query.filter_by(id=id).first()
if result is None:
abort(404)
filename = result.filename
# Try to download the file from dbx to /tmp if it's not already there:
if not os.path.exists('/tmp/' + filename):
try:
download_file_from_dbx(filename)
except:
flash("Unable to download file", "danger")
return redirect(url_for('index'))
# Serve the file to the client:
if os.path.exists('/tmp/' + filename):
return send_from_directory('/tmp', filename, as_attachment=True, attachment_filename=filename)
else:
abort(404)
# Download timetable (Dropbox only)
@app.route('/download-timetable/<string:id>', methods=['POST'])
@is_logged_in
def download_timetable(id):
result = Timetables.query.filter_by(id=id).first()
if result is None:
abort(404)
filename = result.filename
# Try to download the timetable from dbx to /tmp if it's not already there:
if not os.path.exists('/tmp/' + filename):
try:
download_file_from_dbx(filename)
except:
flash("Unable to download timetable", "danger")
return redirect(url_for('timetables'))
# Serve the timetable to the client:
if os.path.exists('/tmp/' + filename):
return send_from_directory('/tmp', filename, as_attachment=True, attachment_filename=filename)
else:
abort(404)
# View timetable (Dropbox only; docx files only)
@app.route('/view-timetable/<string:id>')
@is_logged_in
def view_timetable(id):
if app.config['S3_OR_DBX'] != 'DBX':
abort(403)
result = Timetables.query.filter_by(id=id).first()
if result is None:
abort(404)
filename = result.filename
# Try to download the timetable from dbx to /tmp if it's not already there:
if not os.path.exists('/tmp/' + filename):
try:
download_file_from_dbx(filename)
except:
flash("Unable to download timetable", "danger")
return redirect(url_for('timetables'))
# Convert to HTML:
try:
with open('/tmp/' + filename, "rb") as docx_file:
result = mammoth.convert_to_html(docx_file)
text = result.value
print(text)
return text
except:
flash("Unable to convert to html", "danger")
return redirect(url_for('timetables'))
# Delete file
@app.route('/delete-file/<string:id>', methods=['POST'])
@is_logged_in_as_trainer
def delete_file(id):
result = Files.query.filter_by(id=id).first()
if result is None:
abort(404)
filename = result.filename
# Delete from DB:
psql_delete(result)
# Delete from cloud:
try:
if app.config['S3_OR_DBX'] == 'S3':
delete_file_from_s3(filename)
else:
delete_file_from_dbx(filename)
except:
flash("Unable to delete file from cloud", "warning")
flash("File deleted", "success")
return redirect(url_for('index'))
# Delete timetable
@app.route('/delete-timetable/<string:id>', methods=['POST'])
@is_logged_in_as_trainer
def delete_timetable(id):
result = Timetables.query.filter_by(id=id).first()
if result is None:
abort(404)
filename = result.filename
# Delete from DB:
psql_delete(result)
# Delete from cloud:
try:
if app.config['S3_OR_DBX'] == 'S3':
delete_file_from_s3(filename)
else:
delete_file_from_dbx(filename)
except:
flash("Unable to delete timetable from cloud", "warning")
flash("Timetable deleted", "success")
return redirect(url_for('timetables'))
# Delete trainee
@app.route('/delete-trainee/<string:id>', methods=['POST'])
@is_logged_in_as_admin
def delete_trainee(id):
result = Trainees.query.filter_by(id=id).first()
if result is None:
abort(404)
psql_delete(result)
flash('Trainee account deleted', 'success')
return redirect(url_for('trainee_accounts'))
# Delete trainer
@app.route('/delete-trainer/<string:id>', methods=['POST'])
@is_logged_in_as_admin
def delete_trainer(id):
result = Trainers.query.filter_by(id=id).first()
if result is None:
abort(404)
psql_delete(result)
flash('Trainer account deleted', 'success')
return redirect(url_for('trainer_accounts'))
# Delete workshop
@app.route('/delete-workshop/<string:id>', methods=['POST'])
@is_logged_in_as_admin
def delete_workshop(id):
result = Workshops.query.filter_by(id=id).first()
if result is None:
abort(404)
psql_delete(result)
flash('Workshop deleted', 'success')
return redirect(url_for('workshops'))
# Logout
@app.route('/logout')
@is_logged_in
def logout():
session.clear()
flash('You are now logged out', 'success')
return redirect(url_for('index'))
if __name__ == '__main__':
app.run(debug=True)
| []
| []
| [
"APP_SETTINGS",
"S3_OR_DBX"
]
| [] | ["APP_SETTINGS", "S3_OR_DBX"] | python | 2 | 0 | |
DTO/indexDTO/novel_by_navigation.go | package indexDTO
import (
"encoding/json"
"ms_novel/model"
"os"
)
var INDEX_NAVIGATION_NOVELS_LIMIT = 17
// 总输出DTO
type NovelByNavDataDTO struct {
List []*NovelByNavCopy
}
type NovelNavigationDTO struct {
Id int `json:"id"`
NavigationName string `json:"navigationName"`
Novels []*NovelByNavDTO `json:"novels"`
}
type NovelByNavCopy struct {
model.NovelNavigation
}
type NovelByNavDTO struct {
Id int `json:"id"`
NovelCover string `json:"novelCover"`
NovelAuthor string `json:"novelAuthor"`
NovelTitle string `json:"novelTitle"`
NovelDescription string `json:"novelDescription"`
}
func (p *NovelByNavCopy) MarshalJSON() ([]byte, error) {
var novels []*NovelByNavDTO
for _, value := range p.Novels {
novelAuthor := value.NovelAuthor
if novelAuthor == "" {
novelAuthor = "佚名"
}
novel := NovelByNavDTO{
Id: value.Id,
NovelCover: os.Getenv("FS_HOST") + value.NovelCover,
NovelAuthor: novelAuthor,
NovelTitle: value.NovelTitle,
NovelDescription: value.NovelDescription,
}
novels = append(novels, &novel)
// 首页每个导航栏目下最多展示17个小说
if len(novels) == INDEX_NAVIGATION_NOVELS_LIMIT {
break
}
}
novelNavigationDTO := NovelNavigationDTO{
Id: p.Id,
NavigationName: p.NavigationName,
Novels: novels,
}
return json.Marshal(novelNavigationDTO)
}
| [
"\"FS_HOST\""
]
| []
| [
"FS_HOST"
]
| [] | ["FS_HOST"] | go | 1 | 0 | |
sql-resource/provider/src/main/java/org/openecomp/sdnc/sli/resource/sql/SqlResourceActivator.java | /*-
* ============LICENSE_START=======================================================
* openECOMP : SDN-C
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights
* reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
*/
package org.openecomp.sdnc.sli.resource.sql;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import org.openecomp.sdnc.sli.SvcLogicResource;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SqlResourceActivator implements BundleActivator {
private static final String SQLRESOURCE_PROP_PATH = "/sql-resource.properties";
private ServiceRegistration registration = null;
private static final Logger LOG = LoggerFactory
.getLogger(SqlResourceActivator.class);
@Override
public void start(BundleContext ctx) throws Exception {
String cfgDir = System.getenv("SDNC_CONFIG_DIR");
if ((cfgDir == null) || (cfgDir.length() == 0)) {
cfgDir = "/opt/sdnc/data/properties";
LOG.warn("SDNC_CONFIG_DIR unset - defaulting to "+cfgDir);
}
String cryptKey = "";
File sqlResourcePropFile = new File(cfgDir+SQLRESOURCE_PROP_PATH);
Properties sqlResourceProps = new Properties();
if (sqlResourcePropFile.exists()) {
try {
sqlResourceProps.load(new FileInputStream(sqlResourcePropFile));
cryptKey = sqlResourceProps.getProperty("org.openecomp.sdnc.resource.sql.cryptkey");
} catch (Exception e) {
LOG.warn(
"Could not load properties file " + sqlResourcePropFile.getAbsolutePath(), e);
}
} else {
LOG.warn("Cannot read "+sqlResourcePropFile.getAbsolutePath()+" to find encryption key - using default");
}
SqlResource.setCryptKey(cryptKey);
// Advertise Sql resource adaptor
SvcLogicResource impl = new SqlResource();
String regName = impl.getClass().getName();
if (registration == null)
{
LOG.debug("Registering SqlResource service "+regName);
registration =ctx.registerService(regName, impl, null);
}
}
@Override
public void stop(BundleContext ctx) throws Exception {
if (registration != null)
{
registration.unregister();
registration = null;
}
}
}
| [
"\"SDNC_CONFIG_DIR\""
]
| []
| [
"SDNC_CONFIG_DIR"
]
| [] | ["SDNC_CONFIG_DIR"] | java | 1 | 0 | |
encode_test.go | /*
* Copyright 2021 ByteDance Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sonic
import (
`os`
`bytes`
`encoding`
`encoding/json`
`fmt`
`log`
`math`
`reflect`
`regexp`
`runtime`
`runtime/debug`
`strconv`
`testing`
`unsafe`
`github.com/bytedance/sonic/encoder`
)
var (
debugAsyncGC = os.Getenv("SONIC_NO_ASYNC_GC") == ""
)
func TestMain(m *testing.M) {
go func () {
if !debugAsyncGC {
return
}
println("Begin GC looping...")
for {
runtime.GC()
debug.FreeOSMemory()
}
println("stop GC looping!")
}()
m.Run()
}
type Optionals struct {
Sr string `json:"sr"`
So string `json:"so,omitempty"`
Sw string `json:"-"`
Ir int `json:"omitempty"` // actually named omitempty, not an option
Io int `json:"io,omitempty"`
Slr []string `json:"slr,random"`
Slo []string `json:"slo,omitempty"`
Mr map[string]interface{} `json:"mr"`
Mo map[string]interface{} `json:",omitempty"`
Fr float64 `json:"fr"`
Fo float64 `json:"fo,omitempty"`
Br bool `json:"br"`
Bo bool `json:"bo,omitempty"`
Ur uint `json:"ur"`
Uo uint `json:"uo,omitempty"`
Str struct{} `json:"str"`
Sto struct{} `json:"sto,omitempty"`
}
var optionalsExpected = `{
"sr": "",
"omitempty": 0,
"slr": null,
"mr": {},
"fr": 0,
"br": false,
"ur": 0,
"str": {},
"sto": {}
}`
func TestOmitEmpty(t *testing.T) {
var o Optionals
o.Sw = "something"
o.Mr = map[string]interface{}{}
o.Mo = map[string]interface{}{}
got, err := encoder.EncodeIndented(&o, "", " ", 0)
if err != nil {
t.Fatal(err)
}
if got := string(got); got != optionalsExpected {
t.Errorf(" got: %s\nwant: %s\n", got, optionalsExpected)
}
}
type StringTag struct {
BoolStr bool `json:",string"`
IntStr int64 `json:",string"`
UintptrStr uintptr `json:",string"`
StrStr string `json:",string"`
NumberStr json.Number `json:",string"`
}
func TestRoundtripStringTag(t *testing.T) {
tests := []struct {
name string
in StringTag
want string // empty to just test that we roundtrip
}{
{
name: "AllTypes",
in: StringTag{
BoolStr: true,
IntStr: 42,
UintptrStr: 44,
StrStr: "xzbit",
NumberStr: "46",
},
want: `{
"BoolStr": "true",
"IntStr": "42",
"UintptrStr": "44",
"StrStr": "\"xzbit\"",
"NumberStr": "46"
}`,
},
{
// See golang.org/issues/38173.
name: "StringDoubleEscapes",
in: StringTag{
StrStr: "\b\f\n\r\t\"\\",
NumberStr: "0", // just to satisfy the roundtrip
},
want: `{
"BoolStr": "false",
"IntStr": "0",
"UintptrStr": "0",
"StrStr": "\"\\b\\f\\n\\r\\t\\\"\\\\\"",
"NumberStr": "0"
}`,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
// Indent with a tab prefix to make the multi-line string
// literals in the table nicer to read.
got, err := encoder.EncodeIndented(&test.in, "\t\t\t", "\t", 0)
if err != nil {
t.Fatal(err)
}
if got := string(got); got != test.want {
t.Fatalf(" got: %s\nwant: %s\n", got, test.want)
}
// Verify that it round-trips.
var s2 StringTag
if err := Unmarshal(got, &s2); err != nil {
t.Fatalf("Decode: %v", err)
}
if !reflect.DeepEqual(test.in, s2) {
t.Fatalf("decode didn't match.\nsource: %#v\nEncoded as:\n%s\ndecode: %#v", test.in, string(got), s2)
}
})
}
}
// byte slices are special even if they're renamed types.
type renamedByte byte
type renamedByteSlice []byte
type renamedRenamedByteSlice []renamedByte
func TestEncodeRenamedByteSlice(t *testing.T) {
s := renamedByteSlice("abc")
result, err := Marshal(s)
if err != nil {
t.Fatal(err)
}
expect := `"YWJj"`
if string(result) != expect {
t.Errorf(" got %s want %s", result, expect)
}
r := renamedRenamedByteSlice("abc")
result, err = Marshal(r)
if err != nil {
t.Fatal(err)
}
if string(result) != expect {
t.Errorf(" got %s want %s", result, expect)
}
}
type SamePointerNoCycle struct {
Ptr1, Ptr2 *SamePointerNoCycle
}
var samePointerNoCycle = &SamePointerNoCycle{}
type PointerCycle struct {
Ptr *PointerCycle
}
var pointerCycle = &PointerCycle{}
type PointerCycleIndirect struct {
Ptrs []interface{}
}
type RecursiveSlice []RecursiveSlice
var (
pointerCycleIndirect = &PointerCycleIndirect{}
mapCycle = make(map[string]interface{})
sliceCycle = []interface{}{nil}
sliceNoCycle = []interface{}{nil, nil}
recursiveSliceCycle = []RecursiveSlice{nil}
)
func init() {
ptr := &SamePointerNoCycle{}
samePointerNoCycle.Ptr1 = ptr
samePointerNoCycle.Ptr2 = ptr
pointerCycle.Ptr = pointerCycle
pointerCycleIndirect.Ptrs = []interface{}{pointerCycleIndirect}
mapCycle["x"] = mapCycle
sliceCycle[0] = sliceCycle
sliceNoCycle[1] = sliceNoCycle[:1]
for i := 3; i > 0; i-- {
sliceNoCycle = []interface{}{sliceNoCycle}
}
recursiveSliceCycle[0] = recursiveSliceCycle
}
func TestSamePointerNoCycle(t *testing.T) {
if _, err := Marshal(samePointerNoCycle); err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
func TestSliceNoCycle(t *testing.T) {
if _, err := Marshal(sliceNoCycle); err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
var unsupportedValues = []interface{}{
math.NaN(),
math.Inf(-1),
math.Inf(1),
pointerCycle,
pointerCycleIndirect,
mapCycle,
sliceCycle,
recursiveSliceCycle,
}
func TestUnsupportedValues(t *testing.T) {
for _, v := range unsupportedValues {
if _, err := Marshal(v); err != nil {
if _, ok := err.(*json.UnsupportedValueError); !ok {
t.Errorf("for %v, got %T want UnsupportedValueError", v, err)
}
} else {
t.Errorf("for %v, expected error", v)
}
}
}
// Ref has Marshaler and Unmarshaler methods with pointer receiver.
type Ref int
func (*Ref) MarshalJSON() ([]byte, error) {
return []byte(`"ref"`), nil
}
func (r *Ref) UnmarshalJSON([]byte) error {
*r = 12
return nil
}
// Val has Marshaler methods with value receiver.
type Val int
func (Val) MarshalJSON() ([]byte, error) {
return []byte(`"val"`), nil
}
// RefText has Marshaler and Unmarshaler methods with pointer receiver.
type RefText int
func (*RefText) MarshalText() ([]byte, error) {
return []byte(`"ref"`), nil
}
func (r *RefText) UnmarshalText([]byte) error {
*r = 13
return nil
}
// ValText has Marshaler methods with value receiver.
type ValText int
func (ValText) MarshalText() ([]byte, error) {
return []byte(`"val"`), nil
}
func TestRefValMarshal(t *testing.T) {
var s = struct {
R0 Ref
R1 *Ref
R2 RefText
R3 *RefText
V0 Val
V1 *Val
V2 ValText
V3 *ValText
}{
R0: 12,
R1: new(Ref),
R2: 14,
R3: new(RefText),
V0: 13,
V1: new(Val),
V2: 15,
V3: new(ValText),
}
const want = `{"R0":"ref","R1":"ref","R2":"\"ref\"","R3":"\"ref\"","V0":"val","V1":"val","V2":"\"val\"","V3":"\"val\""}`
b, err := Marshal(&s)
if err != nil {
t.Fatalf("Marshal: %v", err)
}
if got := string(b); got != want {
t.Errorf("got %q, want %q", got, want)
}
}
/*
FIXME: disabling these test cases for now, because Sonic does not implement HTML escape
I don't think there are real usages of the `HTMLEscape` feature in real code
// C implements Marshaler and returns unescaped JSON.
type C int
func (C) MarshalJSON() ([]byte, error) {
return []byte(`"<&>"`), nil
}
// CText implements Marshaler and returns unescaped text.
type CText int
func (CText) MarshalText() ([]byte, error) {
return []byte(`"<&>"`), nil
}
func TestMarshalerEscaping(t *testing.T) {
var c C
want := `"\u003c\u0026\u003e"`
b, err := Marshal(c)
if err != nil {
t.Fatalf("Marshal(c): %v", err)
}
if got := string(b); got != want {
t.Errorf("Marshal(c) = %#q, want %#q", got, want)
}
var ct CText
want = `"\"\u003c\u0026\u003e\""`
b, err = Marshal(ct)
if err != nil {
t.Fatalf("Marshal(ct): %v", err)
}
if got := string(b); got != want {
t.Errorf("Marshal(ct) = %#q, want %#q", got, want)
}
}
*/
func TestAnonymousFields(t *testing.T) {
tests := []struct {
label string // Test name
makeInput func() interface{} // Function to create input value
want string // Expected JSON output
}{{
// Both S1 and S2 have a field named X. From the perspective of S,
// it is ambiguous which one X refers to.
// This should not serialize either field.
label: "AmbiguousField",
makeInput: func() interface{} {
type (
S1 struct{ x, X int }
S2 struct{ x, X int }
S struct {
S1
S2
}
)
return S{S1{1, 2}, S2{3, 4}}
},
want: `{}`,
}, {
label: "DominantField",
// Both S1 and S2 have a field named X, but since S has an X field as
// well, it takes precedence over S1.X and S2.X.
makeInput: func() interface{} {
type (
S1 struct{ x, X int }
S2 struct{ x, X int }
S struct {
S1
S2
x, X int
}
)
return S{S1{1, 2}, S2{3, 4}, 5, 6}
},
want: `{"X":6}`,
}, {
// Unexported embedded field of non-struct type should not be serialized.
label: "UnexportedEmbeddedInt",
makeInput: func() interface{} {
type (
myInt int
S struct{ myInt }
)
return S{5}
},
want: `{}`,
}, {
// Exported embedded field of non-struct type should be serialized.
label: "ExportedEmbeddedInt",
makeInput: func() interface{} {
type (
MyInt int
S struct{ MyInt }
)
return S{5}
},
want: `{"MyInt":5}`,
}, {
// Unexported embedded field of pointer to non-struct type
// should not be serialized.
label: "UnexportedEmbeddedIntPointer",
makeInput: func() interface{} {
type (
myInt int
S struct{ *myInt }
)
s := S{new(myInt)}
*s.myInt = 5
return s
},
want: `{}`,
}, {
// Exported embedded field of pointer to non-struct type
// should be serialized.
label: "ExportedEmbeddedIntPointer",
makeInput: func() interface{} {
type (
MyInt int
S struct{ *MyInt }
)
s := S{new(MyInt)}
*s.MyInt = 5
return s
},
want: `{"MyInt":5}`,
}, {
// Exported fields of embedded structs should have their
// exported fields be serialized regardless of whether the struct types
// themselves are exported.
label: "EmbeddedStruct",
makeInput: func() interface{} {
type (
s1 struct{ x, X int }
S2 struct{ y, Y int }
S struct {
s1
S2
}
)
return S{s1{1, 2}, S2{3, 4}}
},
want: `{"X":2,"Y":4}`,
}, {
// Exported fields of pointers to embedded structs should have their
// exported fields be serialized regardless of whether the struct types
// themselves are exported.
label: "EmbeddedStructPointer",
makeInput: func() interface{} {
type (
s1 struct{ x, X int }
S2 struct{ y, Y int }
S struct {
*s1
*S2
}
)
return S{&s1{1, 2}, &S2{3, 4}}
},
want: `{"X":2,"Y":4}`,
}, {
// Exported fields on embedded unexported structs at multiple levels
// of nesting should still be serialized.
label: "NestedStructAndInts",
makeInput: func() interface{} {
type (
MyInt1 int
MyInt2 int
myInt int
s2 struct {
MyInt2
myInt
}
s1 struct {
MyInt1
myInt
s2
}
S struct {
s1
myInt
}
)
return S{s1{1, 2, s2{3, 4}}, 6}
},
want: `{"MyInt1":1,"MyInt2":3}`,
}, {
// If an anonymous struct pointer field is nil, we should ignore
// the embedded fields behind it. Not properly doing so may
// result in the wrong output or reflect panics.
label: "EmbeddedFieldBehindNilPointer",
makeInput: func() interface{} {
type (
S2 struct{ Field string }
S struct{ *S2 }
)
return S{}
},
want: `{}`,
}}
for _, tt := range tests {
t.Run(tt.label, func(t *testing.T) {
b, err := Marshal(tt.makeInput())
if err != nil {
t.Fatalf("Marshal() = %v, want nil error", err)
}
if string(b) != tt.want {
t.Fatalf("Marshal() = %q, want %q", b, tt.want)
}
})
}
}
type BugA struct {
S string
}
type BugB struct {
BugA
S string
}
type BugC struct {
S string
}
// Legal Go: We never use the repeated embedded field (S).
type BugX struct {
A int
BugA
BugB
}
// golang.org/issue/16042.
// Even if a nil interface value is passed in, as long as
// it implements Marshaler, it should be marshaled.
type nilJSONMarshaler string
func (nm *nilJSONMarshaler) MarshalJSON() ([]byte, error) {
if nm == nil {
return Marshal("0zenil0")
}
return Marshal("zenil:" + string(*nm))
}
// golang.org/issue/34235.
// Even if a nil interface value is passed in, as long as
// it implements encoding.TextMarshaler, it should be marshaled.
type nilTextMarshaler string
func (nm *nilTextMarshaler) MarshalText() ([]byte, error) {
if nm == nil {
return []byte("0zenil0"), nil
}
return []byte("zenil:" + string(*nm)), nil
}
// See golang.org/issue/16042 and golang.org/issue/34235.
func TestNilMarshal(t *testing.T) {
testCases := []struct {
v interface{}
want string
}{
{v: nil, want: `null`},
{v: new(float64), want: `0`},
{v: []interface{}(nil), want: `null`},
{v: []string(nil), want: `null`},
{v: map[string]string(nil), want: `null`},
{v: []byte(nil), want: `null`},
{v: struct{ M string }{"gopher"}, want: `{"M":"gopher"}`},
{v: struct{ M json.Marshaler }{}, want: `{"M":null}`},
{v: struct{ M json.Marshaler }{(*nilJSONMarshaler)(nil)}, want: `{"M":"0zenil0"}`},
{v: struct{ M interface{} }{(*nilJSONMarshaler)(nil)}, want: `{"M":null}`},
{v: struct{ M encoding.TextMarshaler }{}, want: `{"M":null}`},
{v: struct{ M encoding.TextMarshaler }{(*nilTextMarshaler)(nil)}, want: `{"M":"0zenil0"}`},
{v: struct{ M interface{} }{(*nilTextMarshaler)(nil)}, want: `{"M":null}`},
}
for _, tt := range testCases {
out, err := Marshal(tt.v)
if err != nil || string(out) != tt.want {
t.Errorf("Marshal(%#v) = %#q, %#v, want %#q, nil", tt.v, out, err, tt.want)
continue
}
}
}
// Issue 5245.
func TestEmbeddedBug(t *testing.T) {
v := BugB{
BugA{"A"},
"B",
}
b, err := Marshal(v)
if err != nil {
t.Fatal("Marshal:", err)
}
want := `{"S":"B"}`
got := string(b)
if got != want {
t.Fatalf("Marshal: got %s want %s", got, want)
}
// Now check that the duplicate field, S, does not appear.
x := BugX{
A: 23,
}
b, err = Marshal(x)
if err != nil {
t.Fatal("Marshal:", err)
}
want = `{"A":23}`
got = string(b)
if got != want {
t.Fatalf("Marshal: got %s want %s", got, want)
}
}
type BugD struct { // Same as BugA after tagging.
XXX string `json:"S"`
}
// BugD's tagged S field should dominate BugA's.
type BugY struct {
BugA
BugD
}
// Test that a field with a tag dominates untagged fields.
func TestTaggedFieldDominates(t *testing.T) {
v := BugY{
BugA{"BugA"},
BugD{"BugD"},
}
b, err := Marshal(v)
if err != nil {
t.Fatal("Marshal:", err)
}
want := `{"S":"BugD"}`
got := string(b)
if got != want {
t.Fatalf("Marshal: got %s want %s", got, want)
}
}
// There are no tags here, so S should not appear.
type BugZ struct {
BugA
BugC
BugY // Contains a tagged S field through BugD; should not dominate.
}
func TestDuplicatedFieldDisappears(t *testing.T) {
v := BugZ{
BugA{"BugA"},
BugC{"BugC"},
BugY{
BugA{"nested BugA"},
BugD{"nested BugD"},
},
}
b, err := Marshal(v)
if err != nil {
t.Fatal("Marshal:", err)
}
want := `{}`
got := string(b)
if got != want {
t.Fatalf("Marshal: got %s want %s", got, want)
}
}
func TestStdLibIssue10281(t *testing.T) {
type Foo struct {
N json.Number
}
x := Foo{json.Number(`invalid`)}
b, err := Marshal(&x)
if err == nil {
t.Errorf("Marshal(&x) = %#q; want error", b)
}
}
// golang.org/issue/8582
func TestEncodePointerString(t *testing.T) {
type stringPointer struct {
N *int64 `json:"n,string"`
}
var n int64 = 42
b, err := Marshal(stringPointer{N: &n})
if err != nil {
t.Fatalf("Marshal: %v", err)
}
if got, want := string(b), `{"n":"42"}`; got != want {
t.Errorf("Marshal = %s, want %s", got, want)
}
var back stringPointer
err = Unmarshal(b, &back)
if err != nil {
t.Fatalf("Unmarshal: %v", err)
}
if back.N == nil {
t.Fatalf("Unmarshaled nil N field")
}
if *back.N != 42 {
t.Fatalf("*N = %d; want 42", *back.N)
}
}
var encodeStringTests = []struct {
in string
out string
}{
{"\x00", `"\u0000"`},
{"\x01", `"\u0001"`},
{"\x02", `"\u0002"`},
{"\x03", `"\u0003"`},
{"\x04", `"\u0004"`},
{"\x05", `"\u0005"`},
{"\x06", `"\u0006"`},
{"\x07", `"\u0007"`},
{"\x08", `"\b"`},
{"\x09", `"\t"`},
{"\x0a", `"\n"`},
{"\x0b", `"\u000b"`},
{"\x0c", `"\f"`},
{"\x0d", `"\r"`},
{"\x0e", `"\u000e"`},
{"\x0f", `"\u000f"`},
{"\x10", `"\u0010"`},
{"\x11", `"\u0011"`},
{"\x12", `"\u0012"`},
{"\x13", `"\u0013"`},
{"\x14", `"\u0014"`},
{"\x15", `"\u0015"`},
{"\x16", `"\u0016"`},
{"\x17", `"\u0017"`},
{"\x18", `"\u0018"`},
{"\x19", `"\u0019"`},
{"\x1a", `"\u001a"`},
{"\x1b", `"\u001b"`},
{"\x1c", `"\u001c"`},
{"\x1d", `"\u001d"`},
{"\x1e", `"\u001e"`},
{"\x1f", `"\u001f"`},
}
func TestEncodeString(t *testing.T) {
for _, tt := range encodeStringTests {
b, err := Marshal(tt.in)
if err != nil {
t.Errorf("Marshal(%q): %v", tt.in, err)
continue
}
out := string(b)
if out != tt.out {
t.Errorf("Marshal(%q) = %#q, want %#q", tt.in, out, tt.out)
}
}
}
type jsonbyte byte
func (b jsonbyte) MarshalJSON() ([]byte, error) { return tenc(`{"JB":%d}`, b) }
type textbyte byte
func (b textbyte) MarshalText() ([]byte, error) { return tenc(`TB:%d`, b) }
type jsonint int
func (i jsonint) MarshalJSON() ([]byte, error) { return tenc(`{"JI":%d}`, i) }
type textint int
func (i textint) MarshalText() ([]byte, error) { return tenc(`TI:%d`, i) }
func tenc(format string, a ...interface{}) ([]byte, error) {
var buf bytes.Buffer
_, _ = fmt.Fprintf(&buf, format, a...)
return buf.Bytes(), nil
}
// Issue 13783
func TestEncodeBytekind(t *testing.T) {
testdata := []struct {
data interface{}
want string
}{
{byte(7), "7"},
{jsonbyte(7), `{"JB":7}`},
{textbyte(4), `"TB:4"`},
{jsonint(5), `{"JI":5}`},
{textint(1), `"TI:1"`},
{[]byte{0, 1}, `"AAE="`},
{[]jsonbyte{0, 1}, `[{"JB":0},{"JB":1}]`},
{[][]jsonbyte{{0, 1}, {3}}, `[[{"JB":0},{"JB":1}],[{"JB":3}]]`},
{[]textbyte{2, 3}, `["TB:2","TB:3"]`},
{[]jsonint{5, 4}, `[{"JI":5},{"JI":4}]`},
{[]textint{9, 3}, `["TI:9","TI:3"]`},
{[]int{9, 3}, `[9,3]`},
}
for _, d := range testdata {
js, err := Marshal(d.data)
if err != nil {
t.Error(err)
continue
}
got, want := string(js), d.want
if got != want {
t.Errorf("got %s, want %s", got, want)
}
}
}
// https://golang.org/issue/33675
func TestNilMarshalerTextMapKey(t *testing.T) {
b, err := Marshal(map[*unmarshalerText]int{
(*unmarshalerText)(nil): 1,
})
if err != nil {
t.Fatalf("Failed to Marshal *text.Marshaler: %v", err)
}
const want = `{"":1}`
if string(b) != want {
t.Errorf("Marshal map with *text.Marshaler keys: got %#q, want %#q", b, want)
}
}
var re = regexp.MustCompile
// syntactic checks on form of marshaled floating point numbers.
var badFloatREs = []*regexp.Regexp{
re(`p`), // no binary exponential notation
re(`^\+`), // no leading + sign
re(`^-?0[^.]`), // no unnecessary leading zeros
re(`^-?\.`), // leading zero required before decimal point
re(`\.(e|$)`), // no trailing decimal
re(`\.[0-9]+0(e|$)`), // no trailing zero in fraction
re(`^-?(0|[0-9]{2,})\..*e`), // exponential notation must have normalized mantissa
re(`e[+-]0`), // exponent must not have leading zeros
re(`e-[1-6]$`), // not tiny enough for exponential notation
re(`e+(.|1.|20)$`), // not big enough for exponential notation
re(`^-?0\.0000000`), // too tiny, should use exponential notation
re(`^-?[0-9]{22}`), // too big, should use exponential notation
re(`[1-9][0-9]{16}[1-9]`), // too many significant digits in integer
re(`[1-9][0-9.]{17}[1-9]`), // too many significant digits in decimal
}
func TestMarshalFloat(t *testing.T) {
t.Parallel()
nfail := 0
test := func(f float64, bits int) {
vf := interface{}(f)
if bits == 32 {
f = float64(float32(f)) // round
vf = float32(f)
}
bout, err := Marshal(vf)
if err != nil {
t.Errorf("Marshal(%T(%g)): %v", vf, vf, err)
nfail++
return
}
out := string(bout)
// result must convert back to the same float
g, err := strconv.ParseFloat(out, bits)
if err != nil {
t.Errorf("Marshal(%T(%g)) = %q, cannot parse back: %v", vf, vf, out, err)
nfail++
return
}
if f != g {
t.Errorf("Marshal(%T(%g)) = %q (is %g, not %g)", vf, vf, out, float32(g), vf)
nfail++
return
}
for _, re := range badFloatREs {
if re.MatchString(out) {
t.Errorf("Marshal(%T(%g)) = %q, must not match /%s/", vf, vf, out, re)
nfail++
return
}
}
}
var (
bigger = math.Inf(+1)
smaller = math.Inf(-1)
)
var digits = "1.2345678901234567890123"
for i := len(digits); i >= 2; i-- {
if testing.Short() && i < len(digits)-4 {
break
}
for exp := -30; exp <= 30; exp++ {
for _, sign := range "+-" {
for bits := 32; bits <= 64; bits += 32 {
s := fmt.Sprintf("%c%se%d", sign, digits[:i], exp)
f, err := strconv.ParseFloat(s, bits)
if err != nil {
log.Fatal(err)
}
next := math.Nextafter
if bits == 32 {
next = func(g, h float64) float64 {
return float64(math.Nextafter32(float32(g), float32(h)))
}
}
test(f, bits)
test(next(f, bigger), bits)
test(next(f, smaller), bits)
if nfail > 50 {
t.Fatalf("stopping test early")
}
}
}
}
}
test(0, 64)
test(math.Copysign(0, -1), 64)
test(0, 32)
test(math.Copysign(0, -1), 32)
}
func TestMarshalRawMessageValue(t *testing.T) {
type (
T1 struct {
M json.RawMessage `json:",omitempty"`
}
T2 struct {
M *json.RawMessage `json:",omitempty"`
}
)
var (
rawNil = json.RawMessage(nil)
rawEmpty = json.RawMessage([]byte{})
rawText = json.RawMessage(`"foo"`)
)
tests := []struct {
in interface{}
want string
ok bool
}{
// Test with nil RawMessage.
{rawNil, "null", true},
{&rawNil, "null", true},
{[]interface{}{rawNil}, "[null]", true},
{&[]interface{}{rawNil}, "[null]", true},
{[]interface{}{&rawNil}, "[null]", true},
{&[]interface{}{&rawNil}, "[null]", true},
{struct{ M json.RawMessage }{rawNil}, `{"M":null}`, true},
{&struct{ M json.RawMessage }{rawNil}, `{"M":null}`, true},
{struct{ M *json.RawMessage }{&rawNil}, `{"M":null}`, true},
{&struct{ M *json.RawMessage }{&rawNil}, `{"M":null}`, true},
{map[string]interface{}{"M": rawNil}, `{"M":null}`, true},
{&map[string]interface{}{"M": rawNil}, `{"M":null}`, true},
{map[string]interface{}{"M": &rawNil}, `{"M":null}`, true},
{&map[string]interface{}{"M": &rawNil}, `{"M":null}`, true},
{T1{rawNil}, "{}", true},
{T2{&rawNil}, `{"M":null}`, true},
{&T1{rawNil}, "{}", true},
{&T2{&rawNil}, `{"M":null}`, true},
// Test with empty, but non-nil, RawMessage.
{rawEmpty, "", false},
{&rawEmpty, "", false},
{[]interface{}{rawEmpty}, "", false},
{&[]interface{}{rawEmpty}, "", false},
{[]interface{}{&rawEmpty}, "", false},
{&[]interface{}{&rawEmpty}, "", false},
{struct{ X json.RawMessage }{rawEmpty}, "", false},
{&struct{ X json.RawMessage }{rawEmpty}, "", false},
{struct{ X *json.RawMessage }{&rawEmpty}, "", false},
{&struct{ X *json.RawMessage }{&rawEmpty}, "", false},
{map[string]interface{}{"nil": rawEmpty}, "", false},
{&map[string]interface{}{"nil": rawEmpty}, "", false},
{map[string]interface{}{"nil": &rawEmpty}, "", false},
{&map[string]interface{}{"nil": &rawEmpty}, "", false},
{T1{rawEmpty}, "{}", true},
{T2{&rawEmpty}, "", false},
{&T1{rawEmpty}, "{}", true},
{&T2{&rawEmpty}, "", false},
// Test with RawMessage with some text.
//
// The tests below marked with Issue6458 used to generate "ImZvbyI=" instead "foo".
// This behavior was intentionally changed in Go 1.8.
// See https://golang.org/issues/14493#issuecomment-255857318
{rawText, `"foo"`, true}, // Issue6458
{&rawText, `"foo"`, true},
{[]interface{}{rawText}, `["foo"]`, true}, // Issue6458
{&[]interface{}{rawText}, `["foo"]`, true}, // Issue6458
{[]interface{}{&rawText}, `["foo"]`, true},
{&[]interface{}{&rawText}, `["foo"]`, true},
{struct{ M json.RawMessage }{rawText}, `{"M":"foo"}`, true}, // Issue6458
{&struct{ M json.RawMessage }{rawText}, `{"M":"foo"}`, true},
{struct{ M *json.RawMessage }{&rawText}, `{"M":"foo"}`, true},
{&struct{ M *json.RawMessage }{&rawText}, `{"M":"foo"}`, true},
{map[string]interface{}{"M": rawText}, `{"M":"foo"}`, true}, // Issue6458
{&map[string]interface{}{"M": rawText}, `{"M":"foo"}`, true}, // Issue6458
{map[string]interface{}{"M": &rawText}, `{"M":"foo"}`, true},
{&map[string]interface{}{"M": &rawText}, `{"M":"foo"}`, true},
{T1{rawText}, `{"M":"foo"}`, true}, // Issue6458
{T2{&rawText}, `{"M":"foo"}`, true},
{&T1{rawText}, `{"M":"foo"}`, true},
{&T2{&rawText}, `{"M":"foo"}`, true},
}
for i, tt := range tests {
b, err := Marshal(tt.in)
if ok := err == nil; ok != tt.ok {
if err != nil {
t.Errorf("test %d, unexpected failure: %v", i, err)
} else {
t.Errorf("test %d, unexpected success", i)
}
}
if got := string(b); got != tt.want {
t.Errorf("test %d, Marshal(%#v) = %q, want %q", i, tt.in, got, tt.want)
}
}
}
type marshalPanic struct{}
func (marshalPanic) MarshalJSON() ([]byte, error) { panic(0xdead) }
func TestMarshalPanic(t *testing.T) {
defer func() {
if got := recover(); !reflect.DeepEqual(got, 0xdead) {
t.Errorf("panic() = (%T)(%v), want 0xdead", got, got)
}
}()
_, _ = Marshal(&marshalPanic{})
t.Error("Marshal should have panicked")
}
//goland:noinspection NonAsciiCharacters
func TestMarshalUncommonFieldNames(t *testing.T) {
v := struct {
A0, À, Aβ int
}{}
b, err := Marshal(v)
if err != nil {
t.Fatal("Marshal:", err)
}
want := `{"A0":0,"À":0,"Aβ":0}`
got := string(b)
if got != want {
t.Fatalf("Marshal: got %s want %s", got, want)
}
}
type DummyMarshalerError struct {
Type reflect.Type
Err error
SourceFunc string
}
func (self *DummyMarshalerError) err() *json.MarshalerError {
return (*json.MarshalerError)(unsafe.Pointer(self))
}
func TestMarshalerError(t *testing.T) {
s := "test variable"
st := reflect.TypeOf(s)
errText := "json: test error"
tests := []struct {
err *json.MarshalerError
want string
}{
{
(&DummyMarshalerError{st, fmt.Errorf(errText), ""}).err(),
"json: error calling MarshalJSON for type " + st.String() + ": " + errText,
},
{
(&DummyMarshalerError{st, fmt.Errorf(errText), "TestMarshalerError"}).err(),
"json: error calling TestMarshalerError for type " + st.String() + ": " + errText,
},
}
for i, tt := range tests {
got := tt.err.Error()
if got != tt.want {
t.Errorf("MarshalerError test %d, got: %s, want: %s", i, got, tt.want)
}
}
}
| [
"\"SONIC_NO_ASYNC_GC\""
]
| []
| [
"SONIC_NO_ASYNC_GC"
]
| [] | ["SONIC_NO_ASYNC_GC"] | go | 1 | 0 | |
contracts/libc++/upstream/test/support/filesystem_dynamic_test_helper.py | import sys
import os
import stat
# Ensure that this is being run on a specific platform
assert sys.platform.startswith('linux') or sys.platform.startswith('darwin') \
or sys.platform.startswith('cygwin') or sys.platform.startswith('freebsd')
def env_path():
ep = os.environ.get('LIBCXX_FILESYSTEM_DYNAMIC_TEST_ROOT')
assert ep is not None
ep = os.path.realpath(ep)
assert os.path.isdir(ep)
return ep
env_path_global = env_path()
# Make sure we don't try and write outside of env_path.
# All paths used should be sanitized
def sanitize(p):
p = os.path.realpath(p)
if os.path.commonprefix([env_path_global, p]):
return p
assert False
"""
Some of the tests restrict permissions to induce failures.
Before we delete the test environment, we have to walk it and re-raise the
permissions.
"""
def clean_recursive(root_p):
if not os.path.islink(root_p):
os.chmod(root_p, 0o777)
for ent in os.listdir(root_p):
p = os.path.join(root_p, ent)
if os.path.islink(p) or not os.path.isdir(p):
os.remove(p)
else:
assert os.path.isdir(p)
clean_recursive(p)
os.rmdir(p)
def init_test_directory(root_p):
root_p = sanitize(root_p)
assert not os.path.exists(root_p)
os.makedirs(root_p)
def destroy_test_directory(root_p):
root_p = sanitize(root_p)
clean_recursive(root_p)
os.rmdir(root_p)
def create_file(fname, size):
with open(sanitize(fname), 'w') as f:
f.write('c' * size)
def create_dir(dname):
os.mkdir(sanitize(dname))
def create_symlink(source, link):
os.symlink(sanitize(source), sanitize(link))
def create_hardlink(source, link):
os.link(sanitize(source), sanitize(link))
def create_fifo(source):
os.mkfifo(sanitize(source))
def create_socket(source):
mode = 0o600 | stat.S_IFSOCK
os.mknod(sanitize(source), mode)
if __name__ == '__main__':
command = " ".join(sys.argv[1:])
eval(command)
sys.exit(0)
| []
| []
| [
"LIBCXX_FILESYSTEM_DYNAMIC_TEST_ROOT"
]
| [] | ["LIBCXX_FILESYSTEM_DYNAMIC_TEST_ROOT"] | python | 1 | 0 | |
manage.py | #!/usr/bin/env python
import os
import sys
from pathlib import Path
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django # noqa
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
# This allows easy placement of apps within the interior
# test_django_prod_in_gunicorn directory.
current_path = Path(__file__).parent.resolve()
sys.path.append(str(current_path / "test_django_prod_in_gunicorn"))
execute_from_command_line(sys.argv)
| []
| []
| []
| [] | [] | python | 0 | 0 | |
qa/rpc-tests/p2p-acceptblock.py | #!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.mininode import *
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
import time
from test_framework.blocktools import create_block, create_coinbase
'''
AcceptBlockTest -- test processing of unrequested blocks.
Since behavior differs when receiving unrequested blocks from whitelisted peers
versus non-whitelisted peers, this tests the behavior of both (effectively two
separate tests running in parallel).
Setup: two nodes, node0 and node1, not connected to each other. Node0 does not
whitelist localhost, but node1 does. They will each be on their own chain for
this test.
We have one NodeConn connection to each, test_node and white_node respectively.
The test:
1. Generate one block on each node, to leave IBD.
2. Mine a new block on each tip, and deliver to each node from node's peer.
The tip should advance.
3. Mine a block that forks the previous block, and deliver to each node from
corresponding peer.
Node0 should not process this block (just accept the header), because it is
unrequested and doesn't have more work than the tip.
Node1 should process because this is coming from a whitelisted peer.
4. Send another block that builds on the forking block.
Node0 should process this block but be stuck on the shorter chain, because
it's missing an intermediate block.
Node1 should reorg to this longer chain.
4b.Send 288 more blocks on the longer chain.
Node0 should process all but the last block (too far ahead in height).
Send all headers to Node1, and then send the last block in that chain.
Node1 should accept the block because it's coming from a whitelisted peer.
5. Send a duplicate of the block in #3 to Node0.
Node0 should not process the block because it is unrequested, and stay on
the shorter chain.
6. Send Node0 an inv for the height 3 block produced in #4 above.
Node0 should figure out that Node0 has the missing height 2 block and send a
getdata.
7. Send Node0 the missing block again.
Node0 should process and the tip should advance.
'''
# TestNode: bare-bones "peer". Used mostly as a conduit for a test to sending
# p2p messages to a node, generating the messages in the main testing logic.
class TestNode(NodeConnCB):
def __init__(self):
NodeConnCB.__init__(self)
self.connection = None
self.ping_counter = 1
self.last_pong = msg_pong()
def add_connection(self, conn):
self.connection = conn
# Track the last getdata message we receive (used in the test)
def on_getdata(self, conn, message):
self.last_getdata = message
# Spin until verack message is received from the node.
# We use this to signal that our test can begin. This
# is called from the testing thread, so it needs to acquire
# the global lock.
def wait_for_verack(self):
while True:
with mininode_lock:
if self.verack_received:
return
time.sleep(0.05)
# Wrapper for the NodeConn's send_message function
def send_message(self, message):
self.connection.send_message(message)
def on_pong(self, conn, message):
self.last_pong = message
# Sync up with the node after delivery of a block
def sync_with_ping(self, timeout=30):
self.connection.send_message(msg_ping(nonce=self.ping_counter))
received_pong = False
sleep_time = 0.05
while not received_pong and timeout > 0:
time.sleep(sleep_time)
timeout -= sleep_time
with mininode_lock:
if self.last_pong.nonce == self.ping_counter:
received_pong = True
self.ping_counter += 1
return received_pong
class AcceptBlockTest(BitcoinTestFramework):
def add_options(self, parser):
parser.add_option("--testbinary", dest="testbinary",
default=os.getenv("XCQD", "executecoind"),
help="bitcoind binary to test")
def __init__(self):
super().__init__()
self.setup_clean_chain = True
self.num_nodes = 2
def setup_network(self):
# Node0 will be used to test behavior of processing unrequested blocks
# from peers which are not whitelisted, while Node1 will be used for
# the whitelisted case.
self.nodes = []
self.nodes.append(start_node(0, self.options.tmpdir, ["-debug"],
binary=self.options.testbinary))
self.nodes.append(start_node(1, self.options.tmpdir,
["-debug", "-whitelist=127.0.0.1"],
binary=self.options.testbinary))
def run_test(self):
# Setup the p2p connections and start up the network thread.
test_node = TestNode() # connects to node0 (not whitelisted)
white_node = TestNode() # connects to node1 (whitelisted)
connections = []
connections.append(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node))
connections.append(NodeConn('127.0.0.1', p2p_port(1), self.nodes[1], white_node))
test_node.add_connection(connections[0])
white_node.add_connection(connections[1])
NetworkThread().start() # Start up network handling in another thread
# Test logic begins here
test_node.wait_for_verack()
white_node.wait_for_verack()
# 1. Have both nodes mine a block (leave IBD)
[ n.generate(1) for n in self.nodes ]
tips = [ int("0x" + n.getbestblockhash(), 0) for n in self.nodes ]
# 2. Send one block that builds on each tip.
# This should be accepted.
blocks_h2 = [] # the height 2 blocks on each node's chain
block_time = get_mocktime() + 1
for i in range(2):
blocks_h2.append(create_block(tips[i], create_coinbase(2), block_time + 1))
blocks_h2[i].solve()
block_time += 1
test_node.send_message(msg_block(blocks_h2[0]))
white_node.send_message(msg_block(blocks_h2[1]))
[ x.sync_with_ping() for x in [test_node, white_node] ]
assert_equal(self.nodes[0].getblockcount(), 2)
assert_equal(self.nodes[1].getblockcount(), 2)
print("First height 2 block accepted by both nodes")
# 3. Send another block that builds on the original tip.
blocks_h2f = [] # Blocks at height 2 that fork off the main chain
for i in range(2):
blocks_h2f.append(create_block(tips[i], create_coinbase(2), blocks_h2[i].nTime+1))
blocks_h2f[i].solve()
test_node.send_message(msg_block(blocks_h2f[0]))
white_node.send_message(msg_block(blocks_h2f[1]))
[ x.sync_with_ping() for x in [test_node, white_node] ]
for x in self.nodes[0].getchaintips():
if x['hash'] == blocks_h2f[0].hash:
assert_equal(x['status'], "headers-only")
for x in self.nodes[1].getchaintips():
if x['hash'] == blocks_h2f[1].hash:
assert_equal(x['status'], "valid-headers")
print("Second height 2 block accepted only from whitelisted peer")
# 4. Now send another block that builds on the forking chain.
blocks_h3 = []
for i in range(2):
blocks_h3.append(create_block(blocks_h2f[i].sha256, create_coinbase(3), blocks_h2f[i].nTime+1))
blocks_h3[i].solve()
test_node.send_message(msg_block(blocks_h3[0]))
white_node.send_message(msg_block(blocks_h3[1]))
[ x.sync_with_ping() for x in [test_node, white_node] ]
# Since the earlier block was not processed by node0, the new block
# can't be fully validated.
for x in self.nodes[0].getchaintips():
if x['hash'] == blocks_h3[0].hash:
assert_equal(x['status'], "headers-only")
# But this block should be accepted by node0 since it has more work.
try:
self.nodes[0].getblock(blocks_h3[0].hash)
print("Unrequested more-work block accepted from non-whitelisted peer")
except:
raise AssertionError("Unrequested more work block was not processed")
# Node1 should have accepted and reorged.
assert_equal(self.nodes[1].getblockcount(), 3)
print("Successfully reorged to length 3 chain from whitelisted peer")
# 4b. Now mine 288 more blocks and deliver; all should be processed but
# the last (height-too-high) on node0. Node1 should process the tip if
# we give it the headers chain leading to the tip.
tips = blocks_h3
headers_message = msg_headers()
all_blocks = [] # node0's blocks
for j in range(2):
for i in range(288):
next_block = create_block(tips[j].sha256, create_coinbase(i + 4), tips[j].nTime+1)
next_block.solve()
if j==0:
test_node.send_message(msg_block(next_block))
all_blocks.append(next_block)
else:
headers_message.headers.append(CBlockHeader(next_block))
tips[j] = next_block
set_mocktime(get_mocktime() + 2)
set_node_times(self.nodes, get_mocktime())
for x in all_blocks:
try:
self.nodes[0].getblock(x.hash)
if x == all_blocks[287]:
raise AssertionError("Unrequested block too far-ahead should have been ignored")
except:
if x == all_blocks[287]:
print("Unrequested block too far-ahead not processed")
else:
raise AssertionError("Unrequested block with more work should have been accepted")
headers_message.headers.pop() # Ensure the last block is unrequested
white_node.send_message(headers_message) # Send headers leading to tip
white_node.send_message(msg_block(tips[1])) # Now deliver the tip
try:
white_node.sync_with_ping()
self.nodes[1].getblock(tips[1].hash)
print("Unrequested block far ahead of tip accepted from whitelisted peer")
except:
raise AssertionError("Unrequested block from whitelisted peer not accepted")
# 5. Test handling of unrequested block on the node that didn't process
# Should still not be processed (even though it has a child that has more
# work).
test_node.send_message(msg_block(blocks_h2f[0]))
# Here, if the sleep is too short, the test could falsely succeed (if the
# node hasn't processed the block by the time the sleep returns, and then
# the node processes it and incorrectly advances the tip).
# But this would be caught later on, when we verify that an inv triggers
# a getdata request for this block.
test_node.sync_with_ping()
assert_equal(self.nodes[0].getblockcount(), 2)
print("Unrequested block that would complete more-work chain was ignored")
# 6. Try to get node to request the missing block.
# Poke the node with an inv for block at height 3 and see if that
# triggers a getdata on block 2 (it should if block 2 is missing).
with mininode_lock:
# Clear state so we can check the getdata request
test_node.last_getdata = None
test_node.send_message(msg_inv([CInv(2, blocks_h3[0].sha256)]))
test_node.sync_with_ping()
with mininode_lock:
getdata = test_node.last_getdata
# Check that the getdata includes the right block
assert_equal(getdata.inv[0].hash, blocks_h2f[0].sha256)
print("Inv at tip triggered getdata for unprocessed block")
# 7. Send the missing block for the third time (now it is requested)
test_node.send_message(msg_block(blocks_h2f[0]))
test_node.sync_with_ping()
assert_equal(self.nodes[0].getblockcount(), 290)
print("Successfully reorged to longer chain from non-whitelisted peer")
[ c.disconnect_node() for c in connections ]
if __name__ == '__main__':
AcceptBlockTest().main()
| []
| []
| [
"XCQD"
]
| [] | ["XCQD"] | python | 1 | 0 | |
test/functional/buildAndPackage/src/net/adoptium/test/VendorPropertiesTest.java | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.adoptium.test;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import static net.adoptium.test.JdkVersion.VM;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotEquals;
import static org.testng.Assert.assertTrue;
/**
* Tests whether vendor names and correct URLs appear in all the places they are supposed to.
*/
@Test(groups = {"level.extended"})
public class VendorPropertiesTest {
/**
* The checks for a given vendor.
*/
private final VmPropertiesChecks vendorChecks;
/**
* Class tells us what the jdk version and vm type is.
*/
private final JdkVersion jdkVersion = new JdkVersion();
/**
* Constructor method.
*/
public VendorPropertiesTest() {
Set<VmPropertiesChecks> allPropertiesChecks = new LinkedHashSet<>();
allPropertiesChecks.add(new AdoptiumPropertiesChecks());
allPropertiesChecks.add(new CorrettoPropertiesChecks());
// TODO: Somehow obtain the vendor name from the outside. Using any JVM properties is not a solution
// because that's what we want to test here.
String vendor = "Adoptium";
this.vendorChecks = allPropertiesChecks.stream()
.filter(checks -> checks.supports(vendor))
.findFirst()
.orElseThrow(() -> new AssertionError("No checks found for vendor: " + vendor));
}
/**
* Verifies that the vendor name is displayed within
* the java -version output, where applicable.
*/
@Test
public void javaVersionPrintsVendor() {
// Skip test on JDK8 for non-Hotspot JDKs.
if (!jdkVersion.isNewerOrEqual(9) && !jdkVersion.usesVM(VM.HOTSPOT)) {
return;
}
String testJdkHome = System.getenv("TEST_JDK_HOME");
if (testJdkHome == null) {
throw new AssertionError("TEST_JDK_HOME is not set");
}
List<String> command = new ArrayList<>();
command.add(String.format("%s/bin/java", testJdkHome));
command.add("-version");
try {
ProcessBuilder processBuilder = new ProcessBuilder(command);
Process process = processBuilder.start();
String stderr = StreamUtils.consumeStream(process.getErrorStream());
if (process.waitFor() != 0) {
throw new AssertionError("Could not run java -version");
}
this.vendorChecks.javaVersion(stderr);
} catch (InterruptedException | IOException e) {
throw new RuntimeException("Failed to launch JVM", e);
}
}
/**
* Test method that calls a number of other test methods
* themed around vendor-related property checks.
*/
@Test
public void vmPropertiesPointToVendor() {
this.vendorChecks.javaVendor(System.getProperty("java.vendor"));
this.vendorChecks.javaVendorUrl(System.getProperty("java.vendor.url"));
this.vendorChecks.javaVendorUrlBug(System.getProperty("java.vendor.url.bug"));
this.vendorChecks.javaVendorVersion(System.getProperty("java.vendor.version"));
this.vendorChecks.javaVmVendor(System.getProperty("java.vm.vendor"));
this.vendorChecks.javaVmVersion(System.getProperty("java.vm.version"));
}
private interface VmPropertiesChecks {
/**
* Tests whether the implementation of {@linkplain VmPropertiesChecks} is suitable to verify a JDK.
* @param vendor Name identifying the vendor.
* @return boolean result
*/
boolean supports(String vendor);
/**
* Checks whether the output of {@code java -version} is acceptable.
* @param value the value to be validated.
*/
void javaVersion(String value);
/**
* Checks the value of {@code java.vendor}.
* @param value the value to be validated.
*/
void javaVendor(String value);
/**
* Checks the value of {@code java.vendor.url}.
* @param value the value to be validated.
*/
void javaVendorUrl(String value);
/**
* Checks the value of {@code java.vendor.url.bug}.
* @param value the value to be validated.
*/
void javaVendorUrlBug(String value);
/**
* Checks the value of {@code java.vendor.version}.
* @param value the value to be validated.
*/
void javaVendorVersion(String value);
/**
* Checks the value of {@code java.vm.vendor}.
* @param value the value to be validated.
*/
void javaVmVendor(String value);
/**
* Checks the value of {@code java.vm.version}.
* @param value the value to be validated.
*/
void javaVmVersion(String value);
}
private static class AdoptiumPropertiesChecks implements VmPropertiesChecks {
@Override
public boolean supports(final String vendor) {
return vendor.toLowerCase(Locale.US).equals("eclipse foundation");
}
@Override
public void javaVersion(final String value) {
assertTrue(value.contains("Eclipse Foundation"));
}
@Override
public void javaVendor(final String value) {
assertEquals(value, "Eclipse Foundation");
}
@Override
public void javaVendorUrl(final String value) {
assertEquals(value, "https://adoptium.net/");
}
@Override
public void javaVendorUrlBug(final String value) {
assertEquals(value, "https://github.com/adoptium/adoptium-support/issues");
}
@Override
public void javaVendorVersion(final String value) {
assertNotEquals(value.replaceAll("[^0-9]", "").length(), 0,
"java.vendor.version contains no numbers: " + value);
}
@Override
public void javaVmVendor(final String value) {
assertTrue(value.equals("Adoptium") || value.equals("Eclipse OpenJ9"));
}
@Override
public void javaVmVersion(final String value) {
assertNotEquals(value.replaceAll("[^0-9]", "").length(), 0,
"java.vm.version contains no numbers: " + value);
}
}
private static class CorrettoPropertiesChecks implements VmPropertiesChecks {
@Override
public boolean supports(final String vendor) {
return vendor.toLowerCase(Locale.US).startsWith("amazon");
}
@Override
public void javaVersion(final String value) {
assertTrue(value.contains("Corretto"));
}
@Override
public void javaVendor(final String value) {
assertEquals(value, "Amazon.com Inc.");
}
@Override
public void javaVendorUrl(final String value) {
assertEquals(value, "https://aws.amazon.com/corretto/");
}
@Override
public void javaVendorUrlBug(final String value) {
assertTrue(value.startsWith("https://github.com/corretto/corretto"));
}
@Override
public void javaVendorVersion(final String value) {
assertTrue(value.startsWith("Corretto"));
assertNotEquals(value.replaceAll("[^0-9]", "").length(), 0,
"java.vendor.version contains no numbers: " + value);
}
@Override
public void javaVmVendor(final String value) {
assertEquals(value, "Amazon.com Inc.");
}
@Override
public void javaVmVersion(final String value) {
assertNotEquals(value.replaceAll("[^0-9]", "").length(), 0,
"java.vm.version contains no numbers: " + value);
}
}
}
| [
"\"TEST_JDK_HOME\""
]
| []
| [
"TEST_JDK_HOME"
]
| [] | ["TEST_JDK_HOME"] | java | 1 | 0 | |
kafkazk/zookeeper_integration_test.go | // +build integration
package kafkazk
import (
"bytes"
"compress/gzip"
"encoding/json"
"fmt"
"os"
"regexp"
"sort"
"testing"
"time"
zkclient "github.com/samuel/go-zookeeper/zk"
)
var (
zkaddr = "localhost:2181"
zkprefix = "/kafkazk_test"
)
var (
zkc *zkclient.Conn
zki Handler
// Paths to pre-populate.
paths = []string{
zkprefix,
zkprefix + "/brokers",
zkprefix + "/brokers/ids",
zkprefix + "/brokers/topics",
zkprefix + "/admin",
zkprefix + "/admin/reassign_partitions",
zkprefix + "/admin/delete_topics",
zkprefix + "/config",
zkprefix + "/config/topics",
zkprefix + "/config/brokers",
zkprefix + "/config/changes",
zkprefix + "/version",
// Topicmappr specific.
"/topicmappr_test",
"/topicmappr_test/brokermetrics",
"/topicmappr_test/partitionmeta",
}
)
// Sort by string length.
type byLen []string
func (a byLen) Len() int { return len(a) }
func (a byLen) Less(i, j int) bool { return len(a[i]) > len(a[j]) }
func (a byLen) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
// rawHandler is used for testing unexported ZKHandler
// methods that are not part of the Handler interface.
func rawHandler(c *Config) (*ZKHandler, error) {
z := &ZKHandler{
Connect: c.Connect,
Prefix: c.Prefix,
MetricsPrefix: c.MetricsPrefix,
}
var err error
z.client, _, err = zkclient.Connect([]string{z.Connect}, 10*time.Second, zkclient.WithLogInfo(false))
if err != nil {
return nil, err
}
return z, nil
}
// TestSetup is used for long tests that rely on a blank ZooKeeper
// server listening on localhost:2181. A direct ZooKeeper client
// is initialized to write test data into ZooKeeper that a Handler
// interface implementation may be tested against. Any Handler to be
// tested should also be instantiated here. A usable setup can be done
// with the official ZooKeeper docker image:
// - $ docker pull zookeeper
// - $ docker run --rm -d -p 2181:2181 zookeeper
// While the long tests perform a teardown, it's preferable to run the
// container with --rm and just using starting a new one for each test
// run. The removal logic in TestTearDown is quite rudimentary. If any
// steps fail, subsequent test runs will likely produce errors.
func TestSetup(t *testing.T) {
overrideZKAddr := os.Getenv("TEST_ZK_ADDR")
if overrideZKAddr != "" {
zkaddr = overrideZKAddr
}
// Init a direct client.
var err error
zkc, _, err = zkclient.Connect([]string{zkaddr}, time.Second, zkclient.WithLogInfo(false))
if err != nil {
t.Fatalf("Error initializing ZooKeeper client: %s", err)
}
// Init a ZooKeeper based Handler.
var configPrefix string
if len(zkprefix) > 0 {
configPrefix = zkprefix[1:]
} else {
configPrefix = ""
}
zki, err = NewHandler(&Config{
Connect: zkaddr,
Prefix: configPrefix,
MetricsPrefix: "topicmappr_test",
})
if err != nil {
t.Errorf("Error initializing ZooKeeper client: %s", err)
}
time.Sleep(250 * time.Millisecond)
if !zki.Ready() {
t.Fatal("ZooKeeper client not ready in 250ms")
}
/*****************
Populate test data
*****************/
// Create paths.
for _, p := range paths {
_, err := zkc.Create(p, []byte{}, 0, zkclient.WorldACL(31))
if err != nil {
t.Error(fmt.Sprintf("path %s: %s", p, err))
}
}
// Create topics.
partitionMeta := NewPartitionMetaMap()
data := []byte(`{"version":1,"partitions":{"0":[1001,1002],"1":[1002,1001],"2":[1003,1004],"3":[1004,1003]}}`)
for i := 0; i < 5; i++ {
// Init config.
topic := fmt.Sprintf("topic%d", i)
p := fmt.Sprintf("%s/brokers/topics/%s", zkprefix, topic)
_, err := zkc.Create(p, data, 0, zkclient.WorldACL(31))
if err != nil {
t.Error(err)
}
// Create partition meta.
partitionMeta[topic] = map[int]*PartitionMeta{
0: &PartitionMeta{Size: 1000.00},
1: &PartitionMeta{Size: 2000.00},
2: &PartitionMeta{Size: 3000.00},
3: &PartitionMeta{Size: 4000.00},
}
// Create topic configs, states.
statePaths := []string{
fmt.Sprintf("%s/brokers/topics/topic%d/partitions", zkprefix, i),
}
for j := 0; j < 4; j++ {
statePaths = append(statePaths, fmt.Sprintf("%s/brokers/topics/topic%d/partitions/%d", zkprefix, i, j))
statePaths = append(statePaths, fmt.Sprintf("%s/brokers/topics/topic%d/partitions/%d/state", zkprefix, i, j))
}
for _, p := range statePaths {
_, err := zkc.Create(p, []byte{}, 0, zkclient.WorldACL(31))
if err != nil {
t.Error(err)
}
}
config := `{"version":1,"partitions":{"0":[1001,1002], "1":[1002,1001], "2":[1003,1004], "3":[1004,1003]}}`
cfgPath := fmt.Sprintf("%s/brokers/topics/topic%d", zkprefix, i)
_, err = zkc.Set(cfgPath, []byte(config), -1)
if err != nil {
t.Error(err)
}
states := []string{
`{"controller_epoch":1,"leader":1001,"version":1,"leader_epoch":1,"isr":[1001,1002]}`,
`{"controller_epoch":1,"leader":1002,"version":1,"leader_epoch":1,"isr":[1002,1001]}`,
`{"controller_epoch":1,"leader":1003,"version":1,"leader_epoch":1,"isr":[1003,1004]}`,
`{"controller_epoch":1,"leader":1004,"version":1,"leader_epoch":1,"isr":[1004,1003]}`,
}
// We need at least one topic/partition to appear as under-replicated to
// test some functions.
if i == 2 {
states[0] = `{"controller_epoch":1,"leader":1002,"version":1,"leader_epoch":2,"isr":[1002]}`
}
for n, s := range states {
path := fmt.Sprintf("%s/brokers/topics/topic%d/partitions/%d/state", zkprefix, i, n)
_, err := zkc.Set(path, []byte(s), -1)
if err != nil {
t.Error(err)
}
}
}
// Store partition meta.
data, _ = json.Marshal(partitionMeta)
_, err = zkc.Set("/topicmappr_test/partitionmeta", data, -1)
if err != nil {
t.Error(err)
}
// Create reassignments data.
data = []byte(`{"version":1,"partitions":[{"topic":"topic0","partition":0,"replicas":[1003,1004]}]}`)
_, err = zkc.Set(zkprefix+"/admin/reassign_partitions", data, -1)
if err != nil {
t.Error(err)
}
// Create delete_topics data.
_, err = zkc.Create(zkprefix+"/admin/delete_topics/deleting_topic", []byte{}, 0, zkclient.WorldACL(31))
if err != nil {
t.Error(err)
}
// Create topic config.
data = []byte(`{"version":1,"config":{"retention.ms":"129600000"}}`)
_, err = zkc.Create(zkprefix+"/config/topics/topic0", data, 0, zkclient.WorldACL(31))
if err != nil {
t.Error(err)
}
// Create brokers.
rack := []string{"a", "b", "c"}
for i := 0; i < 5; i++ {
// Create data.
data := fmt.Sprintf(`{"listener_security_protocol_map":{"PLAINTEXT":"PLAINTEXT"},"endpoints":["PLAINTEXT://10.0.1.%d:9092"],"rack":"%s","jmx_port":9999,"host":"10.0.1.%d","timestamp":"%d","port":9092,"version":4}`,
100+i, rack[i%3], 100+i, time.Now().Unix())
p := fmt.Sprintf("%s/brokers/ids/%d", zkprefix, 1001+i)
// Add.
_, err = zkc.Create(p, []byte(data), 0, zkclient.WorldACL(31))
if err != nil {
t.Error(err)
}
}
// Create broker metrics.
if err := setBrokerMetrics(); err != nil {
t.Error(err)
}
}
func setBrokerMetrics() error {
data := []byte(`{
"1001": {"StorageFree": 10000.00},
"1002": {"StorageFree": 20000.00},
"1003": {"StorageFree": 30000.00},
"1004": {"StorageFree": 40000.00},
"1005": {"StorageFree": 50000.00}}`)
_, err := zkc.Set("/topicmappr_test/brokermetrics", data, -1)
return err
}
func TestCreateSetGetDelete(t *testing.T) {
err := zki.Create("/test", "")
if err != nil {
t.Error(err)
}
err = zki.Set("/test", "test data")
if err != nil {
t.Error(err)
}
v, err := zki.Get("/test")
if err != nil {
t.Error(err)
}
if string(v) != "test data" {
t.Errorf("Expected string 'test data', got '%s'", v)
}
err = zki.Delete("/test")
if err != nil {
t.Error(err)
}
_, err = zki.Get("/test")
switch err.(type) {
case ErrNoNode:
break
default:
t.Error("Expected ErrNoNode error")
}
}
func TestCreateSequential(t *testing.T) {
err := zki.Create(zkprefix+"/test", "")
if err != nil {
t.Error(err)
}
for i := 0; i < 3; i++ {
err = zki.CreateSequential(zkprefix+"/test/seq", "")
if err != nil {
t.Error(err)
}
}
c, _, err := zkc.Children(zkprefix + "/test")
if err != nil {
t.Error(err)
}
sort.Strings(c)
if len(c) != 3 {
t.Fatalf("Expected 3 znodes to be found, got %d", len(c))
}
expected := []string{
"seq0000000000",
"seq0000000001",
"seq0000000002",
}
for i, z := range c {
if z != expected[i] {
t.Errorf("Expected znode '%s', got '%s'", expected[i], z)
}
}
}
func TestExists(t *testing.T) {
e, err := zki.Exists(zkprefix)
if err != nil {
t.Error(err)
}
if !e {
t.Errorf("Expected path '%s' to exist", zkprefix)
}
}
func TestNextInt(t *testing.T) {
for _, expected := range []int32{1, 2, 3} {
v, err := zki.NextInt(zkprefix + "/version")
if err != nil {
t.Fatal(err)
}
if v != expected {
t.Errorf("Expected version value %d, got %d", expected, v)
}
}
}
func TestGetUnderReplicated(t *testing.T) {
ur, err := zki.GetUnderReplicated()
if err != nil {
t.Error(err)
}
if len(ur) != 1 || ur[0] != "topic2" {
t.Errorf("Expected 'topic2' in under replicated results, got '%s'", ur[0])
}
}
func TestGetReassignments(t *testing.T) {
re := zki.GetReassignments()
if len(re) != 1 {
t.Errorf("Expected 1 reassignment, got %d", len(re))
}
if _, exist := re["topic0"]; !exist {
t.Error("Expected 'topic0' in reassignments")
}
replicas, exist := re["topic0"][0]
if !exist {
t.Error("Expected topic0 partition 0 in reassignments")
}
sort.Ints(replicas)
expected := []int{1003, 1004}
for i, r := range replicas {
if r != expected[i] {
t.Errorf("Expected replica '%d', got '%d'", expected[i], r)
}
}
}
func TestGetPendingDeletion(t *testing.T) {
pd, err := zki.GetPendingDeletion()
if err != nil {
t.Error(err)
}
if len(pd) != 1 {
t.Fatalf("Expected 1 pending delete topic, got %d", len(pd))
}
if pd[0] != "deleting_topic" {
t.Errorf("Unexpected deleting topic name: %s", pd[0])
}
}
func TestGetTopics(t *testing.T) {
rs := []*regexp.Regexp{
regexp.MustCompile("topic[0-2]"),
}
ts, err := zki.GetTopics(rs)
if err != nil {
t.Error(err)
}
sort.Strings(ts)
expected := []string{"topic0", "topic1", "topic2"}
if len(ts) != 3 {
t.Errorf("Expected topic list len of 3, got %d", len(ts))
}
for i, n := range ts {
if n != expected[i] {
t.Errorf("Expected topic '%s', got '%s'", n, expected[i])
}
}
}
func TestGetTopicConfig(t *testing.T) {
c, err := zki.GetTopicConfig("topic0")
if err != nil {
t.Error(err)
}
if c == nil {
t.Error("Unexpectedly nil TopicConfig")
}
v, exist := c.Config["retention.ms"]
if !exist {
t.Error("Expected 'retention.ms' config key to exist")
}
if v != "129600000" {
t.Errorf("Expected config value '129600000', got '%s'", v)
}
}
func TestGetAllBrokerMeta(t *testing.T) {
bm, err := zki.GetAllBrokerMeta(false)
if err != nil {
t.Error(err)
}
if len(bm) != 5 {
t.Errorf("Expected BrokerMetaMap len of 5, got %d", len(bm))
}
expected := map[int]string{
1001: "a",
1002: "b",
1003: "c",
1004: "a",
1005: "b",
}
for b, r := range bm {
if r.Rack != expected[b] {
t.Errorf("Expected rack '%s' for %d, got '%s'", expected[b], b, r.Rack)
}
}
}
func TestGetBrokerMetrics(t *testing.T) {
// Get broker meta withMetrics.
bm, err := zki.GetAllBrokerMeta(true)
if err != nil {
t.Error(err)
}
expected := map[int]float64{
1001: 10000.00,
1002: 20000.00,
1003: 30000.00,
1004: 40000.00,
1005: 50000.00,
}
for b, v := range bm {
if v.StorageFree != expected[b] {
t.Errorf("Unexpected StorageFree metric for broker %d", b)
}
}
}
func TestGetBrokerMetricsCompressed(t *testing.T) {
// Create a compressed version of the metrics data.
data := []byte(`{
"1001": {"StorageFree": 10000.00},
"1002": {"StorageFree": 20000.00},
"1003": {"StorageFree": 30000.00},
"1004": {"StorageFree": 40000.00},
"1005": {"StorageFree": 50000.00}}`)
var buf bytes.Buffer
zw := gzip.NewWriter(&buf)
_, err := zw.Write(data)
if err != nil {
t.Error(err)
}
if err = zw.Close(); err != nil {
t.Error(err)
}
// Store the compressed version.
_, err = zkc.Set("/topicmappr_test/brokermetrics", buf.Bytes(), -1)
if err != nil {
t.Fatal(err)
}
// Test fetching the compressed version.
bm, errs := zki.GetAllBrokerMeta(true)
if errs != nil {
t.Error(err)
}
expected := map[int]float64{
1001: 10000.00,
1002: 20000.00,
1003: 30000.00,
1004: 40000.00,
1005: 50000.00,
}
for b, v := range bm {
if v.StorageFree != expected[b] {
t.Errorf("Unexpected StorageFree metric for broker %d", b)
}
}
// Rewrite the uncompressed version.
if err := setBrokerMetrics(); err != nil {
t.Error(err)
}
}
func TestGetAllPartitionMeta(t *testing.T) {
pm, err := zki.GetAllPartitionMeta()
if err != nil {
t.Error(err)
}
expected := map[int]float64{
0: 1000.00,
1: 2000.00,
2: 3000.00,
3: 4000.00,
}
for i := 0; i < 5; i++ {
topic := fmt.Sprintf("topic%d", i)
meta, exists := pm[topic]
if !exists {
t.Errorf("Expected topic '%s' in partition meta", topic)
}
for partn, m := range meta {
if m.Size != expected[partn] {
t.Errorf("Expected size %f for %s %d, got %f", expected[partn], topic, partn, m.Size)
}
}
}
}
func TestGetAllPartitionMetaCompressed(t *testing.T) {
// Fetch and hold the original partition meta.
pm, err := zki.GetAllPartitionMeta()
if err != nil {
t.Error(err)
}
pmOrig, _ := json.Marshal(pm)
// Create a compressed copy.
var buf bytes.Buffer
zw := gzip.NewWriter(&buf)
_, err = zw.Write(pmOrig)
if err != nil {
t.Error(err)
}
if err := zw.Close(); err != nil {
t.Error(err)
}
// Store the compressed copy.
_, err = zkc.Set("/topicmappr_test/partitionmeta", buf.Bytes(), -1)
if err != nil {
t.Error(err)
}
// Test fetching the compressed copy.
pm, err = zki.GetAllPartitionMeta()
if err != nil {
t.Error(err)
}
expected := map[int]float64{
0: 1000.00,
1: 2000.00,
2: 3000.00,
3: 4000.00,
}
for i := 0; i < 5; i++ {
topic := fmt.Sprintf("topic%d", i)
meta, exists := pm[topic]
if !exists {
t.Errorf("Expected topic '%s' in partition meta", topic)
}
for partn, m := range meta {
if m.Size != expected[partn] {
t.Errorf("Expected size %f for %s %d, got %f", expected[partn], topic, partn, m.Size)
}
}
}
// Reset to the original partitionMeta.
_, err = zkc.Set("/topicmappr_test/partitionmeta", pmOrig, -1)
if err != nil {
t.Error(err)
}
}
func TestOldestMetaTs(t *testing.T) {
// Init a ZKHandler.
var configPrefix string
if len(zkprefix) > 0 {
configPrefix = zkprefix[1:]
} else {
configPrefix = ""
}
zkr, err := rawHandler(&Config{
Connect: zkaddr,
Prefix: configPrefix,
MetricsPrefix: "topicmappr_test",
})
if err != nil {
t.Errorf("Error initializing ZooKeeper client: %s", err)
}
var m *zkclient.Stat
// Get the lowest Mtime value.
_, m, err = zkc.Get("/topicmappr_test/partitionmeta")
if err != nil {
t.Error(err)
}
ts1 := m.Mtime
_, m, err = zkc.Get("/topicmappr_test/brokermetrics")
if err != nil {
t.Error(err)
}
ts2 := m.Mtime
var min int64
if ts1 < ts2 {
min = ts1
} else {
min = ts2
}
// Get the ts.
expected := min * 1000000
age, err := zkr.oldestMetaTs()
if err != nil {
t.Error(err)
}
if age != expected {
t.Errorf("Expected meta ts of %d, got %d", expected, age)
}
}
func TestGetTopicState(t *testing.T) {
ts, err := zki.GetTopicState("topic0")
if err != nil {
t.Error(err)
}
if len(ts.Partitions) != 4 {
t.Errorf("Expected TopicState.Partitions len of 4, got %d", len(ts.Partitions))
}
expected := map[string][]int{
"0": []int{1001, 1002},
"1": []int{1002, 1001},
"2": []int{1003, 1004},
"3": []int{1004, 1003},
}
for p, rs := range ts.Partitions {
v, exists := expected[p]
if !exists {
t.Errorf("Expected partition %s in TopicState", p)
}
if len(rs) != len(v) {
t.Error("Unexpected replica set length")
}
for n := range rs {
if rs[n] != v[n] {
t.Errorf("Expected ID %d, got %d", v[n], rs[n])
}
}
}
}
func TestGetTopicStateISR(t *testing.T) {
ts, err := zki.GetTopicStateISR("topic0")
if err != nil {
t.Error(err)
}
if len(ts) != 4 {
t.Errorf("Expected TopicState.Partitions len of 4, got %d", len(ts))
}
expected := map[string][]int{
"0": []int{1001, 1002},
"1": []int{1002, 1001},
"2": []int{1003, 1004},
"3": []int{1004, 1003},
}
for p := range ts {
v, exists := expected[p]
if !exists {
t.Errorf("Expected partition %s in TopicState", p)
}
if len(ts[p].ISR) != len(v) {
t.Error("Unexpected replica set length")
}
for n := range ts[p].ISR {
if ts[p].ISR[n] != v[n] {
t.Errorf("Expected ID %d, got %d", v[n], ts[p].ISR[n])
}
}
}
}
func TestGetPartitionMap(t *testing.T) {
pm, err := zki.GetPartitionMap("topic0")
if err != nil {
t.Error(err)
}
expected := &PartitionMap{
Version: 1,
Partitions: PartitionList{
Partition{Topic: "topic0", Partition: 0, Replicas: []int{1003, 1004}}, // Via the stub reassign_partitions data.
Partition{Topic: "topic0", Partition: 1, Replicas: []int{1002, 1001}},
Partition{Topic: "topic0", Partition: 2, Replicas: []int{1003, 1004}},
Partition{Topic: "topic0", Partition: 3, Replicas: []int{1004, 1003}},
},
}
if matches, err := pm.Equal(expected); !matches {
t.Errorf("Unexpected PartitionMap inequality: %s", err)
}
}
func TestUpdateKafkaConfigBroker(t *testing.T) {
c := KafkaConfig{
Type: "broker",
Name: "1001",
Configs: []KafkaConfigKV{
KafkaConfigKV{"leader.replication.throttled.rate", "100000"},
KafkaConfigKV{"follower.replication.throttled.rate", "100000"},
},
}
_, err := zki.UpdateKafkaConfig(c)
if err != nil {
t.Error(err)
}
// Re-running the same config should
// be a no-op.
changes, err := zki.UpdateKafkaConfig(c)
if err != nil {
t.Error(err)
}
for _, change := range changes {
if change {
t.Error("Unexpected config update change status")
}
}
// Validate the config.
d, _, err := zkc.Get(zkprefix + "/config/changes/config_change_0000000000")
if err != nil {
t.Error(err)
}
expected := `{"version":2,"entity_path":"brokers/1001"}`
if string(d) != expected {
t.Errorf("Expected config '%s', got '%s'", expected, string(d))
}
d, _, err = zkc.Get(zkprefix + "/config/brokers/1001")
if err != nil {
t.Error(err)
}
expected = `{"version":1,"config":{"follower.replication.throttled.rate":"100000","leader.replication.throttled.rate":"100000"}}`
if string(d) != expected {
t.Errorf("Expected config '%s', got '%s'", expected, string(d))
}
}
func TestUpdateKafkaConfigTopic(t *testing.T) {
c := KafkaConfig{
Type: "topic",
Name: "topic0",
Configs: []KafkaConfigKV{
KafkaConfigKV{"leader.replication.throttled.replicas", "1003,1004"},
KafkaConfigKV{"follower.replication.throttled.replicas", "1003,1004"},
},
}
_, err := zki.UpdateKafkaConfig(c)
if err != nil {
t.Error(err)
}
// Re-running the same config should
// be a no-op.
changes, err := zki.UpdateKafkaConfig(c)
if err != nil {
t.Error(err)
}
for _, change := range changes {
if change {
t.Error("Unexpected config update change status")
}
}
// Validate the config.
d, _, err := zkc.Get(zkprefix + "/config/changes/config_change_0000000001")
if err != nil {
t.Error(err)
}
expected := `{"version":2,"entity_path":"topics/topic0"}`
if string(d) != expected {
t.Errorf("Expected config '%s', got '%s'", expected, string(d))
}
d, _, err = zkc.Get(zkprefix + "/config/topics/topic0")
if err != nil {
t.Error(err)
}
expected = `{"version":1,"config":{"follower.replication.throttled.replicas":"1003,1004","leader.replication.throttled.replicas":"1003,1004","retention.ms":"129600000"}}`
if string(d) != expected {
t.Errorf("Expected config '%s', got '%s'", expected, string(d))
}
}
// TestTearDown does any tear down cleanup.
func TestTearDown(t *testing.T) {
// Test data to be removed.
roots := []string{
zkprefix,
"/topicmappr_test",
}
var paths []string
for _, p := range roots {
paths = append(paths, allChildren(p)...)
}
sort.Sort(sort.Reverse(byLength(paths)))
for _, p := range paths {
_, s, err := zkc.Get(p)
if err != nil {
t.Log(p)
t.Error(err)
} else {
err = zkc.Delete(p, s.Version)
if err != nil {
t.Log(p)
t.Error(err)
}
}
}
zki.Close()
zkc.Close()
}
// Recursive search.
func allChildren(p string) []string {
paths := []string{p}
children, _, _ := zkc.Children(p)
for _, c := range children {
paths = append(paths, allChildren(fmt.Sprintf("%s/%s", p, c))...)
}
return paths
}
type byLength []string
func (s byLength) Len() int { return len(s) }
func (s byLength) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s byLength) Less(i, j int) bool { return len(s[i]) < len(s[j]) }
| [
"\"TEST_ZK_ADDR\""
]
| []
| [
"TEST_ZK_ADDR"
]
| [] | ["TEST_ZK_ADDR"] | go | 1 | 0 | |
cogs/info.py | from discord.ext import commands
import re
import discord
import random
import typing
import emoji
import unicodedata
import textwrap
import contextlib
import io
import asyncio
import async_tio
import itertools
import os
import base64
import secrets
import utils
from difflib import SequenceMatcher
from discord.ext.commands.cooldowns import BucketType
from jishaku.codeblocks import codeblock_converter
import functools
class Info(commands.Cog):
"Gives you Information about data you are allowed to access"
def __init__(self, bot):
self.bot = bot
@commands.command(
help="gives you info about a guild",
aliases=[
"server_info",
"guild_fetch",
"guild_info",
"fetch_guild",
"guildinfo",
],
)
async def serverinfo(self, ctx, *, guild: typing.Optional[discord.Guild] = None):
guild = guild or ctx.guild
if guild is None:
await ctx.send("Guild wanted has not been found")
if guild:
await utils.guildinfo(ctx, guild)
@commands.command(
aliases=["user_info", "user-info", "ui", "whois"],
brief="a command that gives information on users",
help="this can work with mentions, ids, usernames, and even full names.",
)
async def userinfo(self, ctx, *, user: utils.BetterUserconverter = None):
user = user or ctx.author
user_type = "Bot" if user.bot else "User" if isinstance(user, discord.User) else "Member"
statuses = []
badges = [utils.profile_converter("badges", f) for f in user.public_flags.all()] if user.public_flags else []
if user.bot:
badges.append(utils.profile_converter("badges", "bot"))
if user.system:
badges.append(utils.profile_converter("badges", "system"))
if isinstance(user, discord.Member):
nickname = user.nick
joined_guild = f"{discord.utils.format_dt(user.joined_at, style = 'd')}\n{discord.utils.format_dt(user.joined_at, style = 'T')}"
highest_role = user.top_role
for name, status in (
("Status", user.status),
("Desktop", user.desktop_status),
("Mobile", user.mobile_status),
("Web", user.web_status),
):
statuses.append((name, utils.profile_converter(name.lower(), status)))
else:
nickname = "None Found"
joined_guild = "N/A"
highest_role = "None Found"
member = discord.utils.find(lambda member: member.id == user.id, self.bot.get_all_members())
if member:
for name, status in (
("Status", member.status),
("Desktop", member.desktop_status),
("Mobile", member.mobile_status),
("Web", member.web_status),
):
statuses.append((name, utils.profile_converter(name.lower(), status)))
embed = discord.Embed(title=f"{user}", color=random.randint(0, 16777215), timestamp=ctx.message.created_at)
embed.add_field(
name="User Info: ",
value=f"**Username**: {user.name} \n**Discriminator**: {user.discriminator} \n**ID**: {user.id}",
inline=False,
)
join_badges: str = "\u0020".join(badges) if badges else "N/A"
join_statuses = (
" \n| ".join(f"**{name}**: {value}" for name, value in statuses) if statuses else "**Status**: \nUnknown"
)
embed.add_field(
name="User Info 2:",
value=f"Type: {user_type} \nBadges: {join_badges} \n**Joined Discord**: {discord.utils.format_dt(user.created_at, style = 'd')}\n{discord.utils.format_dt(user.created_at, style = 'T')}\n {join_statuses}",
inline=False,
)
embed.add_field(
name="Guild Info:",
value=f"**Joined Guild**: {joined_guild} \n**Nickname**: {nickname} \n**Highest Role:** {highest_role}",
inline=False,
)
embed.set_image(url=user.display_avatar.url)
guilds_list = utils.grab_mutualguilds(ctx, user)
pag = commands.Paginator(prefix="", suffix="")
for g in guilds_list:
pag.add_line(f"{g}")
pages = pag.pages or ["None"]
if ctx.author.dm_channel is None:
await ctx.author.create_dm()
menu = utils.MutualGuildsEmbed(pages, ctx=ctx, disable_after=True)
view = utils.UserInfoSuper(ctx, menu, ctx.author.dm_channel)
await ctx.send(
"Pick a way for Mutual Guilds to be sent to you or not if you really don't the mutualguilds",
embed=embed,
view=view,
)
@commands.command(brief="uploads your emojis into a Senarc Bin link")
async def look_at(self, ctx):
if isinstance(ctx.message.channel, discord.TextChannel):
message_emojis = ""
for x in ctx.guild.emojis:
message_emojis = message_emojis + " " + str(x) + "\n"
paste = await utils.post(self.bot, message_emojis)
await ctx.send(paste)
if isinstance(ctx.channel, discord.DMChannel):
await ctx.send("We can't use that in DMS as it takes emoji regex and puts it into a paste.")
@commands.command(help="gives the id of the current guild or DM if you are in one.")
async def guild_get(self, ctx):
if isinstance(ctx.channel, discord.TextChannel):
await ctx.send(content=ctx.guild.id)
if isinstance(ctx.channel, discord.DMChannel):
await ctx.send(ctx.channel.id)
@commands.command(brief="a command to tell you the channel id", aliases=["GetChannelId"])
async def this(self, ctx):
await ctx.send(ctx.channel.id)
@commands.command(brief="Gives you mention info don't abuse(doesn't mention tho)")
async def mention(self, ctx, *, user: utils.BetterUserconverter = None):
user = user or ctx.author
await ctx.send(
f"Discord Mention: {user.mention} \nRaw Mention: {discord.utils.escape_mentions(user.mention)}",
allowed_mentions=discord.AllowedMentions.none(),
)
@commands.cooldown(1, 30, BucketType.user)
@commands.command(help="fetch invite details")
async def fetch_invite(self, ctx, *invites: typing.Union[discord.Invite, str]):
if invites:
menu = utils.InviteInfoEmbed(invites, ctx=ctx, delete_after=True)
await menu.send()
if not invites:
await ctx.send("Please get actual invites to attempt grab")
ctx.command.reset_cooldown(ctx)
if len(invites) > 50:
await ctx.send(
"Reporting using more than 50 invites in this command. This is to prevent ratelimits with the api."
)
jdjg = await self.bot.try_user(168422909482762240)
await self.bot.get_channel(855217084710912050).send(
f"{jdjg.mention}.\n{ctx.author} causes a ratelimit issue with {len(invites)} invites"
)
@commands.command(brief="gives info about a file")
async def file(self, ctx):
if not ctx.message.attachments:
await ctx.send(ctx.message.attachments)
await ctx.send("no file submitted")
if ctx.message.attachments:
embed = discord.Embed(title="Attachment info", color=random.randint(0, 16777215))
for a in ctx.message.attachments:
embed.add_field(name=f"ID: {a.id}", value=f"[{a.filename}]({a.url})")
embed.set_footer(text="Check on the url/urls to get a direct download to the url.")
await ctx.send(embed=embed, content="\nThat's good")
@commands.command(
brief="a command to get the avatar of a user",
help="using the userinfo technology it now powers avatar grabbing.",
aliases=["pfp", "av"],
)
async def avatar(self, ctx, *, user: utils.BetterUserconverter = None):
user = user or ctx.author
embed = discord.Embed(color=random.randint(0, 16777215))
embed.set_author(name=f"{user.name}'s avatar:", icon_url=user.display_avatar.url)
embed.set_image(url=user.display_avatar.url)
embed.set_footer(text=f"Requested by {ctx.author}")
await ctx.send(embed=embed)
@commands.command(brief="this is a way to get the nearest channel.")
async def find_channel(self, ctx, *, args=None):
if args is None:
await ctx.send("Please specify a channel")
if args:
if isinstance(ctx.channel, discord.TextChannel):
channel = discord.utils.get(ctx.guild.channels, name=args)
if channel:
await ctx.send(channel.mention)
if channel is None:
await ctx.send("Unforantely we haven't found anything")
if isinstance(ctx.channel, discord.DMChannel):
await ctx.send("You can't use it in a DM.")
@commands.command(brief="a command to get the closest user.")
async def closest_user(self, ctx, *, args=None):
if args is None:
return await ctx.send("please specify a user")
if args and not self.bot.users:
return await ctx.send("There are no users cached :(")
if args:
userNearest = discord.utils.get(self.bot.users, name=args)
user_nick = discord.utils.get(self.bot.users, display_name=args)
if userNearest is None:
userNearest = sorted(self.bot.users, key=lambda x: SequenceMatcher(None, x.name, args).ratio())[-1]
if user_nick is None:
user_nick = sorted(self.bot.users, key=lambda x: SequenceMatcher(None, x.display_name, args).ratio())[
-1
]
if isinstance(ctx.channel, discord.TextChannel):
member_list = [x for x in ctx.guild.members if x.nick]
nearest_server_nick = sorted(member_list, key=lambda x: SequenceMatcher(None, x.nick, args).ratio())[-1]
if isinstance(ctx.channel, discord.DMChannel):
nearest_server_nick = "You unfortunately don't get the last value(a nickname) as it's a DM."
await ctx.send(f"Username : {userNearest} \nDisplay name : {user_nick} \nNickname: {nearest_server_nick}")
@commands.command(help="gives info on default emoji and custom emojis", name="emoji")
async def emoji_info(self, ctx, *emojis: typing.Union[utils.EmojiConverter, str]):
if emojis:
menu = utils.EmojiInfoEmbed(emojis, ctx=ctx, delete_after=True)
await menu.send()
if not emojis:
await ctx.send("Looks like there was no emojis.")
@commands.command(brief="gives info on emoji_id and emoji image.")
async def emoji_id(
self,
ctx,
*,
emoji: typing.Optional[typing.Union[discord.PartialEmoji, discord.Message, utils.EmojiBasic]] = None,
):
if isinstance(emoji, discord.Message):
emoji_message = emoji.content
emoji = None
with contextlib.suppress(commands.CommandError, commands.BadArgument):
emoji = await utils.EmojiBasic.convert(
ctx, emoji_message
) or await commands.PartialEmojiConverter().convert(ctx, emoji_message)
if emoji:
embed = discord.Embed(description=f" Emoji ID: {emoji.id}", color=random.randint(0, 16777215))
embed.set_image(url=emoji.url)
await ctx.send(embed=embed)
else:
await ctx.send("Not a valid emoji id.")
@commands.command()
async def fetch_content(self, ctx, *, args=None):
if args is None:
await ctx.send("please send actual text")
if args:
args = discord.utils.escape_mentions(args)
args = discord.utils.escape_markdown(args, as_needed=False, ignore_links=False)
for x in ctx.message.mentions:
args = args.replace(x.mention, f"\{x.mention}")
emojis = emoji.emoji_lis(args)
emojis_return = [d["emoji"] for d in emojis]
for x in emojis_return:
args = args.replace(x, f"\{x}")
for x in re.findall(r":\w*:\d*", args):
args = args.replace(x, f"\{x}")
await ctx.send(f"{args}", allowed_mentions=discord.AllowedMentions.none())
@commands.command(brief="gives info about a role.", aliases=["roleinfo"])
async def role_info(self, ctx, *, role: typing.Optional[discord.Role] = None):
if role:
await utils.roleinfo(ctx, role)
if not role:
await ctx.send(f"The role you wanted was not found.")
class DevTools(commands.Cog):
"Helpful commands for developers in general"
def __init__(self, bot):
self.bot = bot
async def rtfm_lookup(self, url=None, *, args=None):
if not args:
return url
else:
res = await self.bot.session.get(
"https://repi.openrobot.xyz/search_docs",
params={"query": args, "documentation": url},
headers={"Authorization": os.environ["frostiweeb_api"]},
)
results = await res.json()
if not results:
return f"Could not find anything with {args}."
else:
return results
async def rtfm_send(self, ctx, results):
if isinstance(results, str):
await ctx.send(results, allowed_mentions=discord.AllowedMentions.none())
else:
embed = discord.Embed(color=random.randint(0, 16777215))
results = dict(itertools.islice(results.items(), 10))
embed.description = "\n".join(f"[`{result}`]({results.get(result)})" for result in results)
reference = utils.reference(ctx.message)
await ctx.send(embed=embed, reference=reference)
@commands.command(
aliases=["rtd", "rtfs", "rtdm"],
invoke_without_command=True,
brief="a rtfm command that allows you to lookup at any library we support looking up(using selects)",
)
async def rtfm(self, ctx, *, args=None):
rtfm_dictionary = await self.bot.db.fetch("SELECT * FROM RTFM_DICTIONARY")
view = utils.RtfmChoice(ctx, rtfm_dictionary, timeout=15.0)
await ctx.send(content="Please Pick a library you want to parse", view=view)
await view.wait()
await ctx.trigger_typing()
results = await self.rtfm_lookup(url=view.value, args=args)
await self.rtfm_send(ctx, results)
def charinfo_converter(self, string):
digit = f"{ord(string):x}"
name = unicodedata.name(string, "The unicode was not found")
return f"`\\U{digit:>08}`: {name} - {string} \N{EM DASH} <http://www.fileformat.info/info/unicode/char/{digit}>"
@commands.command(brief="Gives you data about charinfo (based on R.danny's command)")
async def charinfo(self, ctx, *, args=None):
if not args:
return await ctx.send("That doesn't help out all :(")
values = "\n".join(map(self.charinfo_converter, set(args)))
content = textwrap.wrap(values, width=2000)
menu = utils.charinfoMenu(content, ctx=ctx, delete_after=True)
await menu.send()
@commands.command(brief="a command to view the rtfm DB")
async def rtfm_view(self, ctx):
rtfm_dictionary = dict(await self.bot.db.fetch("SELECT * FROM RTFM_DICTIONARY"))
pag = commands.Paginator(prefix="", suffix="")
for g in rtfm_dictionary:
pag.add_line(f"{g} : {rtfm_dictionary.get(g)}")
menu = utils.RtfmEmbed(pag.pages, ctx=ctx, delete_after=True)
await menu.send()
@commands.command(brief="a command to autoformat your python code to pep8")
async def pep8(self, ctx):
modal = utils.CodeBlockView(ctx, timeout=180.0)
message = await ctx.send(
"Please Submit the Code Block\nDo you want to use black's line formatter at 120 (i.e. black - l120 .), or just use the default? (i.e black .):",
view=modal,
)
await modal.wait()
if not modal.value:
return await ctx.reply("You need to give it code to work with it.", mention_author=False)
code = codeblock_converter(argument=f"{modal.value}")
if modal.value2 is None or modal.value2 is False:
await message.edit("Default it is.", view=None)
if modal.value is True:
await message.edit("Speacil Formatting at 120 lines it is.")
code_conversion = functools.partial(utils.formatter, code.content, bool(modal.value))
try:
code = await self.bot.loop.run_in_executor(None, code_conversion)
except Exception as e:
return await message.edit(f"Error Ocurred with {e}")
embed = discord.Embed(
title="Reformatted with Black",
description=f"code returned: \n```python\n{code}```",
color=random.randint(0, 16777215),
)
embed.set_footer(text="Make sure you use python code, otherwise it will not work properly.")
await message.edit(embed=embed)
@commands.command(brief="grabs your pfp's image")
async def pfp_grab(self, ctx):
if_animated = ctx.author.display_avatar.is_animated()
save_type = ".gif" if if_animated else ".png"
icon_file = await ctx.author.display_avatar.read()
buffer = io.BytesIO(icon_file)
buffer.seek(0)
# print(len(buffer.getvalue()))
file = discord.File(buffer, filename=f"pfp{save_type}")
try:
await ctx.send(content="here's your avatar:", file=file)
except:
await ctx.send("it looks like it couldn't send the pfp due to the file size.")
@commands.command(brief="Gives info on pypi packages")
async def pypi(self, ctx, *, args=None):
# https://pypi.org/simple/
if args:
pypi_response = await self.bot.session.get(f"https://pypi.org/pypi/{args}/json")
if pypi_response.ok:
pypi_response = await pypi_response.json()
pypi_data = pypi_response["info"]
embed = discord.Embed(
title=f"{pypi_data.get('name') or 'None provided'} {pypi_data.get('version') or 'None provided'}",
url=f"{pypi_data.get('release_url') or 'None provided'}",
description=f"{pypi_data.get('summary') or 'None provided'}",
color=random.randint(0, 16777215),
)
embed.set_thumbnail(url="https://i.imgur.com/oP0e7jK.png")
embed.add_field(
name="**Author Info**",
value=f"**Author Name:** {pypi_data.get('author') or 'None provided'}\n**Author Email:** {pypi_data.get('author_email') or 'None provided'}",
inline=False,
)
embed.add_field(
name="**Package Info**",
value=f"**Download URL**: {pypi_data.get('download_url') or 'None provided'}\n**Documentation URL:** {pypi_data.get('docs_url') or 'None provided'}\n**Home Page:** {pypi_data.get('home_page') or 'None provided'}\n**Keywords:** {pypi_data.get('keywords') or 'None provided'}\n**License:** {pypi_data.get('license') or 'None provided'}",
inline=False,
)
await ctx.send(embed=embed)
else:
await ctx.send(
f"Could not find package **{args}** on pypi.", allowed_mentions=discord.AllowedMentions.none()
)
else:
await ctx.send("Please look for a library to get the info of.")
@commands.command(brief="make a quick bot invite with 0 perms")
async def invite_bot(self, ctx, *, user: typing.Optional[discord.User] = None):
user = user or ctx.author
if not user.bot:
return await ctx.send("That's not a legit bot")
invite = discord.utils.oauth_url(client_id=user.id, scopes=("bot",))
slash_invite = discord.utils.oauth_url(client_id=user.id)
view = discord.ui.View()
view.add_item(
discord.ui.Button(label=f"{user.name}'s Normal Invite", url=invite, style=discord.ButtonStyle.link)
)
view.add_item(
discord.ui.Button(
label=f"{user.name}'s Invite With Slash Commands", url=slash_invite, style=discord.ButtonStyle.link
)
)
await ctx.send(f"Invite with slash commands and the bot scope or only with a bot scope:", view=view)
@commands.command(brief="gets you a guild's icon", aliases=["guild_icon"])
async def server_icon(self, ctx, *, guild: typing.Optional[discord.Guild] = None):
guild = guild or ctx.guild
if not guild:
return await ctx.send("no guild to get the icon of.")
await ctx.send(f"{guild.icon.url if guild.icon else 'No Url for This Guild, I am sorry dude :('}")
@commands.command(brief="some old fooz command..")
async def fooz(self, ctx, *, args=None):
if not args:
await ctx.send("success")
if args:
await ctx.send("didn't use it properly :(")
@commands.command(brief="puts the message time as a timestamp")
async def message_time(self, ctx):
embed = discord.Embed(title="Message Time", color=random.randint(0, 16777215), timestamp=ctx.message.created_at)
embed.set_footer(text=f"{ctx.message.id}")
await ctx.send(content=f"Only here cause JDJG Bot has it and why not have it here now.", embed=embed)
@commands.command(brief="converts info about colors for you.", invoke_without_command=True)
async def color(self, ctx, *, color: utils.ColorConverter = None):
if not color:
return await ctx.send("you need to give me a color to use.")
await ctx.send(f"Hexadecimal: {color} \nValue : {color.value} \nRGB: {color.to_rgb()}")
@commands.command(brief="a command that tells a user creation time.")
async def created_at(self, ctx, *, user: utils.BetterUserconverter = None):
user = user or ctx.author
creation_info = f"{discord.utils.format_dt(user.created_at, style = 'd')}\n{discord.utils.format_dt(user.created_at, style = 'T')}"
await ctx.send(
f"\nName : {user}\nMention : {user.mention} was created:\n{creation_info}\nRaw Version: ```{creation_info}```",
allowed_mentions=discord.AllowedMentions.none(),
)
@commands.command(brief="a command that makes a fake user id based on the current time.")
async def fake_user_id(self, ctx):
await ctx.send(f"User id: {utils.generate_snowflake()}")
@commands.command(brief="gives information on snowflakes")
async def snowflake_info(self, ctx, *, snowflake: typing.Optional[utils.ObjectPlus] = None):
if not snowflake:
await ctx.send(
"you either returned nothing or an invalid snowflake now going to the current time for information."
)
# change objectplus convert back to the before(discord.Object), same thing with utls.ObjectPlus, if edpy adds my pull request into the master.
generated_time = await utils.ObjectPlusConverter().convert(ctx, argument=f"{int(utils.generate_snowflake())}")
snowflake = snowflake or generated_time
embed = discord.Embed(title="❄️ SnowFlake Info:", color=5793266)
embed.add_field(
name="Created At:",
value=f"{discord.utils.format_dt(snowflake.created_at, style = 'd')}\n{discord.utils.format_dt(snowflake.created_at, style = 'T')}",
)
embed.add_field(name="Worker ID:", value=f"{snowflake.worker_id}")
embed.add_field(name="Process ID:", value=f"{snowflake.process_id}")
embed.add_field(name="Increment:", value=f"{snowflake.increment_id}")
embed.set_footer(text=f"Snowflake ID: {snowflake.id}")
await ctx.send(embed=embed)
@commands.command(brief="Generates a fake token from the current time")
async def fake_token(self, ctx):
object = discord.Object(utils.generate_snowflake())
first_encoded = base64.b64encode(f"{object.id}".encode())
first_bit = first_encoded.decode()
timestamp = int(object.created_at.timestamp() - 129384000)
d = timestamp.to_bytes(4, "big")
second_bit_encoded = base64.standard_b64encode(d)
second_bit = second_bit_encoded.decode().rstrip("==")
last_bit = secrets.token_urlsafe(20)
embed = discord.Embed(
title=f"Newly Generated Fake Token",
description=f"ID: ``{object.id}``\nCreated at : \n{discord.utils.format_dt(object.created_at, style = 'd')}\n{discord.utils.format_dt(object.created_at, style = 'T')}",
)
embed.add_field(name="Generated Token:", value=f"``{first_bit}.{second_bit}.{last_bit}``")
embed.set_thumbnail(url=ctx.author.display_avatar.url)
embed.set_footer(text=f"Requested by {ctx.author}")
await ctx.send("We generated a fake token :clap::", embed=embed)
@commands.cooldown(1, 60, BucketType.user)
@commands.command(brief="makes a request to add a bot to the test guild")
async def addbot(self, ctx, *, user: typing.Optional[discord.User] = None):
user = user or ctx.author
if not user.bot:
ctx.command.reset_cooldown(ctx)
return await ctx.send("Please Use A **Bot** ID, not a **User** ID.")
modal = utils.AddBotView(ctx, timeout=180.0)
message = await ctx.send("Please Tell us the reason you want to add your bot to the Test Guild:", view=modal)
await modal.wait()
if modal.value is None:
ctx.command.reset_cooldown(ctx)
return await message.edit("Provide a reason why you want your bot added to your guild")
guild = self.bot.get_guild(438848185008390158)
member = await self.bot.try_member(guild, ctx.author.id)
if member is None:
view = discord.ui.View()
view.add_item(
discord.ui.Button(
label=f"Test Guild Invite",
url="https://discord.gg/hKn8qgCDzK",
style=discord.ButtonStyle.link,
row=1,
)
)
return await message.edit(
"Make sure to join the guild linked soon... then rerun the command. If you are in the guild contact the owner(the owner is listed in the owner command)",
view=view,
)
embed = discord.Embed(
title="Bot Request",
colour=discord.Colour.blurple(),
description=f"reason: \n{modal.value}\n\n[Invite URL]({discord.utils.oauth_url(client_id = user.id, scopes=('bot',))})",
timestamp=ctx.message.created_at,
)
embed.add_field(name="Author", value=f"{ctx.author} (ID: {ctx.author.id})", inline=False)
embed.add_field(name="Bot", value=f"{user} (ID: {user.id})", inline=False)
embed.set_footer(text=ctx.author.id)
embed.set_author(name=user.id, icon_url=user.display_avatar.with_format("png"))
jdjg = self.bot.get_user(168422909482762240)
benitz = self.bot.get_user(529499034495483926)
await self.bot.get_channel(816807453215424573).send(content=f"{jdjg.mention} {benitz.mention}", embed=embed)
await ctx.reply(
f"It appears adding your bot worked. \nIf you leave your bot will be kicked, unless you have an alt there, a friend, etc. \n(It will be kicked to prevent raiding and taking up guild space if you leave). \nYour bot will be checked out. {jdjg} will then determine if your bot is good to add to the guild. Make sure to open your Dms to JDJG, so he can dm you about the bot being added. \nIf you don't add him, your bot will be denied."
)
@commands.command(
brief="a command that takes a url and sees if it's an image (requires embed permissions at the moment)."
)
async def image_check(self, ctx):
await ctx.send(
"Please wait for discord to edit your message, if it does error about not a valid image, please send a screenshot of your usage and the bot's message."
)
await asyncio.sleep(5)
images = list(filter(lambda e: e.type == "image", ctx.message.embeds))
if not images or not ctx.message.embeds:
return await ctx.send(
"you need to pass a url with an image, if you did, then please run again. This is a discord issue, and I do not want to wait for discord to change its message."
)
await ctx.send(f"You have {len(images)} / {len(ctx.message.embeds)} links that are valid images.")
@commands.command(brief="Gives info on npm packages")
async def npm(self, ctx, *, args=None):
if args:
npm_response = await self.bot.session.get(f"https://registry.npmjs.com/{args}")
if npm_response.ok:
npm_response = await npm_response.json()
data = utils.get_required_npm(npm_response)
await ctx.send(embed=utils.npm_create_embed(data))
else:
await ctx.send(
f"Could not find package **{args}** on npm.", allowed_mentions=discord.AllowedMentions.none()
)
else:
await ctx.send("Please look for a library to get the info of.")
@commands.cooldown(1, 30, BucketType.user)
@commands.command(
brief="runs some code in a sandbox(based on Soos's Run command)", aliases=["eval", "run", "sandbox"]
)
async def console(self, ctx, *, code: codeblock_converter = None):
if not code:
return await ctx.send("You need to give me some code to use, otherwise I can not determine what it is.")
if not code.language:
return await ctx.send("You Must provide a language to use")
if not code.content:
return await ctx.send("No code provided")
tio = await async_tio.Tio(session=self.bot.session)
output = await tio.execute(f"{code.content}", language=f"{code.language}")
text_returned = (
f"```{code.language}\n{output}```"
if len(f"{output}") < 200
else await utils.post(self.bot, code=f"{output}")
)
embed = discord.Embed(
title=f"Your code exited with code {output.exit_status}", description=f"{text_returned}", color=242424
)
embed.set_author(name=f"{ctx.author}", icon_url=ctx.author.display_avatar.url)
embed.set_footer(text="Powered by Tio.run")
await ctx.send(content="I executed your code in a sandbox", embed=embed)
async def setup(bot):
await bot.add_cog(Info(bot))
await bot.add_cog(DevTools(bot))
| []
| []
| [
"frostiweeb_api"
]
| [] | ["frostiweeb_api"] | python | 1 | 0 | |
python/pyspark/sql/readwriter.py | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import sys
if sys.version >= '3':
basestring = unicode = str
from py4j.java_gateway import JavaClass
from pyspark import RDD, since, keyword_only
from pyspark.rdd import ignore_unicode_prefix
from pyspark.sql.column import _to_seq
from pyspark.sql.types import *
from pyspark.sql import utils
__all__ = ["DataFrameReader", "DataFrameWriter"]
def to_str(value):
"""
A wrapper over str(), but converts bool values to lower case strings.
If None is given, just returns None, instead of converting it to string "None".
"""
if isinstance(value, bool):
return str(value).lower()
elif value is None:
return value
else:
return str(value)
class OptionUtils(object):
def _set_opts(self, schema=None, **options):
"""
Set named options (filter out those the value is None)
"""
if schema is not None:
self.schema(schema)
for k, v in options.items():
if v is not None:
self.option(k, v)
class DataFrameReader(OptionUtils):
"""
Interface used to load a :class:`DataFrame` from external storage systems
(e.g. file systems, key-value stores, etc). Use :func:`spark.read`
to access this.
.. versionadded:: 1.4
"""
def __init__(self, spark):
self._jreader = spark._ssql_ctx.read()
self._spark = spark
def _df(self, jdf):
from pyspark.sql.dataframe import DataFrame
return DataFrame(jdf, self._spark)
@since(1.4)
def format(self, source):
"""Specifies the input data source format.
:param source: string, name of the data source, e.g. 'json', 'parquet'.
>>> df = spark.read.format('json').load('python/test_support/sql/people.json')
>>> df.dtypes
[('age', 'bigint'), ('name', 'string')]
"""
self._jreader = self._jreader.format(source)
return self
@since(1.4)
def schema(self, schema):
"""Specifies the input schema.
Some data sources (e.g. JSON) can infer the input schema automatically from data.
By specifying the schema here, the underlying data source can skip the schema
inference step, and thus speed up data loading.
:param schema: a StructType object
"""
if not isinstance(schema, StructType):
raise TypeError("schema should be StructType")
jschema = self._spark._ssql_ctx.parseDataType(schema.json())
self._jreader = self._jreader.schema(jschema)
return self
@since(1.5)
def option(self, key, value):
"""Adds an input option for the underlying data source.
"""
self._jreader = self._jreader.option(key, to_str(value))
return self
@since(1.4)
def options(self, **options):
"""Adds input options for the underlying data source.
"""
for k in options:
self._jreader = self._jreader.option(k, to_str(options[k]))
return self
@since(1.4)
def load(self, path=None, format=None, schema=None, **options):
"""Loads data from a data source and returns it as a :class`DataFrame`.
:param path: optional string or a list of string for file-system backed data sources.
:param format: optional string for format of the data source. Default to 'parquet'.
:param schema: optional :class:`StructType` for the input schema.
:param options: all other string options
>>> df = spark.read.load('python/test_support/sql/parquet_partitioned', opt1=True,
... opt2=1, opt3='str')
>>> df.dtypes
[('name', 'string'), ('year', 'int'), ('month', 'int'), ('day', 'int')]
>>> df = spark.read.format('json').load(['python/test_support/sql/people.json',
... 'python/test_support/sql/people1.json'])
>>> df.dtypes
[('age', 'bigint'), ('aka', 'string'), ('name', 'string')]
"""
if format is not None:
self.format(format)
if schema is not None:
self.schema(schema)
self.options(**options)
if isinstance(path, basestring):
return self._df(self._jreader.load(path))
elif path is not None:
if type(path) != list:
path = [path]
return self._df(self._jreader.load(self._spark._sc._jvm.PythonUtils.toSeq(path)))
else:
return self._df(self._jreader.load())
@since(1.4)
def json(self, path, schema=None, primitivesAsString=None, prefersDecimal=None,
allowComments=None, allowUnquotedFieldNames=None, allowSingleQuotes=None,
allowNumericLeadingZero=None, allowBackslashEscapingAnyCharacter=None,
mode=None, columnNameOfCorruptRecord=None):
"""
Loads a JSON file (one object per line) or an RDD of Strings storing JSON objects
(one object per record) and returns the result as a :class`DataFrame`.
If the ``schema`` parameter is not specified, this function goes
through the input once to determine the input schema.
:param path: string represents path to the JSON dataset,
or RDD of Strings storing JSON objects.
:param schema: an optional :class:`StructType` for the input schema.
:param primitivesAsString: infers all primitive values as a string type. If None is set,
it uses the default value, ``false``.
:param prefersDecimal: infers all floating-point values as a decimal type. If the values
do not fit in decimal, then it infers them as doubles. If None is
set, it uses the default value, ``false``.
:param allowComments: ignores Java/C++ style comment in JSON records. If None is set,
it uses the default value, ``false``.
:param allowUnquotedFieldNames: allows unquoted JSON field names. If None is set,
it uses the default value, ``false``.
:param allowSingleQuotes: allows single quotes in addition to double quotes. If None is
set, it uses the default value, ``true``.
:param allowNumericLeadingZero: allows leading zeros in numbers (e.g. 00012). If None is
set, it uses the default value, ``false``.
:param allowBackslashEscapingAnyCharacter: allows accepting quoting of all character
using backslash quoting mechanism. If None is
set, it uses the default value, ``false``.
:param mode: allows a mode for dealing with corrupt records during parsing. If None is
set, it uses the default value, ``PERMISSIVE``.
* ``PERMISSIVE`` : sets other fields to ``null`` when it meets a corrupted \
record and puts the malformed string into a new field configured by \
``columnNameOfCorruptRecord``. When a schema is set by user, it sets \
``null`` for extra fields.
* ``DROPMALFORMED`` : ignores the whole corrupted records.
* ``FAILFAST`` : throws an exception when it meets corrupted records.
:param columnNameOfCorruptRecord: allows renaming the new field having malformed string
created by ``PERMISSIVE`` mode. This overrides
``spark.sql.columnNameOfCorruptRecord``. If None is set,
it uses the value specified in
``spark.sql.columnNameOfCorruptRecord``.
>>> df1 = spark.read.json('python/test_support/sql/people.json')
>>> df1.dtypes
[('age', 'bigint'), ('name', 'string')]
>>> rdd = sc.textFile('python/test_support/sql/people.json')
>>> df2 = spark.read.json(rdd)
>>> df2.dtypes
[('age', 'bigint'), ('name', 'string')]
"""
self._set_opts(
schema=schema, primitivesAsString=primitivesAsString, prefersDecimal=prefersDecimal,
allowComments=allowComments, allowUnquotedFieldNames=allowUnquotedFieldNames,
allowSingleQuotes=allowSingleQuotes, allowNumericLeadingZero=allowNumericLeadingZero,
allowBackslashEscapingAnyCharacter=allowBackslashEscapingAnyCharacter,
mode=mode, columnNameOfCorruptRecord=columnNameOfCorruptRecord)
if isinstance(path, basestring):
path = [path]
if type(path) == list:
return self._df(self._jreader.json(self._spark._sc._jvm.PythonUtils.toSeq(path)))
elif isinstance(path, RDD):
def func(iterator):
for x in iterator:
if not isinstance(x, basestring):
x = unicode(x)
if isinstance(x, unicode):
x = x.encode("utf-8")
yield x
keyed = path.mapPartitions(func)
keyed._bypass_serializer = True
jrdd = keyed._jrdd.map(self._spark._jvm.BytesToString())
return self._df(self._jreader.json(jrdd))
else:
raise TypeError("path can be only string or RDD")
@since(1.4)
def table(self, tableName):
"""Returns the specified table as a :class:`DataFrame`.
:param tableName: string, name of the table.
>>> df = spark.read.parquet('python/test_support/sql/parquet_partitioned')
>>> df.createOrReplaceTempView('tmpTable')
>>> spark.read.table('tmpTable').dtypes
[('name', 'string'), ('year', 'int'), ('month', 'int'), ('day', 'int')]
"""
return self._df(self._jreader.table(tableName))
@since(1.4)
def parquet(self, *paths):
"""Loads a Parquet file, returning the result as a :class:`DataFrame`.
You can set the following Parquet-specific option(s) for reading Parquet files:
* ``mergeSchema``: sets whether we should merge schemas collected from all \
Parquet part-files. This will override ``spark.sql.parquet.mergeSchema``. \
The default value is specified in ``spark.sql.parquet.mergeSchema``.
>>> df = spark.read.parquet('python/test_support/sql/parquet_partitioned')
>>> df.dtypes
[('name', 'string'), ('year', 'int'), ('month', 'int'), ('day', 'int')]
"""
return self._df(self._jreader.parquet(_to_seq(self._spark._sc, paths)))
@ignore_unicode_prefix
@since(1.6)
def text(self, paths):
"""
Loads text files and returns a :class:`DataFrame` whose schema starts with a
string column named "value", and followed by partitioned columns if there
are any.
Each line in the text file is a new row in the resulting DataFrame.
:param paths: string, or list of strings, for input path(s).
>>> df = spark.read.text('python/test_support/sql/text-test.txt')
>>> df.collect()
[Row(value=u'hello'), Row(value=u'this')]
"""
if isinstance(paths, basestring):
path = [paths]
return self._df(self._jreader.text(self._spark._sc._jvm.PythonUtils.toSeq(path)))
@since(2.0)
def csv(self, path, schema=None, sep=None, encoding=None, quote=None, escape=None,
comment=None, header=None, inferSchema=None, ignoreLeadingWhiteSpace=None,
ignoreTrailingWhiteSpace=None, nullValue=None, nanValue=None, positiveInf=None,
negativeInf=None, dateFormat=None, maxColumns=None, maxCharsPerColumn=None,
maxMalformedLogPerPartition=None, mode=None):
"""Loads a CSV file and returns the result as a :class:`DataFrame`.
This function will go through the input once to determine the input schema if
``inferSchema`` is enabled. To avoid going through the entire data once, disable
``inferSchema`` option or specify the schema explicitly using ``schema``.
:param path: string, or list of strings, for input path(s).
:param schema: an optional :class:`StructType` for the input schema.
:param sep: sets the single character as a separator for each field and value.
If None is set, it uses the default value, ``,``.
:param encoding: decodes the CSV files by the given encoding type. If None is set,
it uses the default value, ``UTF-8``.
:param quote: sets the single character used for escaping quoted values where the
separator can be part of the value. If None is set, it uses the default
value, ``"``. If you would like to turn off quotations, you need to set an
empty string.
:param escape: sets the single character used for escaping quotes inside an already
quoted value. If None is set, it uses the default value, ``\``.
:param comment: sets the single character used for skipping lines beginning with this
character. By default (None), it is disabled.
:param header: uses the first line as names of columns. If None is set, it uses the
default value, ``false``.
:param inferSchema: infers the input schema automatically from data. It requires one extra
pass over the data. If None is set, it uses the default value, ``false``.
:param ignoreLeadingWhiteSpace: defines whether or not leading whitespaces from values
being read should be skipped. If None is set, it uses
the default value, ``false``.
:param ignoreTrailingWhiteSpace: defines whether or not trailing whitespaces from values
being read should be skipped. If None is set, it uses
the default value, ``false``.
:param nullValue: sets the string representation of a null value. If None is set, it uses
the default value, empty string.
:param nanValue: sets the string representation of a non-number value. If None is set, it
uses the default value, ``NaN``.
:param positiveInf: sets the string representation of a positive infinity value. If None
is set, it uses the default value, ``Inf``.
:param negativeInf: sets the string representation of a negative infinity value. If None
is set, it uses the default value, ``Inf``.
:param dateFormat: sets the string that indicates a date format. Custom date formats
follow the formats at ``java.text.SimpleDateFormat``. This
applies to both date type and timestamp type. By default, it is None
which means trying to parse times and date by
``java.sql.Timestamp.valueOf()`` and ``java.sql.Date.valueOf()``.
:param maxColumns: defines a hard limit of how many columns a record can have. If None is
set, it uses the default value, ``20480``.
:param maxCharsPerColumn: defines the maximum number of characters allowed for any given
value being read. If None is set, it uses the default value,
``1000000``.
:param maxMalformedLogPerPartition: sets the maximum number of malformed rows Spark will
log for each partition. Malformed records beyond this
number will be ignored. If None is set, it
uses the default value, ``10``.
:param mode: allows a mode for dealing with corrupt records during parsing. If None is
set, it uses the default value, ``PERMISSIVE``.
* ``PERMISSIVE`` : sets other fields to ``null`` when it meets a corrupted record.
When a schema is set by user, it sets ``null`` for extra fields.
* ``DROPMALFORMED`` : ignores the whole corrupted records.
* ``FAILFAST`` : throws an exception when it meets corrupted records.
>>> df = spark.read.csv('python/test_support/sql/ages.csv')
>>> df.dtypes
[('_c0', 'string'), ('_c1', 'string')]
"""
self._set_opts(
schema=schema, sep=sep, encoding=encoding, quote=quote, escape=escape, comment=comment,
header=header, inferSchema=inferSchema, ignoreLeadingWhiteSpace=ignoreLeadingWhiteSpace,
ignoreTrailingWhiteSpace=ignoreTrailingWhiteSpace, nullValue=nullValue,
nanValue=nanValue, positiveInf=positiveInf, negativeInf=negativeInf,
dateFormat=dateFormat, maxColumns=maxColumns, maxCharsPerColumn=maxCharsPerColumn,
maxMalformedLogPerPartition=maxMalformedLogPerPartition, mode=mode)
if isinstance(path, basestring):
path = [path]
return self._df(self._jreader.csv(self._spark._sc._jvm.PythonUtils.toSeq(path)))
@since(1.5)
def orc(self, path):
"""Loads an ORC file, returning the result as a :class:`DataFrame`.
.. note:: Currently ORC support is only available together with Hive support.
>>> df = spark.read.orc('python/test_support/sql/orc_partitioned')
>>> df.dtypes
[('a', 'bigint'), ('b', 'int'), ('c', 'int')]
"""
return self._df(self._jreader.orc(path))
@since(1.4)
def jdbc(self, url, table, column=None, lowerBound=None, upperBound=None, numPartitions=None,
predicates=None, properties=None):
"""
Construct a :class:`DataFrame` representing the database table named ``table``
accessible via JDBC URL ``url`` and connection ``properties``.
Partitions of the table will be retrieved in parallel if either ``column`` or
``predicates`` is specified.
If both ``column`` and ``predicates`` are specified, ``column`` will be used.
.. note:: Don't create too many partitions in parallel on a large cluster; \
otherwise Spark might crash your external database systems.
:param url: a JDBC URL of the form ``jdbc:subprotocol:subname``
:param table: the name of the table
:param column: the name of an integer column that will be used for partitioning;
if this parameter is specified, then ``numPartitions``, ``lowerBound``
(inclusive), and ``upperBound`` (exclusive) will form partition strides
for generated WHERE clause expressions used to split the column
``column`` evenly
:param lowerBound: the minimum value of ``column`` used to decide partition stride
:param upperBound: the maximum value of ``column`` used to decide partition stride
:param numPartitions: the number of partitions
:param predicates: a list of expressions suitable for inclusion in WHERE clauses;
each one defines one partition of the :class:`DataFrame`
:param properties: a dictionary of JDBC database connection arguments; normally,
at least a "user" and "password" property should be included
:return: a DataFrame
"""
if properties is None:
properties = dict()
jprop = JavaClass("java.util.Properties", self._spark._sc._gateway._gateway_client)()
for k in properties:
jprop.setProperty(k, properties[k])
if column is not None:
if numPartitions is None:
numPartitions = self._spark._sc.defaultParallelism
return self._df(self._jreader.jdbc(url, table, column, int(lowerBound), int(upperBound),
int(numPartitions), jprop))
if predicates is not None:
gateway = self._spark._sc._gateway
jpredicates = utils.toJArray(gateway, gateway.jvm.java.lang.String, predicates)
return self._df(self._jreader.jdbc(url, table, jpredicates, jprop))
return self._df(self._jreader.jdbc(url, table, jprop))
class DataFrameWriter(OptionUtils):
"""
Interface used to write a :class:`DataFrame` to external storage systems
(e.g. file systems, key-value stores, etc). Use :func:`DataFrame.write`
to access this.
.. versionadded:: 1.4
"""
def __init__(self, df):
self._df = df
self._spark = df.sql_ctx
self._jwrite = df._jdf.write()
def _sq(self, jsq):
from pyspark.sql.streaming import StreamingQuery
return StreamingQuery(jsq)
@since(1.4)
def mode(self, saveMode):
"""Specifies the behavior when data or table already exists.
Options include:
* `append`: Append contents of this :class:`DataFrame` to existing data.
* `overwrite`: Overwrite existing data.
* `error`: Throw an exception if data already exists.
* `ignore`: Silently ignore this operation if data already exists.
>>> df.write.mode('append').parquet(os.path.join(tempfile.mkdtemp(), 'data'))
"""
# At the JVM side, the default value of mode is already set to "error".
# So, if the given saveMode is None, we will not call JVM-side's mode method.
if saveMode is not None:
self._jwrite = self._jwrite.mode(saveMode)
return self
@since(1.4)
def format(self, source):
"""Specifies the underlying output data source.
:param source: string, name of the data source, e.g. 'json', 'parquet'.
>>> df.write.format('json').save(os.path.join(tempfile.mkdtemp(), 'data'))
"""
self._jwrite = self._jwrite.format(source)
return self
@since(1.5)
def option(self, key, value):
"""Adds an output option for the underlying data source.
"""
self._jwrite = self._jwrite.option(key, to_str(value))
return self
@since(1.4)
def options(self, **options):
"""Adds output options for the underlying data source.
"""
for k in options:
self._jwrite = self._jwrite.option(k, to_str(options[k]))
return self
@since(1.4)
def partitionBy(self, *cols):
"""Partitions the output by the given columns on the file system.
If specified, the output is laid out on the file system similar
to Hive's partitioning scheme.
:param cols: name of columns
>>> df.write.partitionBy('year', 'month').parquet(os.path.join(tempfile.mkdtemp(), 'data'))
"""
if len(cols) == 1 and isinstance(cols[0], (list, tuple)):
cols = cols[0]
self._jwrite = self._jwrite.partitionBy(_to_seq(self._spark._sc, cols))
return self
@since(1.4)
def save(self, path=None, format=None, mode=None, partitionBy=None, **options):
"""Saves the contents of the :class:`DataFrame` to a data source.
The data source is specified by the ``format`` and a set of ``options``.
If ``format`` is not specified, the default data source configured by
``spark.sql.sources.default`` will be used.
:param path: the path in a Hadoop supported file system
:param format: the format used to save
:param mode: specifies the behavior of the save operation when data already exists.
* ``append``: Append contents of this :class:`DataFrame` to existing data.
* ``overwrite``: Overwrite existing data.
* ``ignore``: Silently ignore this operation if data already exists.
* ``error`` (default case): Throw an exception if data already exists.
:param partitionBy: names of partitioning columns
:param options: all other string options
>>> df.write.mode('append').parquet(os.path.join(tempfile.mkdtemp(), 'data'))
"""
self.mode(mode).options(**options)
if partitionBy is not None:
self.partitionBy(partitionBy)
if format is not None:
self.format(format)
if path is None:
self._jwrite.save()
else:
self._jwrite.save(path)
@since(1.4)
def insertInto(self, tableName, overwrite=False):
"""Inserts the content of the :class:`DataFrame` to the specified table.
It requires that the schema of the class:`DataFrame` is the same as the
schema of the table.
Optionally overwriting any existing data.
"""
self._jwrite.mode("overwrite" if overwrite else "append").insertInto(tableName)
@since(1.4)
def saveAsTable(self, name, format=None, mode=None, partitionBy=None, **options):
"""Saves the content of the :class:`DataFrame` as the specified table.
In the case the table already exists, behavior of this function depends on the
save mode, specified by the `mode` function (default to throwing an exception).
When `mode` is `Overwrite`, the schema of the :class:`DataFrame` does not need to be
the same as that of the existing table.
* `append`: Append contents of this :class:`DataFrame` to existing data.
* `overwrite`: Overwrite existing data.
* `error`: Throw an exception if data already exists.
* `ignore`: Silently ignore this operation if data already exists.
:param name: the table name
:param format: the format used to save
:param mode: one of `append`, `overwrite`, `error`, `ignore` (default: error)
:param partitionBy: names of partitioning columns
:param options: all other string options
"""
self.mode(mode).options(**options)
if partitionBy is not None:
self.partitionBy(partitionBy)
if format is not None:
self.format(format)
self._jwrite.saveAsTable(name)
@since(1.4)
def json(self, path, mode=None, compression=None):
"""Saves the content of the :class:`DataFrame` in JSON format at the specified path.
:param path: the path in any Hadoop supported file system
:param mode: specifies the behavior of the save operation when data already exists.
* ``append``: Append contents of this :class:`DataFrame` to existing data.
* ``overwrite``: Overwrite existing data.
* ``ignore``: Silently ignore this operation if data already exists.
* ``error`` (default case): Throw an exception if data already exists.
:param compression: compression codec to use when saving to file. This can be one of the
known case-insensitive shorten names (none, bzip2, gzip, lz4,
snappy and deflate).
>>> df.write.json(os.path.join(tempfile.mkdtemp(), 'data'))
"""
self.mode(mode)
self._set_opts(compression=compression)
self._jwrite.json(path)
@since(1.4)
def parquet(self, path, mode=None, partitionBy=None, compression=None):
"""Saves the content of the :class:`DataFrame` in Parquet format at the specified path.
:param path: the path in any Hadoop supported file system
:param mode: specifies the behavior of the save operation when data already exists.
* ``append``: Append contents of this :class:`DataFrame` to existing data.
* ``overwrite``: Overwrite existing data.
* ``ignore``: Silently ignore this operation if data already exists.
* ``error`` (default case): Throw an exception if data already exists.
:param partitionBy: names of partitioning columns
:param compression: compression codec to use when saving to file. This can be one of the
known case-insensitive shorten names (none, snappy, gzip, and lzo).
This will override ``spark.sql.parquet.compression.codec``. If None
is set, it uses the value specified in
``spark.sql.parquet.compression.codec``.
>>> df.write.parquet(os.path.join(tempfile.mkdtemp(), 'data'))
"""
self.mode(mode)
if partitionBy is not None:
self.partitionBy(partitionBy)
self._set_opts(compression=compression)
self._jwrite.parquet(path)
@since(1.6)
def text(self, path, compression=None):
"""Saves the content of the DataFrame in a text file at the specified path.
:param path: the path in any Hadoop supported file system
:param compression: compression codec to use when saving to file. This can be one of the
known case-insensitive shorten names (none, bzip2, gzip, lz4,
snappy and deflate).
The DataFrame must have only one column that is of string type.
Each row becomes a new line in the output file.
"""
self._set_opts(compression=compression)
self._jwrite.text(path)
@since(2.0)
def csv(self, path, mode=None, compression=None, sep=None, quote=None, escape=None,
header=None, nullValue=None, escapeQuotes=None, quoteAll=None):
"""Saves the content of the :class:`DataFrame` in CSV format at the specified path.
:param path: the path in any Hadoop supported file system
:param mode: specifies the behavior of the save operation when data already exists.
* ``append``: Append contents of this :class:`DataFrame` to existing data.
* ``overwrite``: Overwrite existing data.
* ``ignore``: Silently ignore this operation if data already exists.
* ``error`` (default case): Throw an exception if data already exists.
:param compression: compression codec to use when saving to file. This can be one of the
known case-insensitive shorten names (none, bzip2, gzip, lz4,
snappy and deflate).
:param sep: sets the single character as a separator for each field and value. If None is
set, it uses the default value, ``,``.
:param quote: sets the single character used for escaping quoted values where the
separator can be part of the value. If None is set, it uses the default
value, ``"``. If you would like to turn off quotations, you need to set an
empty string.
:param escape: sets the single character used for escaping quotes inside an already
quoted value. If None is set, it uses the default value, ``\``
:param escapeQuotes: A flag indicating whether values containing quotes should always
be enclosed in quotes. If None is set, it uses the default value
``true``, escaping all values containing a quote character.
:param quoteAll: A flag indicating whether all values should always be enclosed in
quotes. If None is set, it uses the default value ``false``,
only escaping values containing a quote character.
:param header: writes the names of columns as the first line. If None is set, it uses
the default value, ``false``.
:param nullValue: sets the string representation of a null value. If None is set, it uses
the default value, empty string.
>>> df.write.csv(os.path.join(tempfile.mkdtemp(), 'data'))
"""
self.mode(mode)
self._set_opts(compression=compression, sep=sep, quote=quote, escape=escape, header=header,
nullValue=nullValue, escapeQuotes=escapeQuotes, quoteAll=quoteAll)
self._jwrite.csv(path)
@since(1.5)
def orc(self, path, mode=None, partitionBy=None, compression=None):
"""Saves the content of the :class:`DataFrame` in ORC format at the specified path.
.. note:: Currently ORC support is only available together with Hive support.
:param path: the path in any Hadoop supported file system
:param mode: specifies the behavior of the save operation when data already exists.
* ``append``: Append contents of this :class:`DataFrame` to existing data.
* ``overwrite``: Overwrite existing data.
* ``ignore``: Silently ignore this operation if data already exists.
* ``error`` (default case): Throw an exception if data already exists.
:param partitionBy: names of partitioning columns
:param compression: compression codec to use when saving to file. This can be one of the
known case-insensitive shorten names (none, snappy, zlib, and lzo).
This will override ``orc.compress``. If None is set, it uses the
default value, ``snappy``.
>>> orc_df = spark.read.orc('python/test_support/sql/orc_partitioned')
>>> orc_df.write.orc(os.path.join(tempfile.mkdtemp(), 'data'))
"""
self.mode(mode)
if partitionBy is not None:
self.partitionBy(partitionBy)
self._set_opts(compression=compression)
self._jwrite.orc(path)
@since(1.4)
def jdbc(self, url, table, mode=None, properties=None):
"""Saves the content of the :class:`DataFrame` to an external database table via JDBC.
.. note:: Don't create too many partitions in parallel on a large cluster; \
otherwise Spark might crash your external database systems.
:param url: a JDBC URL of the form ``jdbc:subprotocol:subname``
:param table: Name of the table in the external database.
:param mode: specifies the behavior of the save operation when data already exists.
* ``append``: Append contents of this :class:`DataFrame` to existing data.
* ``overwrite``: Overwrite existing data.
* ``ignore``: Silently ignore this operation if data already exists.
* ``error`` (default case): Throw an exception if data already exists.
:param properties: JDBC database connection arguments, a list of
arbitrary string tag/value. Normally at least a
"user" and "password" property should be included.
"""
if properties is None:
properties = dict()
jprop = JavaClass("java.util.Properties", self._spark._sc._gateway._gateway_client)()
for k in properties:
jprop.setProperty(k, properties[k])
self._jwrite.mode(mode).jdbc(url, table, jprop)
def _test():
import doctest
import os
import tempfile
import py4j
from pyspark.context import SparkContext
from pyspark.sql import SparkSession, Row
import pyspark.sql.readwriter
os.chdir(os.environ["SPARK_HOME"])
globs = pyspark.sql.readwriter.__dict__.copy()
sc = SparkContext('local[4]', 'PythonTest')
try:
spark = SparkSession.builder.enableHiveSupport().getOrCreate()
except py4j.protocol.Py4JError:
spark = SparkSession(sc)
globs['tempfile'] = tempfile
globs['os'] = os
globs['sc'] = sc
globs['spark'] = spark
globs['df'] = spark.read.parquet('python/test_support/sql/parquet_partitioned')
(failure_count, test_count) = doctest.testmod(
pyspark.sql.readwriter, globs=globs,
optionflags=doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE | doctest.REPORT_NDIFF)
sc.stop()
if failure_count:
exit(-1)
if __name__ == "__main__":
_test()
| []
| []
| [
"SPARK_HOME"
]
| [] | ["SPARK_HOME"] | python | 1 | 0 | |
python/core/config.py | """
Load the config file and create any custom variables
that are available for ease of use purposes
"""
import yaml
import os
BASE_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')
with open(BASE_DIR + "/config/config.yml", "r") as configFile:
data = configFile.read()
data = yaml.load(data, Loader=yaml.FullLoader)
# ORCS config
if data['orcs']['access_key'] == "":
ACCESS_KEY = os.environ['BIOGRID_ACCESSKEY']
else:
ACCESS_KEY = data['orcs']['access_key']
BASE_URL = data['orcs']['base_url']
# Results config
RESULTS_FOLDER = data['results']['folder_path']
DIAGRAM_FILE_NAME = data['results']['diagram_file_name']
INPUT_DATA_CSV_NAME = data['results']['input_data_csv_name']
CLUSTER_DATA_TXT_NAME = data['results']['cluster_data_txt_name']
CLUSTER_DATA_CSV_FOLDER = data['results']['cluster_data_csv_folder']
CLUSTER_DATA_CSV_PREFIX = data['results']['cluster_data_csv_prefix']
# Plot config
PLOT_TITLE = data['results']['plot']['title']
PLOT_X_LABEL = data['results']['plot']['x_label']
PLOT_Y_LABEL = data['results']['plot']['y_label']
# Clustering config
MAX_DISTANCE = data['clustering']['max_distance']
PRUNING = data['clustering']['pruning']
| []
| []
| [
"BIOGRID_ACCESSKEY"
]
| [] | ["BIOGRID_ACCESSKEY"] | python | 1 | 0 | |
main.go | package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strings"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/pkg/errors"
"github.com/toshi0607/release-tweeter/github"
"github.com/toshi0607/release-tweeter/twitter"
)
// Tweeter is interface to tweet a message
type tweeter interface {
Tweet(message string) (string, error)
}
var twitterClient tweeter
func init() {
twitterAccessToken := os.Getenv("TWITTER_ACCESS_TOKEN")
twitterAccessTokenSecret := os.Getenv("TWITTER_ACCESS_TOKEN_SECRET")
twitterConsumerKey := os.Getenv("TWITTER_CONSUMER_KEY")
twitterConsumerKeySecret := os.Getenv("TWITTER_CONSUMER_SECRET")
tc, err := twitter.NewClient(
twitterAccessToken,
twitterAccessTokenSecret,
twitterConsumerKey,
twitterConsumerKeySecret,
)
if err != nil {
log.Fatal(err)
}
twitterClient = tc
}
type params struct {
Owner string `json:"owner"`
Repo string `json:"repo"`
}
func main() {
lambda.Start(handler)
}
func handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
p, err := parseRequest(request)
if err != nil {
return response(
http.StatusBadRequest,
err.Error(),
), nil
}
c, err := github.NewClient(p.Owner, p.Repo)
if err != nil {
return response(
http.StatusBadRequest,
err.Error(),
), nil
}
tag, err := c.GetLatestTag()
if err != nil {
return response(
http.StatusInternalServerError,
err.Error(),
), nil
}
log.Printf("tag: %s, ID: %s\n", tag, request.RequestContext.RequestID)
message := fmt.Sprintf("%s %s released! check the new features on GitHub.\n%s", c.FullRepo, tag, c.RepoURL)
msg, err := twitterClient.Tweet(message)
if err != nil {
return response(
http.StatusInternalServerError,
err.Error(),
), nil
}
if !strings.Contains(msg, tag) {
return response(
http.StatusInternalServerError,
fmt.Sprintf("failed to tweet: %s", msg),
), nil
}
log.Printf("message tweeted: %s, ID: %s\n", msg, request.RequestContext.RequestID)
return response(http.StatusOK, tag), nil
}
func parseRequest(r events.APIGatewayProxyRequest) (*params, error) {
if r.HTTPMethod != "POST" {
return nil, fmt.Errorf("use POST request")
}
var p params
err := json.Unmarshal([]byte(r.Body), &p)
if err != nil {
return nil, errors.Wrapf(err, "failed to parse params")
}
return &p, nil
}
func response(code int, msg string) events.APIGatewayProxyResponse {
return events.APIGatewayProxyResponse{
StatusCode: code,
Body: fmt.Sprintf("{\"message\":\"%s\"}", msg),
Headers: map[string]string{"Content-Type": "application/json"},
}
}
| [
"\"TWITTER_ACCESS_TOKEN\"",
"\"TWITTER_ACCESS_TOKEN_SECRET\"",
"\"TWITTER_CONSUMER_KEY\"",
"\"TWITTER_CONSUMER_SECRET\""
]
| []
| [
"TWITTER_ACCESS_TOKEN_SECRET",
"TWITTER_ACCESS_TOKEN",
"TWITTER_CONSUMER_SECRET",
"TWITTER_CONSUMER_KEY"
]
| [] | ["TWITTER_ACCESS_TOKEN_SECRET", "TWITTER_ACCESS_TOKEN", "TWITTER_CONSUMER_SECRET", "TWITTER_CONSUMER_KEY"] | go | 4 | 0 | |
desktop/libs/hadoop/gen-py/hadoop/api/hdfs/constants.py | #
# Autogenerated by Thrift
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
from thrift.Thrift import *
from ttypes import *
UNKNOWN_THRIFT_PORT = -1
QUOTA_DONT_SET = -2
QUOTA_RESET = -1
| []
| []
| []
| [] | [] | python | null | null | null |
seleniumbase/fixtures/base_case.py | # -*- coding: utf-8 -*-
r""" ------------> ------------> ------------> ------------>
______ __ _ ____
/ ____/__ / /__ ____ (_)_ ______ ___ / _ \____ ________
\__ \/ _ \/ / _ \/ __ \/ / / / / __ `__ \/ /_) / __ \/ ___/ _ \
___/ / __/ / __/ / / / / /_/ / / / / / / /_) / (_/ /__ / __/
/____/\___/_/\___/_/ /_/_/\__,_/_/ /_/ /_/_____/\__,_/____/\___/
------------> ------------> ------------> ------------>
The BaseCase class is the main gateway for using The SeleniumBase Framework.
It inherits Python's unittest.TestCase class, and runs with Pytest or Nose.
All tests using BaseCase automatically launch WebDriver browsers for tests.
Usage:
from seleniumbase import BaseCase
class MyTestClass(BaseCase):
def test_anything(self):
# Write your code here. Example:
self.open("https://github.com/")
self.type("input.header-search-input", "SeleniumBase\n")
self.click('a[href="/seleniumbase/SeleniumBase"]')
self.assert_element("div.repository-content")
....
SeleniumBase methods expand and improve on existing WebDriver commands.
Improvements include making WebDriver more robust, reliable, and flexible.
Page elements are given enough time to load before WebDriver acts on them.
Code becomes greatly simplified and easier to maintain.
"""
import codecs
import json
import logging
import os
import re
import shutil
import sys
import time
import unittest
import urllib3
from selenium.common.exceptions import (
ElementClickInterceptedException as ECI_Exception,
ElementNotInteractableException as ENI_Exception,
MoveTargetOutOfBoundsException,
NoSuchWindowException,
StaleElementReferenceException,
WebDriverException,
)
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.remote.remote_connection import LOGGER
from seleniumbase import config as sb_config
from seleniumbase.config import settings
from seleniumbase.core import log_helper
from seleniumbase.fixtures import constants
from seleniumbase.fixtures import css_to_xpath
from seleniumbase.fixtures import js_utils
from seleniumbase.fixtures import page_actions
from seleniumbase.fixtures import page_utils
from seleniumbase.fixtures import shared_utils
from seleniumbase.fixtures import xpath_to_css
logging.getLogger("requests").setLevel(logging.ERROR)
logging.getLogger("urllib3").setLevel(logging.ERROR)
urllib3.disable_warnings()
LOGGER.setLevel(logging.WARNING)
python3 = True
if sys.version_info[0] < 3:
python3 = False
reload(sys) # noqa: F821
sys.setdefaultencoding("utf8")
selenium4 = False
if sys.version_info[0] == 3 and sys.version_info[1] >= 7:
selenium4 = True
class BaseCase(unittest.TestCase):
""" <Class seleniumbase.BaseCase> """
def __init__(self, *args, **kwargs):
super(BaseCase, self).__init__(*args, **kwargs)
self.driver = None
self.environment = None
self.env = None # Add a shortened version of self.environment
self.__page_sources = []
self.__extra_actions = []
self.__js_start_time = 0
self.__set_c_from_switch = False
self.__called_setup = False
self.__called_teardown = False
self.__start_time_ms = None
self.__requests_timeout = None
self.__screenshot_count = 0
self.__will_be_skipped = False
self.__passed_then_skipped = False
self.__visual_baseline_copies = []
self.__last_url_of_deferred_assert = "data:,"
self.__last_page_load_url = "data:,"
self.__last_page_screenshot = None
self.__last_page_screenshot_png = None
self.__last_page_url = None
self.__last_page_source = None
self.__skip_reason = None
self.__origins_to_save = []
self.__actions_to_save = []
self.__dont_record_open = False
self.__dont_record_js_click = False
self.__new_window_on_rec_open = True
self.__overrided_default_timeouts = False
self.__added_pytest_html_extra = None
self.__deferred_assert_count = 0
self.__deferred_assert_failures = []
self.__device_width = None
self.__device_height = None
self.__device_pixel_ratio = None
self.__driver_browser_map = {}
self.__changed_jqc_theme = False
self.__jqc_default_theme = None
self.__jqc_default_color = None
self.__jqc_default_width = None
# Requires self._* instead of self.__* for external class use
self._language = "English"
self._presentation_slides = {}
self._presentation_transition = {}
self._rec_overrides_switch = True # Recorder-Mode uses set_c vs switch
self._sb_test_identifier = None
self._html_report_extra = [] # (Used by pytest_plugin.py)
self._default_driver = None
self._drivers_list = []
self._chart_data = {}
self._chart_count = 0
self._chart_label = {}
self._chart_xcount = 0
self._chart_first_series = {}
self._chart_series_count = {}
self._tour_steps = {}
def open(self, url):
""" Navigates the current browser window to the specified page. """
self.__check_scope()
self.__check_browser()
pre_action_url = None
try:
pre_action_url = self.driver.current_url
except Exception:
pass
url = str(url).strip() # Remove leading and trailing whitespace
if not self.__looks_like_a_page_url(url):
# url should start with one of the following:
# "http:", "https:", "://", "data:", "file:",
# "about:", "chrome:", "opera:", or "edge:".
msg = 'Did you forget to prefix your URL with "http:" or "https:"?'
raise Exception('Invalid URL: "%s"\n%s' % (url, msg))
self.__last_page_load_url = None
js_utils.clear_out_console_logs(self.driver)
if url.startswith("://"):
# Convert URLs such as "://google.com" into "https://google.com"
url = "https" + url
if self.recorder_mode and not self.__dont_record_open:
time_stamp = self.execute_script("return Date.now();")
origin = self.get_origin()
action = ["_url_", origin, url, time_stamp]
self.__extra_actions.append(action)
if self.recorder_mode and self.__new_window_on_rec_open:
c_url = self.driver.current_url
if ("http:") in c_url or ("https:") in c_url or ("file:") in c_url:
if self.get_domain_url(url) != self.get_domain_url(c_url):
self.open_new_window(switch_to=True)
try:
self.driver.get(url)
except Exception as e:
if "ERR_CONNECTION_TIMED_OUT" in e.msg:
self.sleep(0.5)
self.driver.get(url)
else:
raise Exception(e.msg)
if (
self.driver.current_url == pre_action_url
and pre_action_url != url
):
time.sleep(0.1) # Make sure load happens
if settings.WAIT_FOR_RSC_ON_PAGE_LOADS:
self.wait_for_ready_state_complete()
self.__demo_mode_pause_if_active()
def get(self, url):
"""If "url" looks like a page URL, open the URL in the web browser.
Otherwise, return self.get_element(URL_AS_A_SELECTOR)
Examples:
self.get("https://seleniumbase.io") # Navigates to the URL
self.get("input.class") # Finds and returns the WebElement
"""
self.__check_scope()
if self.__looks_like_a_page_url(url):
self.open(url)
else:
return self.get_element(url) # url is treated like a selector
def click(
self, selector, by=By.CSS_SELECTOR, timeout=None, delay=0, scroll=True
):
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
original_selector = selector
original_by = by
selector, by = self.__recalculate_selector(selector, by)
if delay and (type(delay) in [int, float]) and delay > 0:
time.sleep(delay)
if page_utils.is_link_text_selector(selector) or by == By.LINK_TEXT:
if not self.is_link_text_visible(selector):
# Handle a special case of links hidden in dropdowns
self.click_link_text(selector, timeout=timeout)
return
if (
page_utils.is_partial_link_text_selector(selector)
or by == By.PARTIAL_LINK_TEXT
):
if not self.is_partial_link_text_visible(selector):
# Handle a special case of partial links hidden in dropdowns
self.click_partial_link_text(selector, timeout=timeout)
return
if self.__is_shadow_selector(selector):
self.__shadow_click(selector)
return
element = page_actions.wait_for_element_visible(
self.driver, selector, by, timeout=timeout
)
self.__demo_mode_highlight_if_active(original_selector, original_by)
if scroll and not self.demo_mode and not self.slow_mode:
self.__scroll_to_element(element, selector, by)
pre_action_url = self.driver.current_url
pre_window_count = len(self.driver.window_handles)
try:
if self.browser == "ie" and by == By.LINK_TEXT:
# An issue with clicking Link Text on IE means using jquery
self.__jquery_click(selector, by=by)
elif self.browser == "safari":
if by == By.LINK_TEXT:
self.__jquery_click(selector, by=by)
else:
self.__js_click(selector, by=by)
else:
href = None
new_tab = False
onclick = None
try:
if self.headless and element.tag_name == "a":
# Handle a special case of opening a new tab (headless)
href = element.get_attribute("href").strip()
onclick = element.get_attribute("onclick")
target = element.get_attribute("target")
if target == "_blank":
new_tab = True
if new_tab and self.__looks_like_a_page_url(href):
if onclick:
try:
self.execute_script(onclick)
except Exception:
pass
current_window = self.driver.current_window_handle
self.open_new_window()
try:
self.open(href)
except Exception:
pass
self.switch_to_window(current_window)
return
except Exception:
pass
# Normal click
element.click()
except StaleElementReferenceException:
self.wait_for_ready_state_complete()
time.sleep(0.16)
element = page_actions.wait_for_element_visible(
self.driver, selector, by, timeout=timeout
)
try:
self.__scroll_to_element(element, selector, by)
except Exception:
pass
if self.browser == "safari":
if by == By.LINK_TEXT:
self.__jquery_click(selector, by=by)
else:
self.__js_click(selector, by=by)
else:
element.click()
except ENI_Exception:
self.wait_for_ready_state_complete()
time.sleep(0.1)
element = page_actions.wait_for_element_visible(
self.driver, selector, by, timeout=timeout
)
href = None
new_tab = False
onclick = None
try:
if element.tag_name == "a":
# Handle a special case of opening a new tab (non-headless)
href = element.get_attribute("href").strip()
onclick = element.get_attribute("onclick")
target = element.get_attribute("target")
if target == "_blank":
new_tab = True
if new_tab and self.__looks_like_a_page_url(href):
if onclick:
try:
self.execute_script(onclick)
except Exception:
pass
current_window = self.driver.current_window_handle
self.open_new_window()
try:
self.open(href)
except Exception:
pass
self.switch_to_window(current_window)
return
except Exception:
pass
self.__scroll_to_element(element, selector, by)
if self.browser == "firefox" or self.browser == "safari":
if by == By.LINK_TEXT or "contains(" in selector:
self.__jquery_click(selector, by=by)
else:
self.__js_click(selector, by=by)
else:
element.click()
except (WebDriverException, MoveTargetOutOfBoundsException):
self.wait_for_ready_state_complete()
try:
self.__js_click(selector, by=by)
except Exception:
try:
self.__jquery_click(selector, by=by)
except Exception:
# One more attempt to click on the element
element = page_actions.wait_for_element_visible(
self.driver, selector, by, timeout=timeout
)
element.click()
latest_window_count = len(self.driver.window_handles)
if (
latest_window_count > pre_window_count
and (
self.recorder_mode
or (
settings.SWITCH_TO_NEW_TABS_ON_CLICK
and self.driver.current_url == pre_action_url
)
)
):
self.__switch_to_newest_window_if_not_blank()
if settings.WAIT_FOR_RSC_ON_CLICKS:
self.wait_for_ready_state_complete()
else:
# A smaller subset of self.wait_for_ready_state_complete()
self.wait_for_angularjs(timeout=settings.MINI_TIMEOUT)
if self.driver.current_url != pre_action_url:
self.__ad_block_as_needed()
if self.demo_mode:
if self.driver.current_url != pre_action_url:
self.__demo_mode_pause_if_active()
else:
self.__demo_mode_pause_if_active(tiny=True)
elif self.slow_mode:
self.__slow_mode_pause_if_active()
def slow_click(self, selector, by=By.CSS_SELECTOR, timeout=None):
"""Similar to click(), but pauses for a brief moment before clicking.
When used in combination with setting the user-agent, you can often
bypass bot-detection by tricking websites into thinking that you're
not a bot. (Useful on websites that block web automation tools.)
To set the user-agent, use: ``--agent=AGENT``.
Here's an example message from GitHub's bot-blocker:
``You have triggered an abuse detection mechanism...``
"""
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
if not self.demo_mode and not self.slow_mode:
self.click(selector, by=by, timeout=timeout, delay=1.05)
elif self.slow_mode:
self.click(selector, by=by, timeout=timeout, delay=0.65)
else:
# Demo Mode already includes a small delay
self.click(selector, by=by, timeout=timeout, delay=0.25)
def double_click(self, selector, by=By.CSS_SELECTOR, timeout=None):
from selenium.webdriver.common.action_chains import ActionChains
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
original_selector = selector
original_by = by
selector, by = self.__recalculate_selector(selector, by)
element = page_actions.wait_for_element_visible(
self.driver, selector, by, timeout=timeout
)
self.__demo_mode_highlight_if_active(original_selector, original_by)
if not self.demo_mode and not self.slow_mode:
self.__scroll_to_element(element, selector, by)
self.wait_for_ready_state_complete()
# Find the element one more time in case scrolling hid it
element = page_actions.wait_for_element_visible(
self.driver, selector, by, timeout=timeout
)
pre_action_url = self.driver.current_url
try:
if self.browser == "safari":
# Jump to the "except" block where the other script should work
raise Exception("This Exception will be caught.")
actions = ActionChains(self.driver)
actions.double_click(element).perform()
except Exception:
css_selector = self.convert_to_css_selector(selector, by=by)
css_selector = re.escape(css_selector) # Add "\\" to special chars
css_selector = self.__escape_quotes_if_needed(css_selector)
double_click_script = (
"""var targetElement1 = document.querySelector('%s');
var clickEvent1 = document.createEvent('MouseEvents');
clickEvent1.initEvent('dblclick', true, true);
targetElement1.dispatchEvent(clickEvent1);"""
% css_selector
)
if ":contains\\(" not in css_selector:
self.execute_script(double_click_script)
else:
double_click_script = (
"""jQuery('%s').dblclick();""" % css_selector
)
self.safe_execute_script(double_click_script)
if settings.WAIT_FOR_RSC_ON_CLICKS:
self.wait_for_ready_state_complete()
else:
# A smaller subset of self.wait_for_ready_state_complete()
self.wait_for_angularjs(timeout=settings.MINI_TIMEOUT)
if self.driver.current_url != pre_action_url:
self.__ad_block_as_needed()
if self.demo_mode:
if self.driver.current_url != pre_action_url:
self.__demo_mode_pause_if_active()
else:
self.__demo_mode_pause_if_active(tiny=True)
elif self.slow_mode:
self.__slow_mode_pause_if_active()
def click_chain(
self, selectors_list, by=By.CSS_SELECTOR, timeout=None, spacing=0
):
"""This method clicks on a list of elements in succession.
@Params
selectors_list - The list of selectors to click on.
by - The type of selector to search by (Default: CSS_Selector).
timeout - How long to wait for the selector to be visible.
spacing - The amount of time to wait between clicks (in seconds).
"""
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
for selector in selectors_list:
self.click(selector, by=by, timeout=timeout)
if spacing > 0:
time.sleep(spacing)
def update_text(
self, selector, text, by=By.CSS_SELECTOR, timeout=None, retry=False
):
"""This method updates an element's text field with new text.
Has multiple parts:
* Waits for the element to be visible.
* Waits for the element to be interactive.
* Clears the text field.
* Types in the new text.
* Hits Enter/Submit (if the text ends in "\n").
@Params
selector - the selector of the text field
text - the new text to type into the text field
by - the type of selector to search by (Default: CSS Selector)
timeout - how long to wait for the selector to be visible
retry - if True, use JS if the Selenium text update fails
"""
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
if self.__is_shadow_selector(selector):
self.__shadow_type(selector, text)
return
element = self.wait_for_element_visible(
selector, by=by, timeout=timeout
)
self.__demo_mode_highlight_if_active(selector, by)
if not self.demo_mode and not self.slow_mode:
self.__scroll_to_element(element, selector, by)
try:
element.clear() # May need https://stackoverflow.com/a/50691625
backspaces = Keys.BACK_SPACE * 42 # Is the answer to everything
element.send_keys(backspaces) # In case autocomplete keeps text
except (StaleElementReferenceException, ENI_Exception):
self.wait_for_ready_state_complete()
time.sleep(0.16)
element = self.wait_for_element_visible(
selector, by=by, timeout=timeout
)
try:
element.clear()
except Exception:
pass # Clearing the text field first might not be necessary
except Exception:
pass # Clearing the text field first might not be necessary
self.__demo_mode_pause_if_active(tiny=True)
pre_action_url = self.driver.current_url
if type(text) is int or type(text) is float:
text = str(text)
try:
if not text.endswith("\n"):
element.send_keys(text)
if settings.WAIT_FOR_RSC_ON_PAGE_LOADS:
self.wait_for_ready_state_complete()
else:
element.send_keys(text[:-1])
element.send_keys(Keys.RETURN)
if settings.WAIT_FOR_RSC_ON_PAGE_LOADS:
self.wait_for_ready_state_complete()
except (StaleElementReferenceException, ENI_Exception):
self.wait_for_ready_state_complete()
time.sleep(0.16)
element = self.wait_for_element_visible(
selector, by=by, timeout=timeout
)
element.clear()
if not text.endswith("\n"):
element.send_keys(text)
else:
element.send_keys(text[:-1])
element.send_keys(Keys.RETURN)
if settings.WAIT_FOR_RSC_ON_PAGE_LOADS:
self.wait_for_ready_state_complete()
if (
retry
and element.get_attribute("value") != text
and not text.endswith("\n")
):
logging.debug("update_text() is falling back to JavaScript!")
self.set_value(selector, text, by=by)
if self.demo_mode:
if self.driver.current_url != pre_action_url:
self.__demo_mode_pause_if_active()
else:
self.__demo_mode_pause_if_active(tiny=True)
elif self.slow_mode:
self.__slow_mode_pause_if_active()
def add_text(self, selector, text, by=By.CSS_SELECTOR, timeout=None):
"""The more-reliable version of driver.send_keys()
Similar to update_text(), but won't clear the text field first."""
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
if self.__is_shadow_selector(selector):
self.__shadow_type(selector, text, clear_first=False)
return
element = self.wait_for_element_visible(
selector, by=by, timeout=timeout
)
self.__demo_mode_highlight_if_active(selector, by)
if not self.demo_mode and not self.slow_mode:
self.__scroll_to_element(element, selector, by)
pre_action_url = self.driver.current_url
if type(text) is int or type(text) is float:
text = str(text)
try:
if not text.endswith("\n"):
element.send_keys(text)
else:
element.send_keys(text[:-1])
element.send_keys(Keys.RETURN)
if settings.WAIT_FOR_RSC_ON_PAGE_LOADS:
self.wait_for_ready_state_complete()
except (StaleElementReferenceException, ENI_Exception):
self.wait_for_ready_state_complete()
time.sleep(0.16)
element = self.wait_for_element_visible(
selector, by=by, timeout=timeout
)
if not text.endswith("\n"):
element.send_keys(text)
else:
element.send_keys(text[:-1])
element.send_keys(Keys.RETURN)
if settings.WAIT_FOR_RSC_ON_PAGE_LOADS:
self.wait_for_ready_state_complete()
if self.demo_mode:
if self.driver.current_url != pre_action_url:
self.__demo_mode_pause_if_active()
else:
self.__demo_mode_pause_if_active(tiny=True)
elif self.slow_mode:
self.__slow_mode_pause_if_active()
def type(
self, selector, text, by=By.CSS_SELECTOR, timeout=None, retry=False
):
"""Same as self.update_text()
This method updates an element's text field with new text.
Has multiple parts:
* Waits for the element to be visible.
* Waits for the element to be interactive.
* Clears the text field.
* Types in the new text.
* Hits Enter/Submit (if the text ends in "\n").
@Params
selector - the selector of the text field
text - the new text to type into the text field
by - the type of selector to search by (Default: CSS Selector)
timeout - how long to wait for the selector to be visible
retry - if True, use JS if the Selenium text update fails
DO NOT confuse self.type() with Python type()! They are different!
"""
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
self.update_text(selector, text, by=by, timeout=timeout, retry=retry)
def submit(self, selector, by=By.CSS_SELECTOR):
""" Alternative to self.driver.find_element_by_*(SELECTOR).submit() """
self.__check_scope()
selector, by = self.__recalculate_selector(selector, by)
element = self.wait_for_element_visible(
selector, by=by, timeout=settings.SMALL_TIMEOUT
)
element.submit()
self.__demo_mode_pause_if_active()
def clear(self, selector, by=By.CSS_SELECTOR, timeout=None):
"""This method clears an element's text field.
A clear() is already included with most methods that type text,
such as self.type(), self.update_text(), etc.
Does not use Demo Mode highlights, mainly because we expect
that some users will be calling an unnecessary clear() before
calling a method that already includes clear() as part of it.
In case websites trigger an autofill after clearing a field,
add backspaces to make sure autofill doesn't undo the clear.
@Params
selector - the selector of the text field
by - the type of selector to search by (Default: CSS Selector)
timeout - how long to wait for the selector to be visible
"""
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
if self.__is_shadow_selector(selector):
self.__shadow_clear(selector)
return
element = self.wait_for_element_visible(
selector, by=by, timeout=timeout
)
self.scroll_to(selector, by=by, timeout=timeout)
try:
element.clear()
backspaces = Keys.BACK_SPACE * 42 # Autofill Defense
element.send_keys(backspaces)
except (StaleElementReferenceException, ENI_Exception):
self.wait_for_ready_state_complete()
time.sleep(0.16)
element = self.wait_for_element_visible(
selector, by=by, timeout=timeout
)
element.clear()
try:
backspaces = Keys.BACK_SPACE * 42 # Autofill Defense
element.send_keys(backspaces)
except Exception:
pass
except Exception:
element.clear()
def focus(self, selector, by=By.CSS_SELECTOR, timeout=None):
"""Make the current page focus on an interactable element.
If the element is not interactable, only scrolls to it.
The "tab" key is another way of setting the page focus."""
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
element = self.wait_for_element_visible(
selector, by=by, timeout=timeout
)
self.scroll_to(selector, by=by, timeout=timeout)
try:
element.send_keys(Keys.NULL)
except (StaleElementReferenceException, ENI_Exception):
self.wait_for_ready_state_complete()
time.sleep(0.12)
element = self.wait_for_element_visible(
selector, by=by, timeout=timeout
)
try:
element.send_keys(Keys.NULL)
except ENI_Exception:
# Non-interactable element. Skip focus and continue.
pass
self.__demo_mode_pause_if_active()
def refresh_page(self):
self.__check_scope()
self.__last_page_load_url = None
js_utils.clear_out_console_logs(self.driver)
self.driver.refresh()
self.wait_for_ready_state_complete()
def refresh(self):
""" The shorter version of self.refresh_page() """
self.refresh_page()
def get_current_url(self):
self.__check_scope()
current_url = self.driver.current_url
if "%" in current_url and python3:
try:
from urllib.parse import unquote
current_url = unquote(current_url, errors="strict")
except Exception:
pass
return current_url
def get_origin(self):
self.__check_scope()
return self.execute_script("return window.location.origin;")
def get_page_source(self):
self.wait_for_ready_state_complete()
return self.driver.page_source
def get_page_title(self):
self.wait_for_ready_state_complete()
self.wait_for_element_present("title", timeout=settings.SMALL_TIMEOUT)
time.sleep(0.03)
return self.driver.title
def get_title(self):
""" The shorter version of self.get_page_title() """
return self.get_page_title()
def get_user_agent(self):
self.__check_scope()
self.__check_browser()
user_agent = self.driver.execute_script("return navigator.userAgent;")
return user_agent
def get_locale_code(self):
self.__check_scope()
self.__check_browser()
locale_code = self.driver.execute_script(
"return navigator.language || navigator.languages[0];"
)
return locale_code
def go_back(self):
self.__check_scope()
self.__last_page_load_url = None
self.driver.back()
if self.browser == "safari":
self.wait_for_ready_state_complete()
self.driver.refresh()
self.wait_for_ready_state_complete()
self.__demo_mode_pause_if_active()
def go_forward(self):
self.__check_scope()
self.__last_page_load_url = None
self.driver.forward()
self.wait_for_ready_state_complete()
self.__demo_mode_pause_if_active()
def open_start_page(self):
"""Navigates the current browser window to the start_page.
You can set the start_page on the command-line in three ways:
'--start_page=URL', '--start-page=URL', or '--url=URL'.
If the start_page is not set, then "data:," will be used."""
self.__check_scope()
start_page = self.start_page
if type(start_page) is str:
start_page = start_page.strip() # Remove extra whitespace
if start_page and len(start_page) >= 4:
if page_utils.is_valid_url(start_page):
self.open(start_page)
else:
new_start_page = "https://" + start_page
if page_utils.is_valid_url(new_start_page):
self.__dont_record_open = True
self.open(new_start_page)
self.__dont_record_open = False
else:
logging.info('Invalid URL: "%s"!' % start_page)
self.open("data:,")
else:
self.open("data:,")
def open_if_not_url(self, url):
""" Opens the url in the browser if it's not the current url. """
self.__check_scope()
if self.driver.current_url != url:
self.open(url)
def is_element_present(self, selector, by=By.CSS_SELECTOR):
self.wait_for_ready_state_complete()
selector, by = self.__recalculate_selector(selector, by)
return page_actions.is_element_present(self.driver, selector, by)
def is_element_visible(self, selector, by=By.CSS_SELECTOR):
self.wait_for_ready_state_complete()
selector, by = self.__recalculate_selector(selector, by)
return page_actions.is_element_visible(self.driver, selector, by)
def is_element_enabled(self, selector, by=By.CSS_SELECTOR):
self.wait_for_ready_state_complete()
selector, by = self.__recalculate_selector(selector, by)
return page_actions.is_element_enabled(self.driver, selector, by)
def is_text_visible(self, text, selector="html", by=By.CSS_SELECTOR):
self.wait_for_ready_state_complete()
time.sleep(0.01)
selector, by = self.__recalculate_selector(selector, by)
return page_actions.is_text_visible(self.driver, text, selector, by)
def is_attribute_present(
self, selector, attribute, value=None, by=By.CSS_SELECTOR
):
"""Returns True if the element attribute/value is found.
If the value is not specified, the attribute only needs to exist."""
self.wait_for_ready_state_complete()
time.sleep(0.01)
selector, by = self.__recalculate_selector(selector, by)
return page_actions.is_attribute_present(
self.driver, selector, attribute, value, by
)
def is_link_text_visible(self, link_text):
self.wait_for_ready_state_complete()
time.sleep(0.01)
return page_actions.is_element_visible(
self.driver, link_text, by=By.LINK_TEXT
)
def is_partial_link_text_visible(self, partial_link_text):
self.wait_for_ready_state_complete()
time.sleep(0.01)
return page_actions.is_element_visible(
self.driver, partial_link_text, by=By.PARTIAL_LINK_TEXT
)
def is_link_text_present(self, link_text):
"""Returns True if the link text appears in the HTML of the page.
The element doesn't need to be visible,
such as elements hidden inside a dropdown selection."""
self.wait_for_ready_state_complete()
soup = self.get_beautiful_soup()
html_links = soup.find_all("a")
for html_link in html_links:
if html_link.text.strip() == link_text.strip():
return True
return False
def is_partial_link_text_present(self, link_text):
"""Returns True if the partial link appears in the HTML of the page.
The element doesn't need to be visible,
such as elements hidden inside a dropdown selection."""
self.wait_for_ready_state_complete()
soup = self.get_beautiful_soup()
html_links = soup.find_all("a")
for html_link in html_links:
if link_text.strip() in html_link.text.strip():
return True
return False
def get_link_attribute(self, link_text, attribute, hard_fail=True):
"""Finds a link by link text and then returns the attribute's value.
If the link text or attribute cannot be found, an exception will
get raised if hard_fail is True (otherwise None is returned)."""
self.wait_for_ready_state_complete()
soup = self.get_beautiful_soup()
html_links = soup.find_all("a")
for html_link in html_links:
if html_link.text.strip() == link_text.strip():
if html_link.has_attr(attribute):
attribute_value = html_link.get(attribute)
return attribute_value
if hard_fail:
raise Exception(
"Unable to find attribute {%s} from link text {%s}!"
% (attribute, link_text)
)
else:
return None
if hard_fail:
raise Exception("Link text {%s} was not found!" % link_text)
else:
return None
def get_link_text_attribute(self, link_text, attribute, hard_fail=True):
"""Same as self.get_link_attribute()
Finds a link by link text and then returns the attribute's value.
If the link text or attribute cannot be found, an exception will
get raised if hard_fail is True (otherwise None is returned)."""
return self.get_link_attribute(link_text, attribute, hard_fail)
def get_partial_link_text_attribute(
self, link_text, attribute, hard_fail=True
):
"""Finds a link by partial link text and then returns the attribute's
value. If the partial link text or attribute cannot be found, an
exception will get raised if hard_fail is True (otherwise None
is returned)."""
self.wait_for_ready_state_complete()
soup = self.get_beautiful_soup()
html_links = soup.find_all("a")
for html_link in html_links:
if link_text.strip() in html_link.text.strip():
if html_link.has_attr(attribute):
attribute_value = html_link.get(attribute)
return attribute_value
if hard_fail:
raise Exception(
"Unable to find attribute {%s} from "
"partial link text {%s}!" % (attribute, link_text)
)
else:
return None
if hard_fail:
raise Exception(
"Partial Link text {%s} was not found!" % link_text
)
else:
return None
def click_link_text(self, link_text, timeout=None):
""" This method clicks link text on a page """
# If using phantomjs, might need to extract and open the link directly
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
pre_action_url = self.driver.current_url
pre_window_count = len(self.driver.window_handles)
if self.browser == "phantomjs":
if self.is_link_text_visible(link_text):
element = self.wait_for_link_text_visible(
link_text, timeout=timeout
)
element.click()
return
self.open(self.__get_href_from_link_text(link_text))
return
if self.browser == "safari":
if self.demo_mode:
self.wait_for_link_text_present(link_text, timeout=timeout)
try:
self.__jquery_slow_scroll_to(link_text, by=By.LINK_TEXT)
except Exception:
element = self.wait_for_link_text_visible(
link_text, timeout=timeout
)
self.__slow_scroll_to_element(element)
o_bs = "" # original_box_shadow
loops = settings.HIGHLIGHTS
selector = self.convert_to_css_selector(
link_text, by=By.LINK_TEXT
)
selector = self.__make_css_match_first_element_only(selector)
try:
selector = re.escape(selector)
selector = self.__escape_quotes_if_needed(selector)
self.__highlight_with_jquery(selector, loops, o_bs)
except Exception:
pass # JQuery probably couldn't load. Skip highlighting.
self.__jquery_click(link_text, by=By.LINK_TEXT)
return
if not self.is_link_text_present(link_text):
self.wait_for_link_text_present(link_text, timeout=timeout)
pre_action_url = self.get_current_url()
try:
element = self.wait_for_link_text_visible(link_text, timeout=0.2)
self.__demo_mode_highlight_if_active(link_text, by=By.LINK_TEXT)
try:
element.click()
except (StaleElementReferenceException, ENI_Exception):
self.wait_for_ready_state_complete()
time.sleep(0.16)
element = self.wait_for_link_text_visible(
link_text, timeout=timeout
)
element.click()
except Exception:
found_css = False
text_id = self.get_link_attribute(link_text, "id", False)
if text_id:
link_css = '[id="%s"]' % link_text
found_css = True
if not found_css:
href = self.__get_href_from_link_text(link_text, False)
if href:
if href.startswith("/") or page_utils.is_valid_url(href):
link_css = '[href="%s"]' % href
found_css = True
if not found_css:
ngclick = self.get_link_attribute(link_text, "ng-click", False)
if ngclick:
link_css = '[ng-click="%s"]' % ngclick
found_css = True
if not found_css:
onclick = self.get_link_attribute(link_text, "onclick", False)
if onclick:
link_css = '[onclick="%s"]' % onclick
found_css = True
success = False
if found_css:
if self.is_element_visible(link_css):
self.click(link_css)
success = True
else:
# The link text might be hidden under a dropdown menu
success = self.__click_dropdown_link_text(
link_text, link_css
)
if not success:
element = self.wait_for_link_text_visible(
link_text, timeout=settings.MINI_TIMEOUT
)
element.click()
latest_window_count = len(self.driver.window_handles)
if (
latest_window_count > pre_window_count
and (
self.recorder_mode
or (
settings.SWITCH_TO_NEW_TABS_ON_CLICK
and self.driver.current_url == pre_action_url
)
)
):
self.__switch_to_newest_window_if_not_blank()
if settings.WAIT_FOR_RSC_ON_PAGE_LOADS:
self.wait_for_ready_state_complete()
if self.demo_mode:
if self.driver.current_url != pre_action_url:
self.__demo_mode_pause_if_active()
else:
self.__demo_mode_pause_if_active(tiny=True)
elif self.slow_mode:
self.__slow_mode_pause_if_active()
def click_partial_link_text(self, partial_link_text, timeout=None):
""" This method clicks the partial link text on a page. """
# If using phantomjs, might need to extract and open the link directly
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
if self.browser == "phantomjs":
if self.is_partial_link_text_visible(partial_link_text):
element = self.wait_for_partial_link_text(partial_link_text)
element.click()
return
soup = self.get_beautiful_soup()
html_links = soup.fetch("a")
for html_link in html_links:
if partial_link_text in html_link.text:
for html_attribute in html_link.attrs:
if html_attribute[0] == "href":
href = html_attribute[1]
if href.startswith("//"):
link = "http:" + href
elif href.startswith("/"):
url = self.driver.current_url
domain_url = self.get_domain_url(url)
link = domain_url + href
else:
link = href
self.open(link)
return
raise Exception(
"Could not parse link from partial link_text "
"{%s}" % partial_link_text
)
raise Exception(
"Partial link text {%s} was not found!" % partial_link_text
)
if not self.is_partial_link_text_present(partial_link_text):
self.wait_for_partial_link_text_present(
partial_link_text, timeout=timeout
)
pre_action_url = self.driver.current_url
pre_window_count = len(self.driver.window_handles)
try:
element = self.wait_for_partial_link_text(
partial_link_text, timeout=0.2
)
self.__demo_mode_highlight_if_active(
partial_link_text, by=By.LINK_TEXT
)
try:
element.click()
except (StaleElementReferenceException, ENI_Exception):
self.wait_for_ready_state_complete()
time.sleep(0.16)
element = self.wait_for_partial_link_text(
partial_link_text, timeout=timeout
)
element.click()
except Exception:
found_css = False
text_id = self.get_partial_link_text_attribute(
partial_link_text, "id", False
)
if text_id:
link_css = '[id="%s"]' % partial_link_text
found_css = True
if not found_css:
href = self.__get_href_from_partial_link_text(
partial_link_text, False
)
if href:
if href.startswith("/") or page_utils.is_valid_url(href):
link_css = '[href="%s"]' % href
found_css = True
if not found_css:
ngclick = self.get_partial_link_text_attribute(
partial_link_text, "ng-click", False
)
if ngclick:
link_css = '[ng-click="%s"]' % ngclick
found_css = True
if not found_css:
onclick = self.get_partial_link_text_attribute(
partial_link_text, "onclick", False
)
if onclick:
link_css = '[onclick="%s"]' % onclick
found_css = True
success = False
if found_css:
if self.is_element_visible(link_css):
self.click(link_css)
success = True
else:
# The link text might be hidden under a dropdown menu
success = self.__click_dropdown_partial_link_text(
partial_link_text, link_css
)
if not success:
element = self.wait_for_partial_link_text(
partial_link_text, timeout=settings.MINI_TIMEOUT
)
element.click()
latest_window_count = len(self.driver.window_handles)
if (
latest_window_count > pre_window_count
and (
self.recorder_mode
or (
settings.SWITCH_TO_NEW_TABS_ON_CLICK
and self.driver.current_url == pre_action_url
)
)
):
self.__switch_to_newest_window_if_not_blank()
if settings.WAIT_FOR_RSC_ON_PAGE_LOADS:
self.wait_for_ready_state_complete()
if self.demo_mode:
if self.driver.current_url != pre_action_url:
self.__demo_mode_pause_if_active()
else:
self.__demo_mode_pause_if_active(tiny=True)
elif self.slow_mode:
self.__slow_mode_pause_if_active()
def get_text(self, selector, by=By.CSS_SELECTOR, timeout=None):
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
if self.__is_shadow_selector(selector):
return self.__get_shadow_text(selector)
self.wait_for_ready_state_complete()
time.sleep(0.01)
element = page_actions.wait_for_element_visible(
self.driver, selector, by, timeout
)
try:
element_text = element.text
except (StaleElementReferenceException, ENI_Exception):
self.wait_for_ready_state_complete()
time.sleep(0.14)
element = page_actions.wait_for_element_visible(
self.driver, selector, by, timeout
)
element_text = element.text
return element_text
def get_attribute(
self,
selector,
attribute,
by=By.CSS_SELECTOR,
timeout=None,
hard_fail=True,
):
""" This method uses JavaScript to get the value of an attribute. """
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
self.wait_for_ready_state_complete()
time.sleep(0.01)
element = page_actions.wait_for_element_present(
self.driver, selector, by, timeout
)
try:
attribute_value = element.get_attribute(attribute)
except (StaleElementReferenceException, ENI_Exception):
self.wait_for_ready_state_complete()
time.sleep(0.14)
element = page_actions.wait_for_element_present(
self.driver, selector, by, timeout
)
attribute_value = element.get_attribute(attribute)
if attribute_value is not None:
return attribute_value
else:
if hard_fail:
raise Exception(
"Element {%s} has no attribute {%s}!"
% (selector, attribute)
)
else:
return None
def set_attribute(
self,
selector,
attribute,
value,
by=By.CSS_SELECTOR,
timeout=None,
scroll=False,
):
"""This method uses JavaScript to set/update an attribute.
Only the first matching selector from querySelector() is used."""
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
if scroll and self.is_element_visible(selector, by=by):
try:
self.scroll_to(selector, by=by, timeout=timeout)
except Exception:
pass
attribute = re.escape(attribute)
attribute = self.__escape_quotes_if_needed(attribute)
value = re.escape(value)
value = self.__escape_quotes_if_needed(value)
css_selector = self.convert_to_css_selector(selector, by=by)
css_selector = re.escape(css_selector) # Add "\\" to special chars
css_selector = self.__escape_quotes_if_needed(css_selector)
script = (
"""document.querySelector('%s').setAttribute('%s','%s');"""
% (css_selector, attribute, value)
)
self.execute_script(script)
def set_attributes(self, selector, attribute, value, by=By.CSS_SELECTOR):
"""This method uses JavaScript to set/update a common attribute.
All matching selectors from querySelectorAll() are used.
Example => (Make all links on a website redirect to Google):
self.set_attributes("a", "href", "https://google.com")"""
self.__check_scope()
selector, by = self.__recalculate_selector(selector, by)
attribute = re.escape(attribute)
attribute = self.__escape_quotes_if_needed(attribute)
value = re.escape(value)
value = self.__escape_quotes_if_needed(value)
css_selector = self.convert_to_css_selector(selector, by=by)
css_selector = re.escape(css_selector) # Add "\\" to special chars
css_selector = self.__escape_quotes_if_needed(css_selector)
script = """var $elements = document.querySelectorAll('%s');
var index = 0, length = $elements.length;
for(; index < length; index++){
$elements[index].setAttribute('%s','%s');}""" % (
css_selector,
attribute,
value,
)
try:
self.execute_script(script)
except Exception:
pass
def set_attribute_all(
self, selector, attribute, value, by=By.CSS_SELECTOR
):
"""Same as set_attributes(), but using querySelectorAll naming scheme.
This method uses JavaScript to set/update a common attribute.
All matching selectors from querySelectorAll() are used.
Example => (Make all links on a website redirect to Google):
self.set_attribute_all("a", "href", "https://google.com")"""
self.set_attributes(selector, attribute, value, by=by)
def remove_attribute(
self, selector, attribute, by=By.CSS_SELECTOR, timeout=None
):
"""This method uses JavaScript to remove an attribute.
Only the first matching selector from querySelector() is used."""
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
if self.is_element_visible(selector, by=by):
try:
self.scroll_to(selector, by=by, timeout=timeout)
except Exception:
pass
attribute = re.escape(attribute)
attribute = self.__escape_quotes_if_needed(attribute)
css_selector = self.convert_to_css_selector(selector, by=by)
css_selector = re.escape(css_selector) # Add "\\" to special chars
css_selector = self.__escape_quotes_if_needed(css_selector)
script = """document.querySelector('%s').removeAttribute('%s');""" % (
css_selector,
attribute,
)
self.execute_script(script)
def remove_attributes(self, selector, attribute, by=By.CSS_SELECTOR):
"""This method uses JavaScript to remove a common attribute.
All matching selectors from querySelectorAll() are used."""
self.__check_scope()
selector, by = self.__recalculate_selector(selector, by)
attribute = re.escape(attribute)
attribute = self.__escape_quotes_if_needed(attribute)
css_selector = self.convert_to_css_selector(selector, by=by)
css_selector = re.escape(css_selector) # Add "\\" to special chars
css_selector = self.__escape_quotes_if_needed(css_selector)
script = """var $elements = document.querySelectorAll('%s');
var index = 0, length = $elements.length;
for(; index < length; index++){
$elements[index].removeAttribute('%s');}""" % (
css_selector,
attribute,
)
try:
self.execute_script(script)
except Exception:
pass
def get_property_value(
self, selector, property, by=By.CSS_SELECTOR, timeout=None
):
"""Returns the property value of a page element's computed style.
Example:
opacity = self.get_property_value("html body a", "opacity")
self.assertTrue(float(opacity) > 0, "Element not visible!")"""
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
self.wait_for_ready_state_complete()
page_actions.wait_for_element_present(
self.driver, selector, by, timeout
)
try:
selector = self.convert_to_css_selector(selector, by=by)
except Exception:
# Don't run action if can't convert to CSS_Selector for JavaScript
raise Exception(
"Exception: Could not convert {%s}(by=%s) to CSS_SELECTOR!"
% (selector, by)
)
selector = re.escape(selector)
selector = self.__escape_quotes_if_needed(selector)
script = """var $elm = document.querySelector('%s');
$val = window.getComputedStyle($elm).getPropertyValue('%s');
return $val;""" % (
selector,
property,
)
value = self.execute_script(script)
if value is not None:
return value
else:
return "" # Return an empty string if the property doesn't exist
def get_image_url(self, selector, by=By.CSS_SELECTOR, timeout=None):
""" Extracts the URL from an image element on the page. """
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
return self.get_attribute(
selector, attribute="src", by=by, timeout=timeout
)
def find_elements(self, selector, by=By.CSS_SELECTOR, limit=0):
"""Returns a list of matching WebElements.
Elements could be either hidden or visible on the page.
If "limit" is set and > 0, will only return that many elements."""
selector, by = self.__recalculate_selector(selector, by)
self.wait_for_ready_state_complete()
time.sleep(0.05)
elements = self.driver.find_elements(by=by, value=selector)
if limit and limit > 0 and len(elements) > limit:
elements = elements[:limit]
return elements
def find_visible_elements(self, selector, by=By.CSS_SELECTOR, limit=0):
"""Returns a list of matching WebElements that are visible.
If "limit" is set and > 0, will only return that many elements."""
selector, by = self.__recalculate_selector(selector, by)
self.wait_for_ready_state_complete()
time.sleep(0.05)
v_elems = page_actions.find_visible_elements(self.driver, selector, by)
if limit and limit > 0 and len(v_elems) > limit:
v_elems = v_elems[:limit]
return v_elems
def click_visible_elements(
self, selector, by=By.CSS_SELECTOR, limit=0, timeout=None
):
"""Finds all matching page elements and clicks visible ones in order.
If a click reloads or opens a new page, the clicking will stop.
If no matching elements appear, an Exception will be raised.
If "limit" is set and > 0, will only click that many elements.
Also clicks elements that become visible from previous clicks.
Works best for actions such as clicking all checkboxes on a page.
Example: self.click_visible_elements('input[type="checkbox"]')"""
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
self.wait_for_element_present(selector, by=by, timeout=timeout)
elements = self.find_elements(selector, by=by)
if self.browser == "safari":
if not limit:
limit = 0
num_elements = len(elements)
if num_elements == 0:
raise Exception(
"No matching elements found for selector {%s}!" % selector
)
elif num_elements < limit or limit == 0:
limit = num_elements
selector, by = self.__recalculate_selector(selector, by)
css_selector = self.convert_to_css_selector(selector, by=by)
last_css_chunk = css_selector.split(" ")[-1]
if ":" in last_css_chunk:
self.__js_click_all(css_selector)
self.wait_for_ready_state_complete()
return
else:
for i in range(1, limit + 1):
new_selector = css_selector + ":nth-of-type(%s)" % str(i)
if self.is_element_visible(new_selector):
self.__js_click(new_selector)
self.wait_for_ready_state_complete()
return
pre_action_url = self.driver.current_url
pre_window_count = len(self.driver.window_handles)
click_count = 0
for element in elements:
if limit and limit > 0 and click_count >= limit:
return
try:
if element.is_displayed():
self.__scroll_to_element(element)
element.click()
click_count += 1
self.wait_for_ready_state_complete()
except ECI_Exception:
continue # ElementClickInterceptedException (Overlay likely)
except (StaleElementReferenceException, ENI_Exception):
self.wait_for_ready_state_complete()
time.sleep(0.12)
try:
if element.is_displayed():
self.__scroll_to_element(element)
element.click()
click_count += 1
self.wait_for_ready_state_complete()
except (StaleElementReferenceException, ENI_Exception):
latest_window_count = len(self.driver.window_handles)
if (
latest_window_count > pre_window_count
and (
self.recorder_mode
or (
settings.SWITCH_TO_NEW_TABS_ON_CLICK
and self.driver.current_url == pre_action_url
)
)
):
self.__switch_to_newest_window_if_not_blank()
return # Probably on new page / Elements are all stale
latest_window_count = len(self.driver.window_handles)
if (
latest_window_count > pre_window_count
and (
self.recorder_mode
or (
settings.SWITCH_TO_NEW_TABS_ON_CLICK
and self.driver.current_url == pre_action_url
)
)
):
self.__switch_to_newest_window_if_not_blank()
def click_nth_visible_element(
self, selector, number, by=By.CSS_SELECTOR, timeout=None
):
"""Finds all matching page elements and clicks the nth visible one.
Example: self.click_nth_visible_element('[type="checkbox"]', 5)
(Clicks the 5th visible checkbox on the page.)"""
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
self.wait_for_ready_state_complete()
self.wait_for_element_present(selector, by=by, timeout=timeout)
elements = self.find_visible_elements(selector, by=by)
if len(elements) < number:
raise Exception(
"Not enough matching {%s} elements of type {%s} to "
"click number %s!" % (selector, by, number)
)
number = number - 1
if number < 0:
number = 0
element = elements[number]
pre_action_url = self.driver.current_url
pre_window_count = len(self.driver.window_handles)
try:
self.__scroll_to_element(element)
element.click()
except (StaleElementReferenceException, ENI_Exception):
time.sleep(0.12)
self.wait_for_ready_state_complete()
self.wait_for_element_present(selector, by=by, timeout=timeout)
elements = self.find_visible_elements(selector, by=by)
if len(elements) < number:
raise Exception(
"Not enough matching {%s} elements of type {%s} to "
"click number %s!" % (selector, by, number)
)
number = number - 1
if number < 0:
number = 0
element = elements[number]
element.click()
latest_window_count = len(self.driver.window_handles)
if (
latest_window_count > pre_window_count
and (
self.recorder_mode
or (
settings.SWITCH_TO_NEW_TABS_ON_CLICK
and self.driver.current_url == pre_action_url
)
)
):
self.__switch_to_newest_window_if_not_blank()
def click_if_visible(self, selector, by=By.CSS_SELECTOR):
"""If the page selector exists and is visible, clicks on the element.
This method only clicks on the first matching element found.
(Use click_visible_elements() to click all matching elements.)"""
self.wait_for_ready_state_complete()
if self.is_element_visible(selector, by=by):
self.click(selector, by=by)
def click_active_element(self):
self.wait_for_ready_state_complete()
pre_action_url = self.driver.current_url
pre_window_count = len(self.driver.window_handles)
self.execute_script("document.activeElement.click();")
latest_window_count = len(self.driver.window_handles)
if (
latest_window_count > pre_window_count
and (
self.recorder_mode
or (
settings.SWITCH_TO_NEW_TABS_ON_CLICK
and self.driver.current_url == pre_action_url
)
)
):
self.__switch_to_newest_window_if_not_blank()
if settings.WAIT_FOR_RSC_ON_CLICKS:
self.wait_for_ready_state_complete()
else:
# A smaller subset of self.wait_for_ready_state_complete()
self.wait_for_angularjs(timeout=settings.MINI_TIMEOUT)
if self.driver.current_url != pre_action_url:
self.__ad_block_as_needed()
if self.demo_mode:
if self.driver.current_url != pre_action_url:
self.__demo_mode_pause_if_active()
else:
self.__demo_mode_pause_if_active(tiny=True)
elif self.slow_mode:
self.__slow_mode_pause_if_active()
def is_checked(self, selector, by=By.CSS_SELECTOR, timeout=None):
"""Determines if a checkbox or a radio button element is checked.
Returns True if the element is checked.
Returns False if the element is not checked.
If the element is not present on the page, raises an exception.
If the element is not a checkbox or radio, raises an exception."""
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
kind = self.get_attribute(selector, "type", by=by, timeout=timeout)
if kind != "checkbox" and kind != "radio":
raise Exception("Expecting a checkbox or a radio button element!")
is_checked = self.get_attribute(
selector, "checked", by=by, timeout=timeout, hard_fail=False
)
if is_checked:
return True
else: # (NoneType)
return False
def is_selected(self, selector, by=By.CSS_SELECTOR, timeout=None):
""" Same as is_checked() """
return self.is_checked(selector, by=by, timeout=timeout)
def check_if_unchecked(self, selector, by=By.CSS_SELECTOR):
""" If a checkbox or radio button is not checked, will check it. """
self.__check_scope()
selector, by = self.__recalculate_selector(selector, by)
if not self.is_checked(selector, by=by):
if self.is_element_visible(selector, by=by):
self.click(selector, by=by)
else:
selector = self.convert_to_css_selector(selector, by=by)
self.__dont_record_js_click = True
self.js_click(selector, by=By.CSS_SELECTOR)
self.__dont_record_js_click = False
def select_if_unselected(self, selector, by=By.CSS_SELECTOR):
""" Same as check_if_unchecked() """
self.check_if_unchecked(selector, by=by)
def uncheck_if_checked(self, selector, by=By.CSS_SELECTOR):
""" If a checkbox is checked, will uncheck it. """
self.__check_scope()
selector, by = self.__recalculate_selector(selector, by)
if self.is_checked(selector, by=by):
if self.is_element_visible(selector, by=by):
self.click(selector, by=by)
else:
selector = self.convert_to_css_selector(selector, by=by)
self.__dont_record_js_click = True
self.js_click(selector, by=By.CSS_SELECTOR)
self.__dont_record_js_click = False
def unselect_if_selected(self, selector, by=By.CSS_SELECTOR):
""" Same as uncheck_if_checked() """
self.uncheck_if_checked(selector, by=by)
def is_element_in_an_iframe(self, selector, by=By.CSS_SELECTOR):
"""Returns True if the selector's element is located in an iframe.
Otherwise returns False."""
self.__check_scope()
selector, by = self.__recalculate_selector(selector, by)
if self.is_element_present(selector, by=by):
return False
soup = self.get_beautiful_soup()
iframe_list = soup.select("iframe")
for iframe in iframe_list:
iframe_identifier = None
if iframe.has_attr("name") and len(iframe["name"]) > 0:
iframe_identifier = iframe["name"]
elif iframe.has_attr("id") and len(iframe["id"]) > 0:
iframe_identifier = iframe["id"]
elif iframe.has_attr("class") and len(iframe["class"]) > 0:
iframe_class = " ".join(iframe["class"])
iframe_identifier = '[class="%s"]' % iframe_class
else:
continue
self.switch_to_frame(iframe_identifier)
if self.is_element_present(selector, by=by):
self.switch_to_default_content()
return True
self.switch_to_default_content()
return False
def switch_to_frame_of_element(self, selector, by=By.CSS_SELECTOR):
"""Set driver control to the iframe containing element (assuming the
element is in a single-nested iframe) and returns the iframe name.
If element is not in an iframe, returns None, and nothing happens.
May not work if multiple iframes are nested within each other."""
self.__check_scope()
selector, by = self.__recalculate_selector(selector, by)
if self.is_element_present(selector, by=by):
return None
soup = self.get_beautiful_soup()
iframe_list = soup.select("iframe")
for iframe in iframe_list:
iframe_identifier = None
if iframe.has_attr("name") and len(iframe["name"]) > 0:
iframe_identifier = iframe["name"]
elif iframe.has_attr("id") and len(iframe["id"]) > 0:
iframe_identifier = iframe["id"]
elif iframe.has_attr("class") and len(iframe["class"]) > 0:
iframe_class = " ".join(iframe["class"])
iframe_identifier = '[class="%s"]' % iframe_class
else:
continue
try:
self.switch_to_frame(iframe_identifier, timeout=1)
if self.is_element_present(selector, by=by):
return iframe_identifier
except Exception:
pass
self.switch_to_default_content()
try:
self.switch_to_frame(selector, timeout=1)
return selector
except Exception:
if self.is_element_present(selector, by=by):
return ""
raise Exception(
"Could not switch to iframe containing "
"element {%s}!" % selector
)
def hover_on_element(self, selector, by=By.CSS_SELECTOR):
self.__check_scope()
original_selector = selector
original_by = by
selector, by = self.__recalculate_selector(selector, by)
if page_utils.is_xpath_selector(selector):
selector = self.convert_to_css_selector(selector, By.XPATH)
by = By.CSS_SELECTOR
self.wait_for_element_visible(
selector, by=by, timeout=settings.SMALL_TIMEOUT
)
self.__demo_mode_highlight_if_active(original_selector, original_by)
self.scroll_to(selector, by=by)
time.sleep(0.05) # Settle down from scrolling before hovering
if self.browser != "chrome":
return page_actions.hover_on_element(self.driver, selector)
# Using Chrome
# (Pure hover actions won't work on early chromedriver versions)
try:
return page_actions.hover_on_element(self.driver, selector)
except WebDriverException as e:
driver_capabilities = self.driver.__dict__["capabilities"]
if "version" in driver_capabilities:
chrome_version = driver_capabilities["version"]
else:
chrome_version = driver_capabilities["browserVersion"]
major_chrome_version = chrome_version.split(".")[0]
chrome_dict = self.driver.__dict__["capabilities"]["chrome"]
chromedriver_version = chrome_dict["chromedriverVersion"]
chromedriver_version = chromedriver_version.split(" ")[0]
major_chromedriver_version = chromedriver_version.split(".")[0]
install_sb = (
"seleniumbase install chromedriver %s" % major_chrome_version
)
if major_chromedriver_version < major_chrome_version:
# Upgrading the driver is required for performing hover actions
message = (
"\n"
"You need a newer chromedriver to perform hover actions!\n"
"Your version of chromedriver is: %s\n"
"And your version of Chrome is: %s\n"
"You can fix this issue by running:\n>>> %s\n"
% (chromedriver_version, chrome_version, install_sb)
)
raise Exception(message)
else:
raise Exception(e)
def hover_and_click(
self,
hover_selector,
click_selector,
hover_by=By.CSS_SELECTOR,
click_by=By.CSS_SELECTOR,
timeout=None,
):
"""When you want to hover over an element or dropdown menu,
and then click an element that appears after that."""
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
original_selector = hover_selector
original_by = hover_by
hover_selector, hover_by = self.__recalculate_selector(
hover_selector, hover_by
)
hover_selector = self.convert_to_css_selector(hover_selector, hover_by)
hover_by = By.CSS_SELECTOR
click_selector, click_by = self.__recalculate_selector(
click_selector, click_by
)
dropdown_element = self.wait_for_element_visible(
hover_selector, by=hover_by, timeout=timeout
)
self.__demo_mode_highlight_if_active(original_selector, original_by)
self.scroll_to(hover_selector, by=hover_by)
pre_action_url = self.driver.current_url
pre_window_count = len(self.driver.window_handles)
if self.recorder_mode:
url = self.get_current_url()
if url and len(url) > 0:
if ("http:") in url or ("https:") in url or ("file:") in url:
if self.get_session_storage_item("pause_recorder") == "no":
time_stamp = self.execute_script("return Date.now();")
origin = self.get_origin()
the_selectors = [hover_selector, click_selector]
action = ["ho_cl", the_selectors, origin, time_stamp]
self.__extra_actions.append(action)
outdated_driver = False
element = None
try:
if self.mobile_emulator:
# On mobile, click to hover the element
dropdown_element.click()
elif self.browser == "safari":
# Use the workaround for hover-clicking on Safari
raise Exception("This Exception will be caught.")
else:
page_actions.hover_element(self.driver, dropdown_element)
except Exception:
outdated_driver = True
element = self.wait_for_element_present(
click_selector, click_by, timeout
)
if click_by == By.LINK_TEXT:
self.open(self.__get_href_from_link_text(click_selector))
elif click_by == By.PARTIAL_LINK_TEXT:
self.open(
self.__get_href_from_partial_link_text(click_selector)
)
else:
self.__dont_record_js_click = True
self.js_click(click_selector, by=click_by)
self.__dont_record_js_click = False
if outdated_driver:
pass # Already did the click workaround
elif self.mobile_emulator:
self.click(click_selector, by=click_by)
elif not outdated_driver:
element = page_actions.hover_and_click(
self.driver,
hover_selector,
click_selector,
hover_by,
click_by,
timeout,
)
latest_window_count = len(self.driver.window_handles)
if (
latest_window_count > pre_window_count
and (
self.recorder_mode
or (
settings.SWITCH_TO_NEW_TABS_ON_CLICK
and self.driver.current_url == pre_action_url
)
)
):
self.__switch_to_newest_window_if_not_blank()
if self.demo_mode:
if self.driver.current_url != pre_action_url:
self.__demo_mode_pause_if_active()
else:
self.__demo_mode_pause_if_active(tiny=True)
elif self.slow_mode:
self.__slow_mode_pause_if_active()
return element
def hover_and_double_click(
self,
hover_selector,
click_selector,
hover_by=By.CSS_SELECTOR,
click_by=By.CSS_SELECTOR,
timeout=None,
):
"""When you want to hover over an element or dropdown menu,
and then double-click an element that appears after that."""
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
original_selector = hover_selector
original_by = hover_by
hover_selector, hover_by = self.__recalculate_selector(
hover_selector, hover_by
)
hover_selector = self.convert_to_css_selector(hover_selector, hover_by)
hover_by = By.CSS_SELECTOR
click_selector, click_by = self.__recalculate_selector(
click_selector, click_by
)
dropdown_element = self.wait_for_element_visible(
hover_selector, by=hover_by, timeout=timeout
)
self.__demo_mode_highlight_if_active(original_selector, original_by)
self.scroll_to(hover_selector, by=hover_by)
pre_action_url = self.driver.current_url
pre_window_count = len(self.driver.window_handles)
outdated_driver = False
element = None
try:
page_actions.hover_element(self.driver, dropdown_element)
except Exception:
outdated_driver = True
element = self.wait_for_element_present(
click_selector, click_by, timeout
)
if click_by == By.LINK_TEXT:
self.open(self.__get_href_from_link_text(click_selector))
elif click_by == By.PARTIAL_LINK_TEXT:
self.open(
self.__get_href_from_partial_link_text(click_selector)
)
else:
self.__dont_record_js_click = True
self.js_click(click_selector, click_by)
self.__dont_record_js_click = False
if not outdated_driver:
element = page_actions.hover_element_and_double_click(
self.driver,
dropdown_element,
click_selector,
click_by=By.CSS_SELECTOR,
timeout=timeout,
)
latest_window_count = len(self.driver.window_handles)
if (
latest_window_count > pre_window_count
and (
self.recorder_mode
or (
settings.SWITCH_TO_NEW_TABS_ON_CLICK
and self.driver.current_url == pre_action_url
)
)
):
self.__switch_to_newest_window_if_not_blank()
if self.demo_mode:
if self.driver.current_url != pre_action_url:
self.__demo_mode_pause_if_active()
else:
self.__demo_mode_pause_if_active(tiny=True)
elif self.slow_mode:
self.__slow_mode_pause_if_active()
return element
def drag_and_drop(
self,
drag_selector,
drop_selector,
drag_by=By.CSS_SELECTOR,
drop_by=By.CSS_SELECTOR,
timeout=None,
):
""" Drag and drop an element from one selector to another. """
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
drag_selector, drag_by = self.__recalculate_selector(
drag_selector, drag_by
)
drop_selector, drop_by = self.__recalculate_selector(
drop_selector, drop_by
)
drag_element = self.wait_for_element_visible(
drag_selector, by=drag_by, timeout=timeout
)
self.__demo_mode_highlight_if_active(drag_selector, drag_by)
self.wait_for_element_visible(
drop_selector, by=drop_by, timeout=timeout
)
self.__demo_mode_highlight_if_active(drop_selector, drop_by)
self.scroll_to(drag_selector, by=drag_by)
drag_selector = self.convert_to_css_selector(drag_selector, drag_by)
drop_selector = self.convert_to_css_selector(drop_selector, drop_by)
drag_and_drop_script = js_utils.get_drag_and_drop_script()
self.safe_execute_script(
drag_and_drop_script
+ (
"$('%s').simulateDragDrop("
"{dropTarget: "
"'%s'});" % (drag_selector, drop_selector)
)
)
if self.demo_mode:
self.__demo_mode_pause_if_active()
elif self.slow_mode:
self.__slow_mode_pause_if_active()
return drag_element
def drag_and_drop_with_offset(
self, selector, x, y, by=By.CSS_SELECTOR, timeout=None
):
""" Drag and drop an element to an {X,Y}-offset location. """
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
css_selector = self.convert_to_css_selector(selector, by=by)
element = self.wait_for_element_visible(css_selector, timeout=timeout)
self.__demo_mode_highlight_if_active(css_selector, By.CSS_SELECTOR)
css_selector = re.escape(css_selector) # Add "\\" to special chars
css_selector = self.__escape_quotes_if_needed(css_selector)
script = js_utils.get_drag_and_drop_with_offset_script(
css_selector, x, y
)
self.safe_execute_script(script)
if self.demo_mode:
self.__demo_mode_pause_if_active()
elif self.slow_mode:
self.__slow_mode_pause_if_active()
return element
def __select_option(
self,
dropdown_selector,
option,
dropdown_by=By.CSS_SELECTOR,
option_by="text",
timeout=None,
):
"""Selects an HTML <select> option by specification.
Option specifications are by "text", "index", or "value".
Defaults to "text" if option_by is unspecified or unknown."""
from selenium.webdriver.support.ui import Select
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
dropdown_selector, dropdown_by = self.__recalculate_selector(
dropdown_selector, dropdown_by
)
self.wait_for_ready_state_complete()
element = self.wait_for_element_present(
dropdown_selector, by=dropdown_by, timeout=timeout
)
if self.is_element_visible(dropdown_selector, by=dropdown_by):
self.__demo_mode_highlight_if_active(
dropdown_selector, dropdown_by
)
pre_action_url = self.driver.current_url
pre_window_count = len(self.driver.window_handles)
try:
if option_by == "index":
Select(element).select_by_index(option)
elif option_by == "value":
Select(element).select_by_value(option)
else:
Select(element).select_by_visible_text(option)
except (StaleElementReferenceException, ENI_Exception):
self.wait_for_ready_state_complete()
time.sleep(0.14)
element = self.wait_for_element_present(
dropdown_selector, by=dropdown_by, timeout=timeout
)
if option_by == "index":
Select(element).select_by_index(option)
elif option_by == "value":
Select(element).select_by_value(option)
else:
Select(element).select_by_visible_text(option)
latest_window_count = len(self.driver.window_handles)
if (
latest_window_count > pre_window_count
and (
self.recorder_mode
or (
settings.SWITCH_TO_NEW_TABS_ON_CLICK
and self.driver.current_url == pre_action_url
)
)
):
self.__switch_to_newest_window_if_not_blank()
if settings.WAIT_FOR_RSC_ON_CLICKS:
self.wait_for_ready_state_complete()
else:
# A smaller subset of self.wait_for_ready_state_complete()
self.wait_for_angularjs(timeout=settings.MINI_TIMEOUT)
if self.demo_mode:
if self.driver.current_url != pre_action_url:
self.__demo_mode_pause_if_active()
else:
self.__demo_mode_pause_if_active(tiny=True)
elif self.slow_mode:
self.__slow_mode_pause_if_active()
def select_option_by_text(
self,
dropdown_selector,
option,
dropdown_by=By.CSS_SELECTOR,
timeout=None,
):
"""Selects an HTML <select> option by option text.
@Params
dropdown_selector - the <select> selector.
option - the text of the option.
"""
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
self.__select_option(
dropdown_selector,
option,
dropdown_by=dropdown_by,
option_by="text",
timeout=timeout,
)
def select_option_by_index(
self,
dropdown_selector,
option,
dropdown_by=By.CSS_SELECTOR,
timeout=None,
):
"""Selects an HTML <select> option by option index.
@Params
dropdown_selector - the <select> selector.
option - the index number of the option.
"""
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
self.__select_option(
dropdown_selector,
option,
dropdown_by=dropdown_by,
option_by="index",
timeout=timeout,
)
def select_option_by_value(
self,
dropdown_selector,
option,
dropdown_by=By.CSS_SELECTOR,
timeout=None,
):
"""Selects an HTML <select> option by option value.
@Params
dropdown_selector - the <select> selector.
option - the value property of the option.
"""
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
self.__select_option(
dropdown_selector,
option,
dropdown_by=dropdown_by,
option_by="value",
timeout=timeout,
)
def load_html_string(self, html_string, new_page=True):
"""Loads an HTML string into the web browser.
If new_page==True, the page will switch to: "data:text/html,"
If new_page==False, will load HTML into the current page."""
self.__check_scope()
soup = self.get_beautiful_soup(html_string)
found_base = False
links = soup.findAll("link")
href = None
for link in links:
if link.get("rel") == ["canonical"] and link.get("href"):
found_base = True
href = link.get("href")
href = self.get_domain_url(href)
if (
found_base
and html_string.count("<head>") == 1
and html_string.count("<base") == 0
):
html_string = html_string.replace(
"<head>", '<head><base href="%s">' % href
)
elif not found_base:
bases = soup.findAll("base")
for base in bases:
if base.get("href"):
href = base.get("href")
if href:
html_string = html_string.replace('base: "."', 'base: "%s"' % href)
soup = self.get_beautiful_soup(html_string)
scripts = soup.findAll("script")
for script in scripts:
if script.get("type") != "application/json":
html_string = html_string.replace(str(script), "")
soup = self.get_beautiful_soup(html_string)
found_head = False
found_body = False
html_head = None
html_body = None
if soup.head and len(str(soup.head)) > 12:
found_head = True
html_head = str(soup.head)
html_head = re.escape(html_head)
html_head = self.__escape_quotes_if_needed(html_head)
html_head = html_head.replace("\\ ", " ")
if soup.body and len(str(soup.body)) > 12:
found_body = True
html_body = str(soup.body)
html_body = html_body.replace("\xc2\xa0", " ")
html_body = html_body.replace("\xc2\xa1", "¡")
html_body = html_body.replace("\xc2\xa9", "©")
html_body = html_body.replace("\xc2\xb7", "·")
html_body = html_body.replace("\xc2\xbf", "¿")
html_body = html_body.replace("\xc3\x97", "×")
html_body = html_body.replace("\xc3\xb7", "÷")
html_body = re.escape(html_body)
html_body = self.__escape_quotes_if_needed(html_body)
html_body = html_body.replace("\\ ", " ")
html_string = re.escape(html_string)
html_string = self.__escape_quotes_if_needed(html_string)
html_string = html_string.replace("\\ ", " ")
if new_page:
self.open("data:text/html,")
inner_head = """document.getElementsByTagName("head")[0].innerHTML"""
inner_body = """document.getElementsByTagName("body")[0].innerHTML"""
if not found_body:
self.execute_script('''%s = \"%s\"''' % (inner_body, html_string))
elif found_body and not found_head:
self.execute_script('''%s = \"%s\"''' % (inner_body, html_body))
elif found_body and found_head:
self.execute_script('''%s = \"%s\"''' % (inner_head, html_head))
self.execute_script('''%s = \"%s\"''' % (inner_body, html_body))
else:
raise Exception("Logic Error!")
for script in scripts:
js_code = script.string
js_src = script.get("src")
if js_code and script.get("type") != "application/json":
js_code_lines = js_code.split("\n")
new_lines = []
for line in js_code_lines:
line = line.strip()
new_lines.append(line)
js_code = "\n".join(new_lines)
js_code = re.escape(js_code)
js_utils.add_js_code(self.driver, js_code)
elif js_src:
js_utils.add_js_link(self.driver, js_src)
else:
pass
def set_content(self, html_string, new_page=False):
""" Same as load_html_string(), but "new_page" defaults to False. """
self.load_html_string(html_string, new_page=new_page)
def load_html_file(self, html_file, new_page=True):
"""Loads a local html file into the browser from a relative file path.
If new_page==True, the page will switch to: "data:text/html,"
If new_page==False, will load HTML into the current page.
Local images and other local src content WILL BE IGNORED.
"""
self.__check_scope()
if self.__looks_like_a_page_url(html_file):
self.open(html_file)
return
if len(html_file) < 6 or not html_file.endswith(".html"):
raise Exception('Expecting a ".html" file!')
abs_path = os.path.abspath(".")
file_path = None
if abs_path in html_file:
file_path = html_file
else:
file_path = abs_path + "/%s" % html_file
html_string = None
with open(file_path, "r") as f:
html_string = f.read().strip()
self.load_html_string(html_string, new_page)
def open_html_file(self, html_file):
"""Opens a local html file into the browser from a relative file path.
The URL displayed in the web browser will start with "file://".
"""
self.__check_scope()
if self.__looks_like_a_page_url(html_file):
self.open(html_file)
return
if len(html_file) < 6 or not html_file.endswith(".html"):
raise Exception('Expecting a ".html" file!')
abs_path = os.path.abspath(".")
file_path = None
if abs_path in html_file:
file_path = html_file
else:
file_path = abs_path + "/%s" % html_file
self.open("file://" + file_path)
def execute_script(self, script, *args, **kwargs):
self.__check_scope()
self.__check_browser()
if not python3:
script = unicode(script.decode('latin-1')) # noqa: F821
return self.driver.execute_script(script, *args, **kwargs)
def execute_async_script(self, script, timeout=None):
self.__check_scope()
self.__check_browser()
if not timeout:
timeout = settings.EXTREME_TIMEOUT
return js_utils.execute_async_script(self.driver, script, timeout)
def safe_execute_script(self, script, *args, **kwargs):
"""When executing a script that contains a jQuery command,
it's important that the jQuery library has been loaded first.
This method will load jQuery if it wasn't already loaded."""
self.__check_scope()
self.__check_browser()
if not js_utils.is_jquery_activated(self.driver):
self.activate_jquery()
return self.driver.execute_script(script, *args, **kwargs)
def set_window_rect(self, x, y, width, height):
self.__check_scope()
self.driver.set_window_rect(x, y, width, height)
self.__demo_mode_pause_if_active()
def set_window_size(self, width, height):
self.__check_scope()
self.driver.set_window_size(width, height)
self.__demo_mode_pause_if_active()
def maximize_window(self):
self.__check_scope()
self.driver.maximize_window()
self.__demo_mode_pause_if_active()
def switch_to_frame(self, frame, timeout=None):
"""Wait for an iframe to appear, and switch to it. This should be
usable as a drop-in replacement for driver.switch_to.frame().
The iframe identifier can be a selector, an index, an id, a name,
or a web element, but scrolling to the iframe first will only occur
for visible iframes with a string selector.
@Params
frame - the frame element, name, id, index, or selector
timeout - the time to wait for the alert in seconds
"""
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
if type(frame) is str and self.is_element_visible(frame):
try:
self.scroll_to(frame, timeout=1)
except Exception:
pass
if self.recorder_mode and self._rec_overrides_switch:
url = self.get_current_url()
if url and len(url) > 0:
if ("http:") in url or ("https:") in url or ("file:") in url:
r_a = self.get_session_storage_item("recorder_activated")
if r_a == "yes":
time_stamp = self.execute_script("return Date.now();")
origin = self.get_origin()
action = ["sk_op", "", origin, time_stamp]
self.__extra_actions.append(action)
self.__set_c_from_switch = True
self.set_content_to_frame(frame, timeout=timeout)
self.__set_c_from_switch = False
time_stamp = self.execute_script("return Date.now();")
origin = self.get_origin()
action = ["sw_fr", frame, origin, time_stamp]
self.__extra_actions.append(action)
return
page_actions.switch_to_frame(self.driver, frame, timeout)
def switch_to_default_content(self):
"""Brings driver control outside the current iframe.
(If the driver control is inside an iframe, the driver control
will be set to one level above the current frame. If the driver
control is not currently in an iframe, nothing will happen.)"""
self.__check_scope()
if self.recorder_mode and self._rec_overrides_switch:
url = self.get_current_url()
if url and len(url) > 0:
if ("http:") in url or ("https:") in url or ("file:") in url:
r_a = self.get_session_storage_item("recorder_activated")
if r_a == "yes":
self.__set_c_from_switch = True
self.set_content_to_default()
self.__set_c_from_switch = False
time_stamp = self.execute_script("return Date.now();")
origin = self.get_origin()
action = ["sw_dc", "", origin, time_stamp]
self.__extra_actions.append(action)
return
self.driver.switch_to.default_content()
def set_content_to_frame(self, frame, timeout=None):
"""Replaces the page html with an iframe's html from that page.
If the iFrame contains an "src" field that includes a valid URL,
then instead of replacing the current html, this method will then
open up the "src" URL of the iFrame in a new browser tab.
To return to default content, use: self.set_content_to_default().
This method also sets the state of the browser window so that the
self.set_content_to_default() method can bring the user back to
the original content displayed, which is similar to how the methods
self.switch_to_frame(frame) and self.switch_to_default_content()
work together to get the user into frames and out of all of them.
"""
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
current_url = self.get_current_url()
c_tab = self.driver.current_window_handle
current_page_source = self.get_page_source()
self.execute_script("document.cframe_swap = 0;")
page_actions.switch_to_frame(self.driver, frame, timeout)
iframe_html = self.get_page_source()
self.driver.switch_to.default_content()
self.wait_for_ready_state_complete()
frame_found = False
o_frame = frame
if self.is_element_present(frame):
frame_found = True
elif " " not in frame:
frame = 'iframe[name="%s"]' % frame
if self.is_element_present(frame):
frame_found = True
url = None
if frame_found:
url = self.execute_script(
"""return document.querySelector('%s').src;""" % frame
)
if not python3:
url = str(url)
if url and len(url) > 0:
if ("http:") in url or ("https:") in url or ("file:") in url:
pass
else:
url = None
cframe_tab = False
if url:
cframe_tab = True
self.__page_sources.append([current_url, current_page_source, c_tab])
if self.recorder_mode and not self.__set_c_from_switch:
time_stamp = self.execute_script("return Date.now();")
origin = self.get_origin()
action = ["sk_op", "", origin, time_stamp]
self.__extra_actions.append(action)
if cframe_tab:
self.execute_script("document.cframe_tab = 1;")
self.open_new_window(switch_to=True)
self.open(url)
self.execute_script("document.cframe_tab = 1;")
else:
self.set_content(iframe_html)
if not self.execute_script("return document.cframe_swap;"):
self.execute_script("document.cframe_swap = 1;")
else:
self.execute_script("document.cframe_swap += 1;")
if self.recorder_mode and not self.__set_c_from_switch:
time_stamp = self.execute_script("return Date.now();")
origin = self.get_origin()
action = ["s_c_f", o_frame, origin, time_stamp]
self.__extra_actions.append(action)
def set_content_to_default(self, nested=True):
"""After using self.set_content_to_frame(), this reverts the page back.
If self.set_content_to_frame() hasn't been called here, only refreshes.
If "nested" is set to False when the content was set to nested iFrames,
then the control will only move above the last iFrame that was entered.
"""
self.__check_scope()
swap_cnt = self.execute_script("return document.cframe_swap;")
tab_sta = self.execute_script("return document.cframe_tab;")
if self.recorder_mode and not self.__set_c_from_switch:
time_stamp = self.execute_script("return Date.now();")
origin = self.get_origin()
action = ["sk_op", "", origin, time_stamp]
self.__extra_actions.append(action)
if nested:
if (
len(self.__page_sources) > 0
and (
(swap_cnt and int(swap_cnt) > 0)
or (tab_sta and int(tab_sta) > 0)
)
):
past_content = self.__page_sources[0]
past_url = past_content[0]
past_source = past_content[1]
past_tab = past_content[2]
current_tab = self.driver.current_window_handle
if not current_tab == past_tab:
if past_tab in self.driver.window_handles:
self.switch_to_window(past_tab)
url_of_past_tab = self.get_current_url()
if url_of_past_tab == past_url:
self.set_content(past_source)
else:
self.refresh_page()
else:
self.refresh_page()
self.execute_script("document.cframe_swap = 0;")
self.__page_sources = []
else:
just_refresh = False
if swap_cnt and int(swap_cnt) > 0 and len(self.__page_sources) > 0:
self.execute_script("document.cframe_swap -= 1;")
current_url = self.get_current_url()
past_content = self.__page_sources.pop()
past_url = past_content[0]
past_source = past_content[1]
if current_url == past_url:
self.set_content(past_source)
else:
just_refresh = True
elif tab_sta and int(tab_sta) > 0 and len(self.__page_sources) > 0:
past_content = self.__page_sources.pop()
past_tab = past_content[2]
if past_tab in self.driver.window_handles:
self.switch_to_window(past_tab)
else:
just_refresh = True
else:
just_refresh = True
if just_refresh:
self.refresh_page()
self.execute_script("document.cframe_swap = 0;")
self.__page_sources = []
if self.recorder_mode and not self.__set_c_from_switch:
time_stamp = self.execute_script("return Date.now();")
origin = self.get_origin()
action = ["s_c_d", nested, origin, time_stamp]
self.__extra_actions.append(action)
def open_new_window(self, switch_to=True):
""" Opens a new browser tab/window and switches to it by default. """
self.__check_scope()
self.__check_browser() # Current window must exist to open a new one
self.driver.execute_script("window.open('');")
time.sleep(0.01)
if switch_to:
self.switch_to_newest_window()
time.sleep(0.01)
if self.browser == "safari":
self.wait_for_ready_state_complete()
def switch_to_window(self, window, timeout=None):
""" Switches control of the browser to the specified window.
The window can be an integer: 0 -> 1st tab, 1 -> 2nd tab, etc...
Or it can be a list item from self.driver.window_handles """
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
page_actions.switch_to_window(self.driver, window, timeout)
def switch_to_default_window(self):
self.switch_to_window(0)
def __switch_to_newest_window_if_not_blank(self):
current_window = self.driver.current_window_handle
try:
self.switch_to_window(len(self.driver.window_handles) - 1)
if self.get_current_url() == "about:blank":
self.switch_to_window(current_window)
except Exception:
self.switch_to_window(current_window)
def switch_to_newest_window(self):
self.switch_to_window(len(self.driver.window_handles) - 1)
def get_new_driver(
self,
browser=None,
headless=None,
locale_code=None,
protocol=None,
servername=None,
port=None,
proxy=None,
proxy_bypass_list=None,
agent=None,
switch_to=True,
cap_file=None,
cap_string=None,
recorder_ext=None,
disable_csp=None,
enable_ws=None,
enable_sync=None,
use_auto_ext=None,
no_sandbox=None,
disable_gpu=None,
incognito=None,
guest_mode=None,
devtools=None,
remote_debug=None,
swiftshader=None,
ad_block_on=None,
block_images=None,
chromium_arg=None,
firefox_arg=None,
firefox_pref=None,
user_data_dir=None,
extension_zip=None,
extension_dir=None,
is_mobile=None,
d_width=None,
d_height=None,
d_p_r=None,
):
"""This method spins up an extra browser for tests that require
more than one. The first browser is already provided by tests
that import base_case.BaseCase from seleniumbase. If parameters
aren't specified, the method uses the same as the default driver.
@Params
browser - the browser to use. (Ex: "chrome", "firefox")
headless - the option to run webdriver in headless mode
locale_code - the Language Locale Code for the web browser
protocol - if using a Selenium Grid, set the host protocol here
servername - if using a Selenium Grid, set the host address here
port - if using a Selenium Grid, set the host port here
proxy - if using a proxy server, specify the "host:port" combo here
proxy_bypass_list - ";"-separated hosts to bypass (Eg. "*.foo.com")
switch_to - the option to switch to the new driver (default = True)
cap_file - the file containing desired capabilities for the browser
cap_string - the string with desired capabilities for the browser
recorder_ext - the option to enable the SBase Recorder extension
disable_csp - an option to disable Chrome's Content Security Policy
enable_ws - the option to enable the Web Security feature (Chrome)
enable_sync - the option to enable the Chrome Sync feature (Chrome)
use_auto_ext - the option to enable Chrome's Automation Extension
no_sandbox - the option to enable the "No-Sandbox" feature (Chrome)
disable_gpu - the option to enable Chrome's "Disable GPU" feature
incognito - the option to enable Chrome's Incognito mode (Chrome)
guest - the option to enable Chrome's Guest mode (Chrome)
devtools - the option to open Chrome's DevTools on start (Chrome)
remote_debug - the option to enable Chrome's Remote Debugger
swiftshader - the option to use Chrome's swiftshader (Chrome-only)
ad_block_on - the option to block ads from loading (Chromium-only)
block_images - the option to block images from loading (Chrome)
chromium_arg - the option to add a Chromium arg to Chrome/Edge
firefox_arg - the option to add a Firefox arg to Firefox runs
firefox_pref - the option to add a Firefox pref:value set (Firefox)
user_data_dir - Chrome's User Data Directory to use (Chrome-only)
extension_zip - A Chrome Extension ZIP file to use (Chrome-only)
extension_dir - A Chrome Extension folder to use (Chrome-only)
is_mobile - the option to use the mobile emulator (Chrome-only)
d_width - the device width of the mobile emulator (Chrome-only)
d_height - the device height of the mobile emulator (Chrome-only)
d_p_r - the device pixel ratio of the mobile emulator (Chrome-only)
"""
self.__check_scope()
if self.browser == "remote" and self.servername == "localhost":
raise Exception(
'Cannot use "remote" browser driver on localhost!'
" Did you mean to connect to a remote Grid server"
" such as BrowserStack or Sauce Labs? In that"
' case, you must specify the "server" and "port"'
" parameters on the command line! "
"Example: "
"--server=user:[email protected] --port=80"
)
browserstack_ref = "https://browserstack.com/automate/capabilities"
sauce_labs_ref = (
"https://wiki.saucelabs.com/display/DOCS/Platform+Configurator#/"
)
if self.browser == "remote" and not (self.cap_file or self.cap_string):
raise Exception(
"Need to specify a desired capabilities file when "
'using "--browser=remote". Add "--cap_file=FILE". '
"File should be in the Python format used by: "
"%s OR "
"%s "
"See SeleniumBase/examples/sample_cap_file_BS.py "
"and SeleniumBase/examples/sample_cap_file_SL.py"
% (browserstack_ref, sauce_labs_ref)
)
if browser is None:
browser = self.browser
browser_name = browser
if headless is None:
headless = self.headless
if locale_code is None:
locale_code = self.locale_code
if protocol is None:
protocol = self.protocol
if servername is None:
servername = self.servername
if port is None:
port = self.port
use_grid = False
if servername != "localhost":
# Use Selenium Grid (Use "127.0.0.1" for localhost Grid)
use_grid = True
proxy_string = proxy
if proxy_string is None:
proxy_string = self.proxy_string
if proxy_bypass_list is None:
proxy_bypass_list = self.proxy_bypass_list
user_agent = agent
if user_agent is None:
user_agent = self.user_agent
if recorder_ext is None:
recorder_ext = self.recorder_ext
if disable_csp is None:
disable_csp = self.disable_csp
if enable_ws is None:
enable_ws = self.enable_ws
if enable_sync is None:
enable_sync = self.enable_sync
if use_auto_ext is None:
use_auto_ext = self.use_auto_ext
if no_sandbox is None:
no_sandbox = self.no_sandbox
if disable_gpu is None:
disable_gpu = self.disable_gpu
if incognito is None:
incognito = self.incognito
if guest_mode is None:
guest_mode = self.guest_mode
if devtools is None:
devtools = self.devtools
if remote_debug is None:
remote_debug = self.remote_debug
if swiftshader is None:
swiftshader = self.swiftshader
if ad_block_on is None:
ad_block_on = self.ad_block_on
if block_images is None:
block_images = self.block_images
if chromium_arg is None:
chromium_arg = self.chromium_arg
if firefox_arg is None:
firefox_arg = self.firefox_arg
if firefox_pref is None:
firefox_pref = self.firefox_pref
if user_data_dir is None:
user_data_dir = self.user_data_dir
if extension_zip is None:
extension_zip = self.extension_zip
if extension_dir is None:
extension_dir = self.extension_dir
test_id = self.__get_test_id()
if cap_file is None:
cap_file = self.cap_file
if cap_string is None:
cap_string = self.cap_string
if is_mobile is None:
is_mobile = self.mobile_emulator
if d_width is None:
d_width = self.__device_width
if d_height is None:
d_height = self.__device_height
if d_p_r is None:
d_p_r = self.__device_pixel_ratio
valid_browsers = constants.ValidBrowsers.valid_browsers
if browser_name not in valid_browsers:
raise Exception(
"Browser: {%s} is not a valid browser option. "
"Valid options = {%s}" % (browser, valid_browsers)
)
# Launch a web browser
from seleniumbase.core import browser_launcher
new_driver = browser_launcher.get_driver(
browser_name=browser_name,
headless=headless,
locale_code=locale_code,
use_grid=use_grid,
protocol=protocol,
servername=servername,
port=port,
proxy_string=proxy_string,
proxy_bypass_list=proxy_bypass_list,
user_agent=user_agent,
cap_file=cap_file,
cap_string=cap_string,
recorder_ext=recorder_ext,
disable_csp=disable_csp,
enable_ws=enable_ws,
enable_sync=enable_sync,
use_auto_ext=use_auto_ext,
no_sandbox=no_sandbox,
disable_gpu=disable_gpu,
incognito=incognito,
guest_mode=guest_mode,
devtools=devtools,
remote_debug=remote_debug,
swiftshader=swiftshader,
ad_block_on=ad_block_on,
block_images=block_images,
chromium_arg=chromium_arg,
firefox_arg=firefox_arg,
firefox_pref=firefox_pref,
user_data_dir=user_data_dir,
extension_zip=extension_zip,
extension_dir=extension_dir,
test_id=test_id,
mobile_emulator=is_mobile,
device_width=d_width,
device_height=d_height,
device_pixel_ratio=d_p_r,
)
self._drivers_list.append(new_driver)
self.__driver_browser_map[new_driver] = browser_name
if switch_to:
self.driver = new_driver
self.browser = browser_name
if self.headless or self.xvfb:
# Make sure the invisible browser window is big enough
width = settings.HEADLESS_START_WIDTH
height = settings.HEADLESS_START_HEIGHT
try:
self.driver.set_window_size(width, height)
self.wait_for_ready_state_complete()
except Exception:
# This shouldn't fail, but in case it does,
# get safely through setUp() so that
# WebDrivers can get closed during tearDown().
pass
else:
if self.browser == "chrome" or self.browser == "edge":
width = settings.CHROME_START_WIDTH
height = settings.CHROME_START_HEIGHT
try:
if self.maximize_option:
self.driver.maximize_window()
else:
self.driver.set_window_size(width, height)
self.wait_for_ready_state_complete()
except Exception:
pass # Keep existing browser resolution
elif self.browser == "firefox":
width = settings.CHROME_START_WIDTH
try:
if self.maximize_option:
self.driver.maximize_window()
else:
self.driver.set_window_size(width, 720)
self.wait_for_ready_state_complete()
except Exception:
pass # Keep existing browser resolution
elif self.browser == "safari":
width = settings.CHROME_START_WIDTH
if self.maximize_option:
try:
self.driver.maximize_window()
self.wait_for_ready_state_complete()
except Exception:
pass # Keep existing browser resolution
else:
try:
self.driver.set_window_rect(10, 30, width, 630)
except Exception:
pass
elif self.browser == "opera":
width = settings.CHROME_START_WIDTH
if self.maximize_option:
try:
self.driver.maximize_window()
self.wait_for_ready_state_complete()
except Exception:
pass # Keep existing browser resolution
else:
try:
self.driver.set_window_rect(10, 30, width, 700)
except Exception:
pass
if self.start_page and len(self.start_page) >= 4:
if page_utils.is_valid_url(self.start_page):
self.open(self.start_page)
else:
new_start_page = "https://" + self.start_page
if page_utils.is_valid_url(new_start_page):
self.__dont_record_open = True
self.open(new_start_page)
self.__dont_record_open = False
return new_driver
def switch_to_driver(self, driver):
"""Switches control of the browser to the specified driver.
Also sets the self.driver variable to the specified driver.
You may need this if using self.get_new_driver() in your code."""
self.__check_scope()
self.driver = driver
if self.driver in self.__driver_browser_map:
self.browser = self.__driver_browser_map[self.driver]
def switch_to_default_driver(self):
""" Sets self.driver to the default/original driver. """
self.__check_scope()
self.driver = self._default_driver
if self.driver in self.__driver_browser_map:
self.browser = self.__driver_browser_map[self.driver]
def save_screenshot(
self, name, folder=None, selector=None, by=By.CSS_SELECTOR
):
"""
Saves a screenshot of the current page.
If no folder is specified, uses the folder where pytest was called.
The screenshot will include the entire page unless a selector is given.
If a provided selector is not found, then takes a full-page screenshot.
If the folder provided doesn't exist, it will get created.
The screenshot will be in PNG format: (*.png)
"""
self.wait_for_ready_state_complete()
if selector and by:
selector, by = self.__recalculate_selector(selector, by)
if page_actions.is_element_present(self.driver, selector, by):
return page_actions.save_screenshot(
self.driver, name, folder, selector, by
)
return page_actions.save_screenshot(self.driver, name, folder)
def save_screenshot_to_logs(
self, name=None, selector=None, by=By.CSS_SELECTOR
):
"""Saves a screenshot of the current page to the "latest_logs" folder.
Naming is automatic:
If NO NAME provided: "_1_screenshot.png", "_2_screenshot.png", etc.
If NAME IS provided, it becomes: "_1_name.png", "_2_name.png", etc.
The screenshot will include the entire page unless a selector is given.
If a provided selector is not found, then takes a full-page screenshot.
(The last_page / failure screenshot is always "screenshot.png")
The screenshot will be in PNG format."""
self.wait_for_ready_state_complete()
test_logpath = os.path.join(self.log_path, self.__get_test_id())
self.__create_log_path_as_needed(test_logpath)
if name:
name = str(name)
self.__screenshot_count += 1
if not name or len(name) == 0:
name = "_%s_screenshot.png" % self.__screenshot_count
else:
pre_name = "_%s_" % self.__screenshot_count
if len(name) >= 4 and name[-4:].lower() == ".png":
name = name[:-4]
if len(name) == 0:
name = "screenshot"
name = "%s%s.png" % (pre_name, name)
if selector and by:
selector, by = self.__recalculate_selector(selector, by)
if page_actions.is_element_present(self.driver, selector, by):
return page_actions.save_screenshot(
self.driver, name, test_logpath, selector, by
)
if self.recorder_mode:
url = self.get_current_url()
if url and len(url) > 0:
if ("http:") in url or ("https:") in url or ("file:") in url:
if self.get_session_storage_item("pause_recorder") == "no":
time_stamp = self.execute_script("return Date.now();")
origin = self.get_origin()
action = ["ss_tl", "", origin, time_stamp]
self.__extra_actions.append(action)
return page_actions.save_screenshot(self.driver, name, test_logpath)
def save_page_source(self, name, folder=None):
"""Saves the page HTML to the current directory (or given subfolder).
If the folder specified doesn't exist, it will get created.
@Params
name - The file name to save the current page's HTML to.
folder - The folder to save the file to. (Default = current folder)
"""
self.wait_for_ready_state_complete()
return page_actions.save_page_source(self.driver, name, folder)
def save_cookies(self, name="cookies.txt"):
""" Saves the page cookies to the "saved_cookies" folder. """
self.wait_for_ready_state_complete()
cookies = self.driver.get_cookies()
json_cookies = json.dumps(cookies)
if name.endswith("/"):
raise Exception("Invalid filename for Cookies!")
if "/" in name:
name = name.split("/")[-1]
if len(name) < 1:
raise Exception("Filename for Cookies is too short!")
if not name.endswith(".txt"):
name = name + ".txt"
folder = constants.SavedCookies.STORAGE_FOLDER
abs_path = os.path.abspath(".")
file_path = abs_path + "/%s" % folder
if not os.path.exists(file_path):
os.makedirs(file_path)
cookies_file_path = "%s/%s" % (file_path, name)
cookies_file = codecs.open(cookies_file_path, "w+", encoding="utf-8")
cookies_file.writelines(json_cookies)
cookies_file.close()
def load_cookies(self, name="cookies.txt"):
""" Loads the page cookies from the "saved_cookies" folder. """
self.wait_for_ready_state_complete()
if name.endswith("/"):
raise Exception("Invalid filename for Cookies!")
if "/" in name:
name = name.split("/")[-1]
if len(name) < 1:
raise Exception("Filename for Cookies is too short!")
if not name.endswith(".txt"):
name = name + ".txt"
folder = constants.SavedCookies.STORAGE_FOLDER
abs_path = os.path.abspath(".")
file_path = abs_path + "/%s" % folder
cookies_file_path = "%s/%s" % (file_path, name)
json_cookies = None
with open(cookies_file_path, "r") as f:
json_cookies = f.read().strip()
cookies = json.loads(json_cookies)
for cookie in cookies:
if "expiry" in cookie:
del cookie["expiry"]
self.driver.add_cookie(cookie)
def delete_all_cookies(self):
"""Deletes all cookies in the web browser.
Does NOT delete the saved cookies file."""
self.wait_for_ready_state_complete()
self.driver.delete_all_cookies()
def delete_saved_cookies(self, name="cookies.txt"):
"""Deletes the cookies file from the "saved_cookies" folder.
Does NOT delete the cookies from the web browser."""
self.wait_for_ready_state_complete()
if name.endswith("/"):
raise Exception("Invalid filename for Cookies!")
if "/" in name:
name = name.split("/")[-1]
if len(name) < 1:
raise Exception("Filename for Cookies is too short!")
if not name.endswith(".txt"):
name = name + ".txt"
folder = constants.SavedCookies.STORAGE_FOLDER
abs_path = os.path.abspath(".")
file_path = abs_path + "/%s" % folder
cookies_file_path = "%s/%s" % (file_path, name)
if os.path.exists(cookies_file_path):
if cookies_file_path.endswith(".txt"):
os.remove(cookies_file_path)
def __ad_block_as_needed(self):
""" This is an internal method for handling ad-blocking.
Use "pytest --ad-block" to enable this during tests.
When not Chromium or in headless mode, use the hack. """
if self.ad_block_on and (self.headless or not self.is_chromium()):
# (Chromium browsers in headed mode use the extension instead)
current_url = self.get_current_url()
if not current_url == self.__last_page_load_url:
if page_actions.is_element_present(
self.driver, "iframe", By.CSS_SELECTOR
):
self.ad_block()
self.__last_page_load_url = current_url
def wait_for_ready_state_complete(self, timeout=None):
""" Waits for the "readyState" of the page to be "complete".
Returns True when the method completes. """
self.__check_scope()
self.__check_browser()
if not timeout:
timeout = settings.EXTREME_TIMEOUT
if self.timeout_multiplier and timeout == settings.EXTREME_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
js_utils.wait_for_ready_state_complete(self.driver, timeout)
self.wait_for_angularjs(timeout=settings.MINI_TIMEOUT)
if self.js_checking_on:
self.assert_no_js_errors()
self.__ad_block_as_needed()
return True
def wait_for_angularjs(self, timeout=None, **kwargs):
""" Waits for Angular components of the page to finish loading.
Returns True when the method completes. """
self.__check_scope()
if not timeout:
timeout = settings.MINI_TIMEOUT
if self.timeout_multiplier and timeout == settings.MINI_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
js_utils.wait_for_angularjs(self.driver, timeout, **kwargs)
return True
def sleep(self, seconds):
self.__check_scope()
if not sb_config.time_limit:
time.sleep(seconds)
elif seconds < 0.4:
shared_utils.check_if_time_limit_exceeded()
time.sleep(seconds)
shared_utils.check_if_time_limit_exceeded()
else:
start_ms = time.time() * 1000.0
stop_ms = start_ms + (seconds * 1000.0)
for x in range(int(seconds * 5)):
shared_utils.check_if_time_limit_exceeded()
now_ms = time.time() * 1000.0
if now_ms >= stop_ms:
break
time.sleep(0.2)
def install_addon(self, xpi_file):
"""Installs a Firefox add-on instantly at run-time.
@Params
xpi_file - A file archive in .xpi format.
"""
self.wait_for_ready_state_complete()
if self.browser != "firefox":
raise Exception(
"install_addon(xpi_file) is for Firefox ONLY!\n"
"To load a Chrome extension, use the comamnd-line:\n"
"--extension_zip=CRX_FILE OR --extension_dir=DIR"
)
xpi_path = os.path.abspath(xpi_file)
self.driver.install_addon(xpi_path, temporary=True)
def activate_demo_mode(self):
self.demo_mode = True
def deactivate_demo_mode(self):
self.demo_mode = False
def activate_design_mode(self):
# Activate Chrome's Design Mode, which lets you edit a site directly.
# See: https://twitter.com/sulco/status/1177559150563344384
self.wait_for_ready_state_complete()
script = """document.designMode = 'on';"""
self.execute_script(script)
def deactivate_design_mode(self):
# Deactivate Chrome's Design Mode.
self.wait_for_ready_state_complete()
script = """document.designMode = 'off';"""
self.execute_script(script)
def activate_recorder(self):
from seleniumbase.js_code.recorder_js import recorder_js
if not self.is_chromium():
raise Exception(
"The Recorder is only for Chromium browsers: (Chrome or Edge)")
url = self.driver.current_url
if (
url.startswith("data:") or url.startswith("about:")
or url.startswith("chrome:") or url.startswith("edge:")
):
message = (
'The URL in Recorder-Mode cannot start with: '
'"data:", "about:", "chrome:", or "edge:"!')
print("\n" + message)
return
if self.recorder_ext:
return # The Recorder extension is already active
try:
recorder_on = self.get_session_storage_item("recorder_activated")
if not recorder_on == "yes":
self.execute_script(recorder_js)
self.recorder_mode = True
message = "Recorder Mode ACTIVE. [ESC]: Pause. [~`]: Resume."
print("\n" + message)
p_msg = "Recorder Mode ACTIVE.<br>[ESC]: Pause. [~`]: Resume."
self.post_message(p_msg, pause=False, style="error")
except Exception:
pass
def save_recorded_actions(self):
"""(When using Recorder Mode, use this method if you plan on
navigating to a different domain/origin in the same tab.)
This method saves recorded actions from the active tab so that
a complete recording can be exported as a SeleniumBase file at the
end of the test. This is only needed in special cases because most
actions that result in a new origin, (such as clicking on a link),
should automatically open a new tab while Recorder Mode is enabled."""
url = self.get_current_url()
if url and len(url) > 0:
if ("http:") in url or ("https:") in url or ("file:") in url:
origin = self.get_origin()
self.__origins_to_save.append(origin)
tab_actions = self.__get_recorded_actions_on_active_tab()
self.__actions_to_save.append(tab_actions)
def __get_recorded_actions_on_active_tab(self):
url = self.driver.current_url
if (
url.startswith("data:") or url.startswith("about:")
or url.startswith("chrome:") or url.startswith("edge:")
):
return []
actions = self.get_session_storage_item('recorded_actions')
if actions:
actions = json.loads(actions)
return actions
else:
return []
def __process_recorded_actions(self):
import colorama
raw_actions = [] # All raw actions from sessionStorage
srt_actions = []
cleaned_actions = []
sb_actions = []
used_actions = []
action_dict = {}
for window in self.driver.window_handles:
self.switch_to_window(window)
tab_actions = self.__get_recorded_actions_on_active_tab()
for action in tab_actions:
if action not in used_actions:
used_actions.append(action)
raw_actions.append(action)
for tab_actions in self.__actions_to_save:
for action in tab_actions:
if action not in used_actions:
used_actions.append(action)
raw_actions.append(action)
for action in self.__extra_actions:
if action not in used_actions:
used_actions.append(action)
raw_actions.append(action)
for action in raw_actions:
if self._reuse_session:
if int(action[3]) < int(self.__js_start_time):
continue
# Use key for sorting and preventing duplicates
key = str(action[3]) + "-" + str(action[0])
action_dict[key] = action
for key in sorted(action_dict):
# print(action_dict[key]) # For debugging purposes
srt_actions.append(action_dict[key])
for n in range(len(srt_actions)):
if (
(srt_actions[n][0] == "begin" or srt_actions[n][0] == "_url_")
and n > 0
and srt_actions[n-1][0] == "sk_op"
):
srt_actions[n][0] = "_skip"
for n in range(len(srt_actions)):
if (
(srt_actions[n][0] == "begin" or srt_actions[n][0] == "_url_")
and n > 1
and srt_actions[n-1][0] == "_skip"
and srt_actions[n-2][0] == "sk_op"
and srt_actions[n][2] == srt_actions[n-1][2]
):
srt_actions[n][0] = "_skip"
for n in range(len(srt_actions)):
if (
(srt_actions[n][0] == "begin" or srt_actions[n][0] == "_url_")
and n > 0
and (
srt_actions[n-1][0] == "click"
or srt_actions[n-1][0] == "js_cl"
or srt_actions[n-1][0] == "js_ca"
)
):
url1 = srt_actions[n-1][2]
if (
srt_actions[n-1][0] == "js_cl"
or srt_actions[n-1][0] == "js_ca"
):
url1 = srt_actions[n-1][2][0]
if url1.endswith("/#/"):
url1 = url1[:-3]
elif url1.endswith("/"):
url1 = url1[:-1]
url2 = srt_actions[n][2]
if url2.endswith("/#/"):
url2 = url1[:-3]
elif url2.endswith("/"):
url2 = url2[:-1]
if (
url1 == url2
or url1 == url2.replace("www.", "")
or (len(url1) > 0
and (url2.startswith(url1) or "?search" in url1)
and (int(srt_actions[n][3]) - int(
srt_actions[n-1][3]) < 6500))
):
srt_actions[n][0] = "f_url"
for n in range(len(srt_actions)):
if (
(srt_actions[n][0] == "begin" or srt_actions[n][0] == "_url_")
and n > 0
and (
srt_actions[n-1][0] == "begin"
or srt_actions[n-1][0] == "_url_"
)
):
url1 = srt_actions[n-1][2]
if url1.endswith("/#/"):
url1 = url1[:-3]
elif url1.endswith("/"):
url1 = url1[:-1]
url2 = srt_actions[n][2]
if url2.endswith("/#/"):
url2 = url1[:-3]
elif url2.endswith("/"):
url2 = url2[:-1]
if url1.replace("www.", "") == url2.replace("www.", ""):
srt_actions[n-1][0] = "_skip"
elif url2.startswith(url1):
srt_actions[n][0] = "f_url"
for n in range(len(srt_actions)):
if (
srt_actions[n][0] == "input"
and n > 0
and srt_actions[n-1][0] == "input"
and srt_actions[n-1][2] == ""
):
srt_actions[n-1][0] = "_skip"
for n in range(len(srt_actions)):
if (
(srt_actions[n][0] == "begin" or srt_actions[n][0] == "_url_")
and n > 0
and (
srt_actions[n-1][0] == "click"
or srt_actions[n-1][0] == "js_cl"
or srt_actions[n-1][0] == "js_ca"
or srt_actions[n-1][0] == "input"
)
and (int(srt_actions[n][3]) - int(srt_actions[n-1][3]) < 6500)
):
if (
srt_actions[n-1][0] == "click"
or srt_actions[n-1][0] == "js_cl"
or srt_actions[n-1][0] == "js_ca"
):
if (
srt_actions[n-1][1].startswith("input")
or srt_actions[n-1][1].startswith("button")
):
srt_actions[n][0] = "f_url"
elif srt_actions[n-1][0] == "input":
if srt_actions[n-1][2].endswith("\n"):
srt_actions[n][0] = "f_url"
for n in range(len(srt_actions)):
if (
srt_actions[n][0] == "cho_f"
and n > 0
and srt_actions[n-1][0] == "chfil"
):
srt_actions[n-1][0] = "_skip"
srt_actions[n][2] = srt_actions[n-1][1][1]
for n in range(len(srt_actions)):
if (
srt_actions[n][0] == "input"
and n > 0
and srt_actions[n-1][0] == "e_mfa"
):
srt_actions[n][0] = "_skip"
for n in range(len(srt_actions)):
if (
(srt_actions[n][0] == "begin" or srt_actions[n][0] == "_url_")
and n > 0
and (
srt_actions[n-1][0] == "submi"
or srt_actions[n-1][0] == "e_mfa"
)
):
srt_actions[n][0] = "f_url"
origins = []
for n in range(len(srt_actions)):
if (
srt_actions[n][0] == "begin"
or srt_actions[n][0] == "_url_"
or srt_actions[n][0] == "f_url"
):
origin = srt_actions[n][1]
if origin.endswith("/"):
origin = origin[0:-1]
if origin not in origins:
origins.append(origin)
for origin in self.__origins_to_save:
origins.append(origin)
for n in range(len(srt_actions)):
if (
srt_actions[n][0] == "click"
and n > 0
and srt_actions[n-1][0] == "ho_cl"
and srt_actions[n-1][2] in origins
):
srt_actions[n-1][0] = "_skip"
srt_actions[n][0] = "h_clk"
srt_actions[n][1] = srt_actions[n-1][1][0]
srt_actions[n][2] = srt_actions[n-1][1][1]
for n in range(len(srt_actions)):
if srt_actions[n][0] == "chfil" and srt_actions[n][2] in origins:
srt_actions[n][0] = "cho_f"
srt_actions[n][2] = srt_actions[n][1][1]
srt_actions[n][1] = srt_actions[n][1][0]
for n in range(len(srt_actions)):
if (
srt_actions[n][0] == "sh_fc"
and n > 0
and srt_actions[n-1][0] == "sh_fc"
):
srt_actions[n-1][0] = "_skip"
ext_actions = []
ext_actions.append("_url_")
ext_actions.append("js_cl")
ext_actions.append("js_ca")
ext_actions.append("js_ty")
ext_actions.append("as_el")
ext_actions.append("as_ep")
ext_actions.append("asenv")
ext_actions.append("hi_li")
ext_actions.append("as_lt")
ext_actions.append("as_ti")
ext_actions.append("as_df")
ext_actions.append("do_fi")
ext_actions.append("as_at")
ext_actions.append("as_te")
ext_actions.append("as_et")
ext_actions.append("sw_fr")
ext_actions.append("sw_dc")
ext_actions.append("s_c_f")
ext_actions.append("s_c_d")
ext_actions.append("sh_fc")
ext_actions.append("c_l_s")
ext_actions.append("e_mfa")
ext_actions.append("ss_tl")
for n in range(len(srt_actions)):
if srt_actions[n][0] in ext_actions:
origin = srt_actions[n][2]
if (
srt_actions[n][0] == "js_cl"
or srt_actions[n][0] == "js_ca"
):
origin = srt_actions[n][2][1]
if origin.endswith("/"):
origin = origin[0:-1]
if srt_actions[n][0] == "js_ty":
srt_actions[n][2] = srt_actions[n][1][1]
srt_actions[n][1] = srt_actions[n][1][0]
if srt_actions[n][0] == "e_mfa":
srt_actions[n][2] = srt_actions[n][1][1]
srt_actions[n][1] = srt_actions[n][1][0]
if srt_actions[n][0] == "_url_" and origin not in origins:
origins.append(origin)
if origin not in origins:
srt_actions[n][0] = "_skip"
for n in range(len(srt_actions)):
if (
srt_actions[n][0] == "input"
and n > 0
and srt_actions[n-1][0] == "js_ty"
and srt_actions[n][2] == srt_actions[n-1][2]
):
srt_actions[n][0] = "_skip"
for n in range(len(srt_actions)):
cleaned_actions.append(srt_actions[n])
for action in srt_actions:
if action[0] == "begin" or action[0] == "_url_":
if "%" in action[2] and python3:
try:
from urllib.parse import unquote
action[2] = unquote(action[2], errors="strict")
except Exception:
pass
sb_actions.append('self.open("%s")' % action[2])
elif action[0] == "f_url":
if "%" in action[2] and python3:
try:
from urllib.parse import unquote
action[2] = unquote(action[2], errors="strict")
except Exception:
pass
sb_actions.append('self.open_if_not_url("%s")' % action[2])
elif action[0] == "click":
method = "click"
if '"' not in action[1]:
sb_actions.append('self.%s("%s")' % (method, action[1]))
else:
sb_actions.append("self.%s('%s')" % (method, action[1]))
elif action[0] == "js_cl":
method = "js_click"
if '"' not in action[1]:
sb_actions.append('self.%s("%s")' % (method, action[1]))
else:
sb_actions.append("self.%s('%s')" % (method, action[1]))
elif action[0] == "js_ca":
method = "js_click_all"
if '"' not in action[1]:
sb_actions.append('self.%s("%s")' % (method, action[1]))
else:
sb_actions.append("self.%s('%s')" % (method, action[1]))
elif action[0] == "input" or action[0] == "js_ty":
method = "type"
if action[0] == "js_ty":
method = "js_type"
text = action[2].replace("\n", "\\n")
if '"' not in action[1] and '"' not in text:
sb_actions.append('self.%s("%s", "%s")' % (
method, action[1], text))
elif '"' not in action[1] and '"' in text:
sb_actions.append('self.%s("%s", \'%s\')' % (
method, action[1], text))
elif '"' in action[1] and '"' not in text:
sb_actions.append('self.%s(\'%s\', "%s")' % (
method, action[1], text))
elif '"' in action[1] and '"' in text:
sb_actions.append("self.%s('%s', '%s')" % (
method, action[1], text))
elif action[0] == "e_mfa":
method = "enter_mfa_code"
text = action[2].replace("\n", "\\n")
if '"' not in action[1] and '"' not in text:
sb_actions.append('self.%s("%s", "%s")' % (
method, action[1], text))
elif '"' not in action[1] and '"' in text:
sb_actions.append('self.%s("%s", \'%s\')' % (
method, action[1], text))
elif '"' in action[1] and '"' not in text:
sb_actions.append('self.%s(\'%s\', "%s")' % (
method, action[1], text))
elif '"' in action[1] and '"' in text:
sb_actions.append("self.%s('%s', '%s')" % (
method, action[1], text))
elif action[0] == "h_clk":
method = "hover_and_click"
if '"' not in action[1] and '"' not in action[2]:
sb_actions.append('self.%s("%s", "%s")' % (
method, action[1], action[2]))
elif '"' not in action[1] and '"' in action[2]:
sb_actions.append('self.%s("%s", \'%s\')' % (
method, action[1], action[2]))
elif '"' in action[1] and '"' not in action[2]:
sb_actions.append('self.%s(\'%s\', "%s")' % (
method, action[1], action[2]))
elif '"' in action[1] and '"' in action[2]:
sb_actions.append("self.%s('%s', '%s')" % (
method, action[1], action[2]))
elif action[0] == "ddrop":
method = "drag_and_drop"
if '"' not in action[1] and '"' not in action[2]:
sb_actions.append('self.%s("%s", "%s")' % (
method, action[1], action[2]))
elif '"' not in action[1] and '"' in action[2]:
sb_actions.append('self.%s("%s", \'%s\')' % (
method, action[1], action[2]))
elif '"' in action[1] and '"' not in action[2]:
sb_actions.append('self.%s(\'%s\', "%s")' % (
method, action[1], action[2]))
elif '"' in action[1] and '"' in action[2]:
sb_actions.append("self.%s('%s', '%s')" % (
method, action[1], action[2]))
elif action[0] == "s_opt":
method = "select_option_by_text"
if '"' not in action[1] and '"' not in action[2]:
sb_actions.append('self.%s("%s", "%s")' % (
method, action[1], action[2]))
elif '"' not in action[1] and '"' in action[2]:
sb_actions.append('self.%s("%s", \'%s\')' % (
method, action[1], action[2]))
elif '"' in action[1] and '"' not in action[2]:
sb_actions.append('self.%s(\'%s\', "%s")' % (
method, action[1], action[2]))
elif '"' in action[1] and '"' in action[2]:
sb_actions.append("self.%s('%s', '%s')" % (
method, action[1], action[2]))
elif action[0] == "set_v":
method = "set_value"
if '"' not in action[1] and '"' not in action[2]:
sb_actions.append('self.%s("%s", "%s")' % (
method, action[1], action[2]))
elif '"' not in action[1] and '"' in action[2]:
sb_actions.append('self.%s("%s", \'%s\')' % (
method, action[1], action[2]))
elif '"' in action[1] and '"' not in action[2]:
sb_actions.append('self.%s(\'%s\', "%s")' % (
method, action[1], action[2]))
elif '"' in action[1] and '"' in action[2]:
sb_actions.append("self.%s('%s', '%s')" % (
method, action[1], action[2]))
elif action[0] == "cho_f":
method = "choose_file"
action[2] = action[2].replace("\\", "\\\\")
if '"' not in action[1] and '"' not in action[2]:
sb_actions.append('self.%s("%s", "%s")' % (
method, action[1], action[2]))
elif '"' not in action[1] and '"' in action[2]:
sb_actions.append('self.%s("%s", \'%s\')' % (
method, action[1], action[2]))
elif '"' in action[1] and '"' not in action[2]:
sb_actions.append('self.%s(\'%s\', "%s")' % (
method, action[1], action[2]))
elif '"' in action[1] and '"' in action[2]:
sb_actions.append("self.%s('%s', '%s')" % (
method, action[1], action[2]))
elif action[0] == "sw_fr":
method = "switch_to_frame"
if '"' not in action[1]:
sb_actions.append('self.%s("%s")' % (method, action[1]))
else:
sb_actions.append("self.%s('%s')" % (method, action[1]))
elif action[0] == "sw_dc":
sb_actions.append("self.switch_to_default_content()")
elif action[0] == "s_c_f":
method = "set_content_to_frame"
if '"' not in action[1]:
sb_actions.append('self.%s("%s")' % (method, action[1]))
else:
sb_actions.append("self.%s('%s')" % (method, action[1]))
elif action[0] == "s_c_d":
method = "set_content_to_default"
nested = action[1]
if nested:
sb_actions.append("self.%s()" % method)
else:
sb_actions.append("self.%s(nested=False)" % method)
elif action[0] == "as_el":
method = "assert_element"
if '"' not in action[1]:
sb_actions.append('self.%s("%s")' % (method, action[1]))
else:
sb_actions.append("self.%s('%s')" % (method, action[1]))
elif action[0] == "as_ep":
method = "assert_element_present"
if '"' not in action[1]:
sb_actions.append('self.%s("%s")' % (method, action[1]))
else:
sb_actions.append("self.%s('%s')" % (method, action[1]))
elif action[0] == "asenv":
method = "assert_element_not_visible"
if '"' not in action[1]:
sb_actions.append('self.%s("%s")' % (method, action[1]))
else:
sb_actions.append("self.%s('%s')" % (method, action[1]))
elif action[0] == "hi_li":
method = "highlight"
if '"' not in action[1]:
sb_actions.append('self.%s("%s")' % (method, action[1]))
else:
sb_actions.append("self.%s('%s')" % (method, action[1]))
elif action[0] == "as_lt":
method = "assert_link_text"
if '"' not in action[1]:
sb_actions.append('self.%s("%s")' % (method, action[1]))
else:
sb_actions.append("self.%s('%s')" % (method, action[1]))
elif action[0] == "as_ti":
method = "assert_title"
if '"' not in action[1]:
sb_actions.append('self.%s("%s")' % (method, action[1]))
else:
sb_actions.append("self.%s('%s')" % (method, action[1]))
elif action[0] == "as_df":
method = "assert_downloaded_file"
if '"' not in action[1]:
sb_actions.append('self.%s("%s")' % (method, action[1]))
else:
sb_actions.append("self.%s('%s')" % (method, action[1]))
elif action[0] == "do_fi":
method = "download_file"
file_url = action[1][0]
dest = action[1][1]
if not dest:
sb_actions.append('self.%s("%s")' % (
method, file_url))
else:
sb_actions.append('self.%s("%s", "%s")' % (
method, file_url, dest))
elif action[0] == "as_at":
method = "assert_attribute"
if ('"' not in action[1][0]) and action[1][2]:
sb_actions.append('self.%s("%s", "%s", "%s")' % (
method, action[1][0], action[1][1], action[1][2]))
elif ('"' not in action[1][0]) and not action[1][2]:
sb_actions.append('self.%s("%s", "%s")' % (
method, action[1][0], action[1][1]))
elif ('"' in action[1][0]) and action[1][2]:
sb_actions.append('self.%s(\'%s\', "%s", "%s")' % (
method, action[1][0], action[1][1], action[1][2]))
else:
sb_actions.append('self.%s(\'%s\', "%s")' % (
method, action[1][0], action[1][1]))
elif action[0] == "as_te" or action[0] == "as_et":
import unicodedata
action[1][0] = unicodedata.normalize("NFKC", action[1][0])
method = "assert_text"
if action[0] == "as_et":
method = "assert_exact_text"
if action[1][1] != "html":
if '"' not in action[1][0] and '"' not in action[1][1]:
sb_actions.append('self.%s("%s", "%s")' % (
method, action[1][0], action[1][1]))
elif '"' not in action[1][0] and '"' in action[1][1]:
sb_actions.append('self.%s("%s", \'%s\')' % (
method, action[1][0], action[1][1]))
elif '"' in action[1] and '"' not in action[1][1]:
sb_actions.append('self.%s(\'%s\', "%s")' % (
method, action[1][0], action[1][1]))
elif '"' in action[1] and '"' in action[1][1]:
sb_actions.append("self.%s('%s', '%s')" % (
method, action[1][0], action[1][1]))
else:
if '"' not in action[1][0]:
sb_actions.append('self.%s("%s")' % (
method, action[1][0]))
else:
sb_actions.append("self.%s('%s')" % (
method, action[1][0]))
elif action[0] == "ss_tl":
method = "save_screenshot_to_logs"
sb_actions.append('self.%s()' % method)
elif action[0] == "sh_fc":
method = "show_file_choosers"
sb_actions.append('self.%s()' % method)
elif action[0] == "c_l_s":
sb_actions.append("self.clear_local_storage()")
elif action[0] == "c_box":
method = "check_if_unchecked"
if action[2] == "no":
method = "uncheck_if_checked"
if '"' not in action[1]:
sb_actions.append('self.%s("%s")' % (method, action[1]))
else:
sb_actions.append("self.%s('%s')" % (method, action[1]))
filename = self.__get_filename()
new_file = False
data = []
if filename not in sb_config._recorded_actions:
new_file = True
sb_config._recorded_actions[filename] = []
data.append("from seleniumbase import BaseCase")
data.append("")
data.append("")
data.append("class %s(BaseCase):" % self.__class__.__name__)
else:
data = sb_config._recorded_actions[filename]
data.append(" def %s(self):" % self._testMethodName)
if len(sb_actions) > 0:
for action in sb_actions:
data.append(" " + action)
else:
data.append(" pass")
data.append("")
sb_config._recorded_actions[filename] = data
recordings_folder = constants.Recordings.SAVED_FOLDER
if recordings_folder.endswith("/"):
recordings_folder = recordings_folder[:-1]
if not os.path.exists(recordings_folder):
try:
os.makedirs(recordings_folder)
except Exception:
pass
file_name = self.__class__.__module__.split(".")[-1] + "_rec.py"
file_path = "%s/%s" % (recordings_folder, file_name)
out_file = codecs.open(file_path, "w+", "utf-8")
out_file.writelines("\r\n".join(data))
out_file.close()
rec_message = ">>> RECORDING SAVED as: "
if not new_file:
rec_message = ">>> RECORDING ADDED to: "
star_len = len(rec_message) + len(file_path)
try:
terminal_size = os.get_terminal_size().columns
if terminal_size > 30 and star_len > terminal_size:
star_len = terminal_size
except Exception:
pass
stars = "*" * star_len
c1 = ""
c2 = ""
cr = ""
if "linux" not in sys.platform:
colorama.init(autoreset=True)
c1 = colorama.Fore.RED + colorama.Back.LIGHTYELLOW_EX
c2 = colorama.Fore.LIGHTRED_EX + colorama.Back.LIGHTYELLOW_EX
cr = colorama.Style.RESET_ALL
rec_message = rec_message.replace(">>>", c2 + ">>>" + cr)
print("\n\n%s%s%s%s\n%s" % (rec_message, c1, file_path, cr, stars))
def activate_jquery(self):
"""If "jQuery is not defined", use this method to activate it for use.
This happens because jQuery is not always defined on web sites."""
self.wait_for_ready_state_complete()
js_utils.activate_jquery(self.driver)
self.wait_for_ready_state_complete()
def __are_quotes_escaped(self, string):
return js_utils.are_quotes_escaped(string)
def __escape_quotes_if_needed(self, string):
return js_utils.escape_quotes_if_needed(string)
def bring_to_front(self, selector, by=By.CSS_SELECTOR):
"""Updates the Z-index of a page element to bring it into view.
Useful when getting a WebDriverException, such as the one below:
{ Element is not clickable at point (#, #).
Other element would receive the click: ... }"""
self.__check_scope()
selector, by = self.__recalculate_selector(selector, by)
self.wait_for_element_visible(
selector, by=by, timeout=settings.SMALL_TIMEOUT
)
try:
selector = self.convert_to_css_selector(selector, by=by)
except Exception:
# Don't run action if can't convert to CSS_Selector for JavaScript
return
selector = re.escape(selector)
selector = self.__escape_quotes_if_needed(selector)
script = (
"""document.querySelector('%s').style.zIndex = '999999';"""
% selector
)
self.execute_script(script)
def highlight_click(
self, selector, by=By.CSS_SELECTOR, loops=3, scroll=True
):
self.__check_scope()
if not self.demo_mode:
self.highlight(selector, by=by, loops=loops, scroll=scroll)
self.click(selector, by=by)
def highlight_update_text(
self, selector, text, by=By.CSS_SELECTOR, loops=3, scroll=True
):
self.__check_scope()
if not self.demo_mode:
self.highlight(selector, by=by, loops=loops, scroll=scroll)
self.update_text(selector, text, by=by)
def highlight(self, selector, by=By.CSS_SELECTOR, loops=None, scroll=True):
"""This method uses fancy JavaScript to highlight an element.
Used during demo_mode.
@Params
selector - the selector of the element to find
by - the type of selector to search by (Default: CSS)
loops - # of times to repeat the highlight animation
(Default: 4. Each loop lasts for about 0.18s)
scroll - the option to scroll to the element first (Default: True)
"""
self.__check_scope()
selector, by = self.__recalculate_selector(selector, by, xp_ok=False)
element = self.wait_for_element_visible(
selector, by=by, timeout=settings.SMALL_TIMEOUT
)
if not loops:
loops = settings.HIGHLIGHTS
if scroll:
try:
if self.browser != "safari":
scroll_distance = js_utils.get_scroll_distance_to_element(
self.driver, element
)
if abs(scroll_distance) > constants.Values.SSMD:
self.__jquery_slow_scroll_to(selector, by)
else:
self.__slow_scroll_to_element(element)
else:
self.__jquery_slow_scroll_to(selector, by)
except Exception:
self.wait_for_ready_state_complete()
time.sleep(0.12)
element = self.wait_for_element_visible(
selector, by=by, timeout=settings.SMALL_TIMEOUT
)
self.__slow_scroll_to_element(element)
try:
selector = self.convert_to_css_selector(selector, by=by)
except Exception:
# Don't highlight if can't convert to CSS_SELECTOR
return
if self.highlights:
loops = self.highlights
if self.browser == "ie":
loops = 1 # Override previous setting because IE is slow
loops = int(loops)
o_bs = "" # original_box_shadow
try:
style = element.get_attribute("style")
except Exception:
self.wait_for_ready_state_complete()
time.sleep(0.12)
element = self.wait_for_element_visible(
selector, by=By.CSS_SELECTOR, timeout=settings.SMALL_TIMEOUT
)
style = element.get_attribute("style")
if style:
if "box-shadow: " in style:
box_start = style.find("box-shadow: ")
box_end = style.find(";", box_start) + 1
original_box_shadow = style[box_start:box_end]
o_bs = original_box_shadow
orig_selector = selector
if ":contains" not in selector and ":first" not in selector:
selector = re.escape(selector)
selector = self.__escape_quotes_if_needed(selector)
self.__highlight_with_js(selector, loops, o_bs)
else:
selector = self.__make_css_match_first_element_only(selector)
selector = re.escape(selector)
selector = self.__escape_quotes_if_needed(selector)
try:
self.__highlight_with_jquery(selector, loops, o_bs)
except Exception:
pass # JQuery probably couldn't load. Skip highlighting.
if self.recorder_mode:
url = self.get_current_url()
if url and len(url) > 0:
if ("http:") in url or ("https:") in url or ("file:") in url:
if self.get_session_storage_item("pause_recorder") == "no":
time_stamp = self.execute_script("return Date.now();")
origin = self.get_origin()
action = ["hi_li", orig_selector, origin, time_stamp]
self.__extra_actions.append(action)
time.sleep(0.065)
def __highlight_with_js(self, selector, loops, o_bs):
self.wait_for_ready_state_complete()
js_utils.highlight_with_js(self.driver, selector, loops, o_bs)
def __highlight_with_jquery(self, selector, loops, o_bs):
self.wait_for_ready_state_complete()
js_utils.highlight_with_jquery(self.driver, selector, loops, o_bs)
def press_up_arrow(self, selector="html", times=1, by=By.CSS_SELECTOR):
"""Simulates pressing the UP Arrow on the keyboard.
By default, "html" will be used as the CSS Selector target.
You can specify how many times in-a-row the action happens."""
self.__check_scope()
if times < 1:
return
element = self.wait_for_element_present(selector)
self.__demo_mode_highlight_if_active(selector, by)
if not self.demo_mode and not self.slow_mode:
self.__scroll_to_element(element, selector, by)
for i in range(int(times)):
try:
element.send_keys(Keys.ARROW_UP)
except Exception:
self.wait_for_ready_state_complete()
element = self.wait_for_element_visible(selector)
element.send_keys(Keys.ARROW_UP)
time.sleep(0.01)
if self.slow_mode:
time.sleep(0.1)
def press_down_arrow(self, selector="html", times=1, by=By.CSS_SELECTOR):
"""Simulates pressing the DOWN Arrow on the keyboard.
By default, "html" will be used as the CSS Selector target.
You can specify how many times in-a-row the action happens."""
self.__check_scope()
if times < 1:
return
element = self.wait_for_element_present(selector)
self.__demo_mode_highlight_if_active(selector, by)
if not self.demo_mode and not self.slow_mode:
self.__scroll_to_element(element, selector, by)
for i in range(int(times)):
try:
element.send_keys(Keys.ARROW_DOWN)
except Exception:
self.wait_for_ready_state_complete()
element = self.wait_for_element_visible(selector)
element.send_keys(Keys.ARROW_DOWN)
time.sleep(0.01)
if self.slow_mode:
time.sleep(0.1)
def press_left_arrow(self, selector="html", times=1, by=By.CSS_SELECTOR):
"""Simulates pressing the LEFT Arrow on the keyboard.
By default, "html" will be used as the CSS Selector target.
You can specify how many times in-a-row the action happens."""
self.__check_scope()
if times < 1:
return
element = self.wait_for_element_present(selector)
self.__demo_mode_highlight_if_active(selector, by)
if not self.demo_mode and not self.slow_mode:
self.__scroll_to_element(element, selector, by)
for i in range(int(times)):
try:
element.send_keys(Keys.ARROW_LEFT)
except Exception:
self.wait_for_ready_state_complete()
element = self.wait_for_element_visible(selector)
element.send_keys(Keys.ARROW_LEFT)
time.sleep(0.01)
if self.slow_mode:
time.sleep(0.1)
def press_right_arrow(self, selector="html", times=1, by=By.CSS_SELECTOR):
"""Simulates pressing the RIGHT Arrow on the keyboard.
By default, "html" will be used as the CSS Selector target.
You can specify how many times in-a-row the action happens."""
self.__check_scope()
if times < 1:
return
element = self.wait_for_element_present(selector)
self.__demo_mode_highlight_if_active(selector, by)
if not self.demo_mode and not self.slow_mode:
self.__scroll_to_element(element, selector, by)
for i in range(int(times)):
try:
element.send_keys(Keys.ARROW_RIGHT)
except Exception:
self.wait_for_ready_state_complete()
element = self.wait_for_element_visible(selector)
element.send_keys(Keys.ARROW_RIGHT)
time.sleep(0.01)
if self.slow_mode:
time.sleep(0.1)
def scroll_to(self, selector, by=By.CSS_SELECTOR, timeout=None):
""" Fast scroll to destination """
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
if self.demo_mode or self.slow_mode:
self.slow_scroll_to(selector, by=by, timeout=timeout)
return
element = self.wait_for_element_visible(
selector, by=by, timeout=timeout
)
try:
self.__scroll_to_element(element, selector, by)
except (StaleElementReferenceException, ENI_Exception):
self.wait_for_ready_state_complete()
time.sleep(0.12)
element = self.wait_for_element_visible(
selector, by=by, timeout=timeout
)
self.__scroll_to_element(element, selector, by)
def scroll_to_element(self, selector, by=By.CSS_SELECTOR, timeout=None):
self.scroll_to(selector, by=by, timeout=timeout)
def slow_scroll_to(self, selector, by=By.CSS_SELECTOR, timeout=None):
""" Slow motion scroll to destination """
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
element = self.wait_for_element_visible(
selector, by=by, timeout=timeout
)
try:
scroll_distance = js_utils.get_scroll_distance_to_element(
self.driver, element
)
if abs(scroll_distance) > constants.Values.SSMD:
self.__jquery_slow_scroll_to(selector, by)
else:
self.__slow_scroll_to_element(element)
except Exception:
self.wait_for_ready_state_complete()
time.sleep(0.12)
element = self.wait_for_element_visible(
selector, by=by, timeout=timeout
)
self.__slow_scroll_to_element(element)
def slow_scroll_to_element(
self, selector, by=By.CSS_SELECTOR, timeout=None
):
self.slow_scroll_to(selector, by=by, timeout=timeout)
def scroll_to_top(self):
""" Scroll to the top of the page. """
self.__check_scope()
scroll_script = "window.scrollTo(0, 0);"
try:
self.execute_script(scroll_script)
time.sleep(0.012)
return True
except Exception:
return False
def scroll_to_bottom(self):
""" Scroll to the bottom of the page. """
self.__check_scope()
scroll_script = "window.scrollTo(0, 10000);"
try:
self.execute_script(scroll_script)
time.sleep(0.012)
return True
except Exception:
return False
def click_xpath(self, xpath):
# Technically self.click() will automatically detect an xpath selector,
# so self.click_xpath() is just a longer name for the same action.
self.click(xpath, by=By.XPATH)
def js_click(
self, selector, by=By.CSS_SELECTOR, all_matches=False, scroll=True
):
"""Clicks an element using JavaScript.
Can be used to click hidden / invisible elements.
If "all_matches" is False, only the first match is clicked.
If "scroll" is False, won't scroll unless running in Demo Mode."""
self.wait_for_ready_state_complete()
selector, by = self.__recalculate_selector(selector, by, xp_ok=False)
if by == By.LINK_TEXT:
message = (
"Pure JavaScript doesn't support clicking by Link Text. "
"You may want to use self.jquery_click() instead, which "
"allows this with :contains(), assuming jQuery isn't blocked. "
"For now, self.js_click() will use a regular WebDriver click."
)
logging.debug(message)
self.click(selector, by=by)
return
element = self.wait_for_element_present(
selector, by=by, timeout=settings.SMALL_TIMEOUT
)
if self.is_element_visible(selector, by=by):
self.__demo_mode_highlight_if_active(selector, by)
if scroll and not self.demo_mode and not self.slow_mode:
success = js_utils.scroll_to_element(self.driver, element)
if not success:
self.wait_for_ready_state_complete()
timeout = settings.SMALL_TIMEOUT
element = page_actions.wait_for_element_present(
self.driver, selector, by, timeout=timeout
)
css_selector = self.convert_to_css_selector(selector, by=by)
css_selector = re.escape(css_selector) # Add "\\" to special chars
css_selector = self.__escape_quotes_if_needed(css_selector)
action = None
pre_action_url = self.driver.current_url
pre_window_count = len(self.driver.window_handles)
if self.recorder_mode and not self.__dont_record_js_click:
time_stamp = self.execute_script("return Date.now();")
tag_name = None
href = ""
if ":contains\\(" not in css_selector:
tag_name = self.execute_script(
"return document.querySelector('%s').tagName.toLowerCase()"
% css_selector
)
if tag_name == "a":
href = self.execute_script(
"return document.querySelector('%s').href" % css_selector
)
origin = self.get_origin()
href_origin = [href, origin]
action = ["js_cl", selector, href_origin, time_stamp]
if all_matches:
action[0] = "js_ca"
if not all_matches:
if ":contains\\(" not in css_selector:
self.__js_click(selector, by=by)
else:
click_script = """jQuery('%s')[0].click();""" % css_selector
self.safe_execute_script(click_script)
else:
if ":contains\\(" not in css_selector:
self.__js_click_all(selector, by=by)
else:
click_script = """jQuery('%s').click();""" % css_selector
self.safe_execute_script(click_script)
if self.recorder_mode and action:
self.__extra_actions.append(action)
latest_window_count = len(self.driver.window_handles)
if (
latest_window_count > pre_window_count
and (
self.recorder_mode
or (
settings.SWITCH_TO_NEW_TABS_ON_CLICK
and self.driver.current_url == pre_action_url
)
)
):
self.__switch_to_newest_window_if_not_blank()
self.wait_for_ready_state_complete()
self.__demo_mode_pause_if_active()
def js_click_all(self, selector, by=By.CSS_SELECTOR):
""" Clicks all matching elements using pure JS. (No jQuery) """
self.js_click(selector, by=By.CSS_SELECTOR, all_matches=True)
def jquery_click(self, selector, by=By.CSS_SELECTOR):
"""Clicks an element using jQuery. (Different from using pure JS.)
Can be used to click hidden / invisible elements."""
self.__check_scope()
selector, by = self.__recalculate_selector(selector, by, xp_ok=False)
self.wait_for_element_present(
selector, by=by, timeout=settings.SMALL_TIMEOUT
)
if self.is_element_visible(selector, by=by):
self.__demo_mode_highlight_if_active(selector, by)
selector = self.convert_to_css_selector(selector, by=by)
selector = self.__make_css_match_first_element_only(selector)
click_script = """jQuery('%s')[0].click();""" % selector
self.safe_execute_script(click_script)
self.__demo_mode_pause_if_active()
def jquery_click_all(self, selector, by=By.CSS_SELECTOR):
""" Clicks all matching elements using jQuery. """
self.__check_scope()
selector, by = self.__recalculate_selector(selector, by, xp_ok=False)
self.wait_for_element_present(
selector, by=by, timeout=settings.SMALL_TIMEOUT
)
if self.is_element_visible(selector, by=by):
self.__demo_mode_highlight_if_active(selector, by)
css_selector = self.convert_to_css_selector(selector, by=by)
click_script = """jQuery('%s').click();""" % css_selector
self.safe_execute_script(click_script)
self.__demo_mode_pause_if_active()
def hide_element(self, selector, by=By.CSS_SELECTOR):
""" Hide the first element on the page that matches the selector. """
self.__check_scope()
selector, by = self.__recalculate_selector(selector, by)
selector = self.convert_to_css_selector(selector, by=by)
selector = self.__make_css_match_first_element_only(selector)
hide_script = """jQuery('%s').hide();""" % selector
self.safe_execute_script(hide_script)
def hide_elements(self, selector, by=By.CSS_SELECTOR):
""" Hide all elements on the page that match the selector. """
self.__check_scope()
selector, by = self.__recalculate_selector(selector, by)
selector = self.convert_to_css_selector(selector, by=by)
hide_script = """jQuery('%s').hide();""" % selector
self.safe_execute_script(hide_script)
def show_element(self, selector, by=By.CSS_SELECTOR):
""" Show the first element on the page that matches the selector. """
self.__check_scope()
selector, by = self.__recalculate_selector(selector, by)
selector = self.convert_to_css_selector(selector, by=by)
selector = self.__make_css_match_first_element_only(selector)
show_script = """jQuery('%s').show(0);""" % selector
self.safe_execute_script(show_script)
def show_elements(self, selector, by=By.CSS_SELECTOR):
""" Show all elements on the page that match the selector. """
self.__check_scope()
selector, by = self.__recalculate_selector(selector, by)
selector = self.convert_to_css_selector(selector, by=by)
show_script = """jQuery('%s').show(0);""" % selector
self.safe_execute_script(show_script)
def remove_element(self, selector, by=By.CSS_SELECTOR):
""" Remove the first element on the page that matches the selector. """
self.__check_scope()
selector, by = self.__recalculate_selector(selector, by)
selector = self.convert_to_css_selector(selector, by=by)
selector = self.__make_css_match_first_element_only(selector)
remove_script = """jQuery('%s').remove();""" % selector
self.safe_execute_script(remove_script)
def remove_elements(self, selector, by=By.CSS_SELECTOR):
""" Remove all elements on the page that match the selector. """
self.__check_scope()
selector, by = self.__recalculate_selector(selector, by)
selector = self.convert_to_css_selector(selector, by=by)
remove_script = """jQuery('%s').remove();""" % selector
self.safe_execute_script(remove_script)
def ad_block(self):
""" Block ads that appear on the current web page. """
from seleniumbase.config import ad_block_list
self.__check_scope() # Using wait_for_RSC would cause an infinite loop
for css_selector in ad_block_list.AD_BLOCK_LIST:
css_selector = re.escape(css_selector) # Add "\\" to special chars
css_selector = self.__escape_quotes_if_needed(css_selector)
script = (
"""var $elements = document.querySelectorAll('%s');
var index = 0, length = $elements.length;
for(; index < length; index++){
$elements[index].remove();}"""
% css_selector
)
try:
self.execute_script(script)
except Exception:
pass # Don't fail test if ad_blocking fails
def show_file_choosers(self):
"""Display hidden file-chooser input fields on sites if present."""
css_selector = 'input[type="file"]'
try:
self.show_elements(css_selector)
except Exception:
pass
css_selector = re.escape(css_selector) # Add "\\" to special chars
css_selector = self.__escape_quotes_if_needed(css_selector)
script = (
"""var $elements = document.querySelectorAll('%s');
var index = 0, length = $elements.length;
for(; index < length; index++){
the_class = $elements[index].getAttribute('class');
new_class = the_class.replaceAll('hidden', 'visible');
$elements[index].setAttribute('class', new_class);}"""
% css_selector
)
try:
self.execute_script(script)
except Exception:
pass
if self.recorder_mode:
url = self.get_current_url()
if url and len(url) > 0:
if ("http:") in url or ("https:") in url or ("file:") in url:
if self.get_session_storage_item("pause_recorder") == "no":
time_stamp = self.execute_script("return Date.now();")
origin = self.get_origin()
action = ["sh_fc", "", origin, time_stamp]
self.__extra_actions.append(action)
def get_domain_url(self, url):
self.__check_scope()
return page_utils.get_domain_url(url)
def get_beautiful_soup(self, source=None):
"""BeautifulSoup is a toolkit for dissecting an HTML document
and extracting what you need. It's great for screen-scraping!
See: https://www.crummy.com/software/BeautifulSoup/bs4/doc/
"""
from bs4 import BeautifulSoup
if not source:
source = self.get_page_source()
soup = BeautifulSoup(source, "html.parser")
return soup
def get_unique_links(self):
"""Get all unique links in the html of the page source.
Page links include those obtained from:
"a"->"href", "img"->"src", "link"->"href", and "script"->"src".
"""
page_url = self.get_current_url()
soup = self.get_beautiful_soup(self.get_page_source())
links = page_utils._get_unique_links(page_url, soup)
return links
def get_link_status_code(self, link, allow_redirects=False, timeout=5):
"""Get the status code of a link.
If the timeout is set to less than 1, it becomes 1.
If the timeout is exceeded by requests.get(), it will return a 404.
For a list of available status codes, see:
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
"""
if self.__requests_timeout:
timeout = self.__requests_timeout
if timeout < 1:
timeout = 1
status_code = page_utils._get_link_status_code(
link, allow_redirects=allow_redirects, timeout=timeout
)
return status_code
def assert_link_status_code_is_not_404(self, link):
status_code = str(self.get_link_status_code(link))
bad_link_str = 'Error: "%s" returned a 404!' % link
self.assertNotEqual(status_code, "404", bad_link_str)
def __get_link_if_404_error(self, link):
status_code = str(self.get_link_status_code(link))
if status_code == "404":
# Verify again to be sure. (In case of multi-threading overload.)
status_code = str(self.get_link_status_code(link))
if status_code == "404":
return link
else:
return None
else:
return None
def assert_no_404_errors(self, multithreaded=True, timeout=None):
"""Assert no 404 errors from page links obtained from:
"a"->"href", "img"->"src", "link"->"href", and "script"->"src".
Timeout is on a per-link basis using the "requests" library.
(A 404 error represents a broken link on a web page.)
"""
all_links = self.get_unique_links()
links = []
for link in all_links:
if (
"javascript:" not in link
and "mailto:" not in link
and "data:" not in link
and "://fonts.gstatic.com" not in link
):
links.append(link)
if timeout:
if not type(timeout) is int and not type(timeout) is float:
raise Exception('Expecting a numeric value for "timeout"!')
if timeout < 0:
raise Exception('The "timeout" cannot be a negative number!')
self.__requests_timeout = timeout
broken_links = []
if multithreaded:
from multiprocessing.dummy import Pool as ThreadPool
pool = ThreadPool(10)
results = pool.map(self.__get_link_if_404_error, links)
pool.close()
pool.join()
for result in results:
if result:
broken_links.append(result)
else:
broken_links = []
for link in links:
if self.__get_link_if_404_error(link):
broken_links.append(link)
self.__requests_timeout = None # Reset the requests.get() timeout
if len(broken_links) > 0:
bad_links_str = "\n".join(broken_links)
if len(broken_links) == 1:
self.fail("Broken link detected:\n%s" % bad_links_str)
elif len(broken_links) > 1:
self.fail("Broken links detected:\n%s" % bad_links_str)
if self.demo_mode:
a_t = "ASSERT NO 404 ERRORS"
if self._language != "English":
from seleniumbase.fixtures.words import SD
a_t = SD.translate_assert_no_404_errors(self._language)
messenger_post = "%s" % a_t
self.__highlight_with_assert_success(messenger_post, "html")
def print_unique_links_with_status_codes(self):
"""Finds all unique links in the html of the page source
and then prints out those links with their status codes.
Format: ["link" -> "status_code"] (per line)
Page links include those obtained from:
"a"->"href", "img"->"src", "link"->"href", and "script"->"src".
"""
page_url = self.get_current_url()
soup = self.get_beautiful_soup(self.get_page_source())
page_utils._print_unique_links_with_status_codes(page_url, soup)
def __fix_unicode_conversion(self, text):
""" Fixing Chinese characters when converting from PDF to HTML. """
text = text.replace("\u2f8f", "\u884c")
text = text.replace("\u2f45", "\u65b9")
text = text.replace("\u2f08", "\u4eba")
text = text.replace("\u2f70", "\u793a")
text = text.replace("\xe2\xbe\x8f", "\xe8\xa1\x8c")
text = text.replace("\xe2\xbd\xb0", "\xe7\xa4\xba")
text = text.replace("\xe2\xbe\x8f", "\xe8\xa1\x8c")
text = text.replace("\xe2\xbd\x85", "\xe6\x96\xb9")
return text
def get_pdf_text(
self,
pdf,
page=None,
maxpages=None,
password=None,
codec="utf-8",
wrap=False,
nav=False,
override=False,
):
"""Gets text from a PDF file.
PDF can be either a URL or a file path on the local file system.
@Params
pdf - The URL or file path of the PDF file.
page - The page number (or a list of page numbers) of the PDF.
If a page number is provided, looks only at that page.
(1 is the first page, 2 is the second page, etc.)
If no page number is provided, returns all PDF text.
maxpages - Instead of providing a page number, you can provide
the number of pages to use from the beginning.
password - If the PDF is password-protected, enter it here.
codec - The compression format for character encoding.
(The default codec used by this method is 'utf-8'.)
wrap - Replaces ' \n' with ' ' so that individual sentences
from a PDF don't get broken up into separate lines when
getting converted into text format.
nav - If PDF is a URL, navigates to the URL in the browser first.
(Not needed because the PDF will be downloaded anyway.)
override - If the PDF file to be downloaded already exists in the
downloaded_files/ folder, that PDF will be used
instead of downloading it again."""
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=UserWarning)
from pdfminer.high_level import extract_text
if not password:
password = ""
if not maxpages:
maxpages = 0
if not pdf.lower().endswith(".pdf"):
raise Exception("%s is not a PDF file! (Expecting a .pdf)" % pdf)
file_path = None
if page_utils.is_valid_url(pdf):
from seleniumbase.core import download_helper
downloads_folder = download_helper.get_downloads_folder()
if nav:
if self.get_current_url() != pdf:
self.open(pdf)
file_name = pdf.split("/")[-1]
file_path = downloads_folder + "/" + file_name
if not os.path.exists(file_path):
self.download_file(pdf)
elif override:
self.download_file(pdf)
else:
if not os.path.exists(pdf):
raise Exception("%s is not a valid URL or file path!" % pdf)
file_path = os.path.abspath(pdf)
page_search = None # (Pages are delimited by '\x0c')
if type(page) is list:
pages = page
page_search = []
for page in pages:
page_search.append(page - 1)
elif type(page) is int:
page = page - 1
if page < 0:
page = 0
page_search = [page]
else:
page_search = None
pdf_text = extract_text(
file_path,
password="",
page_numbers=page_search,
maxpages=maxpages,
caching=False,
codec=codec,
)
pdf_text = self.__fix_unicode_conversion(pdf_text)
if wrap:
pdf_text = pdf_text.replace(" \n", " ")
pdf_text = pdf_text.strip() # Remove leading and trailing whitespace
return pdf_text
def assert_pdf_text(
self,
pdf,
text,
page=None,
maxpages=None,
password=None,
codec="utf-8",
wrap=True,
nav=False,
override=False,
):
"""Asserts text in a PDF file.
PDF can be either a URL or a file path on the local file system.
@Params
pdf - The URL or file path of the PDF file.
text - The expected text to verify in the PDF.
page - The page number of the PDF to use (optional).
If a page number is provided, looks only at that page.
(1 is the first page, 2 is the second page, etc.)
If no page number is provided, looks at all the pages.
maxpages - Instead of providing a page number, you can provide
the number of pages to use from the beginning.
password - If the PDF is password-protected, enter it here.
codec - The compression format for character encoding.
(The default codec used by this method is 'utf-8'.)
wrap - Replaces ' \n' with ' ' so that individual sentences
from a PDF don't get broken up into separate lines when
getting converted into text format.
nav - If PDF is a URL, navigates to the URL in the browser first.
(Not needed because the PDF will be downloaded anyway.)
override - If the PDF file to be downloaded already exists in the
downloaded_files/ folder, that PDF will be used
instead of downloading it again."""
text = self.__fix_unicode_conversion(text)
if not codec:
codec = "utf-8"
pdf_text = self.get_pdf_text(
pdf,
page=page,
maxpages=maxpages,
password=password,
codec=codec,
wrap=wrap,
nav=nav,
override=override,
)
if type(page) is int:
if text not in pdf_text:
raise Exception(
"PDF [%s] is missing expected text [%s] on "
"page [%s]!" % (pdf, text, page)
)
else:
if text not in pdf_text:
raise Exception(
"PDF [%s] is missing expected text [%s]!" % (pdf, text)
)
return True
def create_folder(self, folder):
""" Creates a folder of the given name if it doesn't already exist. """
if folder.endswith("/"):
folder = folder[:-1]
if len(folder) < 1:
raise Exception("Minimum folder name length = 1.")
if not os.path.exists(folder):
try:
os.makedirs(folder)
except Exception:
pass
def choose_file(
self, selector, file_path, by=By.CSS_SELECTOR, timeout=None
):
"""This method is used to choose a file to upload to a website.
It works by populating a file-chooser "input" field of type="file".
A relative file_path will get converted into an absolute file_path.
Example usage:
self.choose_file('input[type="file"]', "my_dir/my_file.txt")
"""
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
abs_path = os.path.abspath(file_path)
element = self.wait_for_element_present(
selector, by=by, timeout=timeout
)
if self.is_element_visible(selector, by=by):
self.__demo_mode_highlight_if_active(selector, by)
if not self.demo_mode and not self.slow_mode:
self.__scroll_to_element(element, selector, by)
else:
choose_file_selector = 'input[type="file"]'
if self.is_element_present(choose_file_selector):
if not self.is_element_visible(choose_file_selector):
self.show_file_choosers()
if self.is_element_visible(selector, by=by):
self.__demo_mode_highlight_if_active(selector, by)
if not self.demo_mode and not self.slow_mode:
self.__scroll_to_element(element, selector, by)
pre_action_url = self.driver.current_url
if self.recorder_mode:
url = self.get_current_url()
if url and len(url) > 0:
if ("http:") in url or ("https:") in url or ("file:") in url:
if self.get_session_storage_item("pause_recorder") == "no":
time_stamp = self.execute_script("return Date.now();")
origin = self.get_origin()
sele_file_path = [selector, file_path]
action = ["chfil", sele_file_path, origin, time_stamp]
self.__extra_actions.append(action)
if type(abs_path) is int or type(abs_path) is float:
abs_path = str(abs_path)
try:
element.send_keys(abs_path)
except (StaleElementReferenceException, ENI_Exception):
self.wait_for_ready_state_complete()
time.sleep(0.16)
element = self.wait_for_element_present(
selector, by=by, timeout=timeout
)
element.send_keys(abs_path)
if self.demo_mode:
if self.driver.current_url != pre_action_url:
self.__demo_mode_pause_if_active()
else:
self.__demo_mode_pause_if_active(tiny=True)
elif self.slow_mode:
self.__slow_mode_pause_if_active()
def save_element_as_image_file(
self, selector, file_name, folder=None, overlay_text=""
):
"""Take a screenshot of an element and save it as an image file.
If no folder is specified, will save it to the current folder.
If overlay_text is provided, will add that to the saved image."""
element = self.wait_for_element_visible(selector)
element_png = element.screenshot_as_png
if len(file_name.split(".")[0]) < 1:
raise Exception("Error: file_name length must be > 0.")
if not file_name.endswith(".png"):
file_name = file_name + ".png"
image_file_path = None
if folder:
if folder.endswith("/"):
folder = folder[:-1]
if len(folder) > 0:
self.create_folder(folder)
image_file_path = "%s/%s" % (folder, file_name)
if not image_file_path:
image_file_path = file_name
with open(image_file_path, "wb") as file:
file.write(element_png)
# Add a text overlay if given
if type(overlay_text) is str and len(overlay_text) > 0:
from PIL import Image, ImageDraw
text_rows = overlay_text.split("\n")
len_text_rows = len(text_rows)
max_width = 0
for text_row in text_rows:
if len(text_row) > max_width:
max_width = len(text_row)
image = Image.open(image_file_path)
draw = ImageDraw.Draw(image)
draw.rectangle(
(0, 0, (max_width * 6) + 6, 16 * len_text_rows),
fill=(236, 236, 28),
)
draw.text(
(4, 2), # Coordinates
overlay_text, # Text
(8, 38, 176), # Color
)
image.save(image_file_path, "PNG", quality=100, optimize=True)
def download_file(self, file_url, destination_folder=None):
"""Downloads the file from the url to the destination folder.
If no destination folder is specified, the default one is used.
(The default [Downloads Folder] = "./downloaded_files")"""
if not destination_folder:
destination_folder = constants.Files.DOWNLOADS_FOLDER
if not os.path.exists(destination_folder):
os.makedirs(destination_folder)
page_utils._download_file_to(file_url, destination_folder)
if self.recorder_mode:
url = self.get_current_url()
if url and len(url) > 0:
if ("http:") in url or ("https:") in url or ("file:") in url:
if self.get_session_storage_item("pause_recorder") == "no":
time_stamp = self.execute_script("return Date.now();")
origin = self.get_origin()
url_dest = [file_url, destination_folder]
action = ["do_fi", url_dest, origin, time_stamp]
self.__extra_actions.append(action)
def save_file_as(self, file_url, new_file_name, destination_folder=None):
"""Similar to self.download_file(), except that you get to rename the
file being downloaded to whatever you want."""
if not destination_folder:
destination_folder = constants.Files.DOWNLOADS_FOLDER
page_utils._download_file_to(
file_url, destination_folder, new_file_name
)
def save_data_as(self, data, file_name, destination_folder=None):
"""Saves the data specified to a file of the name specified.
If no destination folder is specified, the default one is used.
(The default [Downloads Folder] = "./downloaded_files")"""
if not destination_folder:
destination_folder = constants.Files.DOWNLOADS_FOLDER
page_utils._save_data_as(data, destination_folder, file_name)
def get_downloads_folder(self):
"""Returns the path of the SeleniumBase "downloaded_files/" folder.
Calling self.download_file(file_url) will put that file in here.
With the exception of Safari, IE, and Chromium Guest Mode,
any clicks that download files will also use this folder
rather than using the browser's default "downloads/" path."""
self.__check_scope()
from seleniumbase.core import download_helper
return download_helper.get_downloads_folder()
def get_browser_downloads_folder(self):
"""Returns the path that is used when a click initiates a download.
SeleniumBase overrides the system path to be "downloaded_files/"
The path can't be changed on Safari, IE, or Chromium Guest Mode.
The same problem occurs when using an out-of-date chromedriver.
"""
self.__check_scope()
if self.is_chromium() and self.guest_mode and not self.headless:
# Guest Mode (non-headless) can force the default downloads path
return os.path.join(os.path.expanduser("~"), "downloads")
elif self.browser == "safari" or self.browser == "ie":
# Can't change the system [Downloads Folder] on Safari or IE
return os.path.join(os.path.expanduser("~"), "downloads")
elif (
self.driver.capabilities["browserName"].lower() == "chrome"
and int(self.get_chromedriver_version().split(".")[0]) < 73
and self.headless
):
return os.path.join(os.path.expanduser("~"), "downloads")
else:
from seleniumbase.core import download_helper
return download_helper.get_downloads_folder()
return os.path.join(os.path.expanduser("~"), "downloads")
def get_path_of_downloaded_file(self, file, browser=False):
""" Returns the OS path of the downloaded file. """
if browser:
return os.path.join(self.get_browser_downloads_folder(), file)
else:
return os.path.join(self.get_downloads_folder(), file)
def is_downloaded_file_present(self, file, browser=False):
"""Returns True if the file exists in the pre-set [Downloads Folder].
For browser click-initiated downloads, SeleniumBase will override
the system [Downloads Folder] to be "./downloaded_files/",
but that path can't be overridden when using Safari, IE,
or Chromium Guest Mode, which keeps the default system path.
self.download_file(file_url) will always use "./downloaded_files/".
@Params
file - The filename of the downloaded file.
browser - If True, uses the path set by click-initiated downloads.
If False, uses the self.download_file(file_url) path.
Those paths are often the same. (browser-dependent)
(Default: False).
"""
return os.path.exists(
self.get_path_of_downloaded_file(file, browser=browser)
)
def delete_downloaded_file_if_present(self, file, browser=False):
"""Deletes the file from the [Downloads Folder] if the file exists.
For browser click-initiated downloads, SeleniumBase will override
the system [Downloads Folder] to be "./downloaded_files/",
but that path can't be overridden when using Safari, IE,
or Chromium Guest Mode, which keeps the default system path.
self.download_file(file_url) will always use "./downloaded_files/".
@Params
file - The filename to be deleted from the [Downloads Folder].
browser - If True, uses the path set by click-initiated downloads.
If False, uses the self.download_file(file_url) path.
Those paths are usually the same. (browser-dependent)
(Default: False).
"""
if self.is_downloaded_file_present(file, browser=browser):
file_path = self.get_path_of_downloaded_file(file, browser=browser)
try:
os.remove(file_path)
except Exception:
pass
def delete_downloaded_file(self, file, browser=False):
"""Same as self.delete_downloaded_file_if_present()
Deletes the file from the [Downloads Folder] if the file exists.
For browser click-initiated downloads, SeleniumBase will override
the system [Downloads Folder] to be "./downloaded_files/",
but that path can't be overridden when using Safari, IE,
or Chromium Guest Mode, which keeps the default system path.
self.download_file(file_url) will always use "./downloaded_files/".
@Params
file - The filename to be deleted from the [Downloads Folder].
browser - If True, uses the path set by click-initiated downloads.
If False, uses the self.download_file(file_url) path.
Those paths are usually the same. (browser-dependent)
(Default: False).
"""
if self.is_downloaded_file_present(file, browser=browser):
file_path = self.get_path_of_downloaded_file(file, browser=browser)
try:
os.remove(file_path)
except Exception:
pass
def assert_downloaded_file(self, file, timeout=None, browser=False):
"""Asserts that the file exists in SeleniumBase's [Downloads Folder].
For browser click-initiated downloads, SeleniumBase will override
the system [Downloads Folder] to be "./downloaded_files/",
but that path can't be overridden when using Safari, IE,
or Chromium Guest Mode, which keeps the default system path.
self.download_file(file_url) will always use "./downloaded_files/".
@Params
file - The filename of the downloaded file.
timeout - The time (seconds) to wait for the download to complete.
browser - If True, uses the path set by click-initiated downloads.
If False, uses the self.download_file(file_url) path.
Those paths are often the same. (browser-dependent)
(Default: False).
"""
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
start_ms = time.time() * 1000.0
stop_ms = start_ms + (timeout * 1000.0)
downloaded_file_path = self.get_path_of_downloaded_file(file, browser)
found = False
for x in range(int(timeout)):
shared_utils.check_if_time_limit_exceeded()
try:
self.assertTrue(
os.path.exists(downloaded_file_path),
"File [%s] was not found in the downloads folder [%s]!"
% (file, self.get_downloads_folder()),
)
found = True
break
except Exception:
now_ms = time.time() * 1000.0
if now_ms >= stop_ms:
break
time.sleep(1)
if not found and not os.path.exists(downloaded_file_path):
message = (
"File {%s} was not found in the downloads folder {%s} "
"after %s seconds! (Or the download didn't complete!)"
% (file, self.get_downloads_folder(), timeout)
)
page_actions.timeout_exception("NoSuchFileException", message)
if self.recorder_mode:
url = self.get_current_url()
if url and len(url) > 0:
if ("http:") in url or ("https:") in url or ("file:") in url:
if self.get_session_storage_item("pause_recorder") == "no":
time_stamp = self.execute_script("return Date.now();")
origin = self.get_origin()
action = ["as_df", file, origin, time_stamp]
self.__extra_actions.append(action)
if self.demo_mode:
messenger_post = "ASSERT DOWNLOADED FILE: [%s]" % file
try:
js_utils.activate_jquery(self.driver)
js_utils.post_messenger_success_message(
self.driver, messenger_post, self.message_duration
)
except Exception:
pass
def assert_true(self, expr, msg=None):
"""Asserts that the expression is True.
Will raise an exception if the statement if False."""
self.assertTrue(expr, msg=msg)
def assert_false(self, expr, msg=None):
"""Asserts that the expression is False.
Will raise an exception if the statement if True."""
self.assertFalse(expr, msg=msg)
def assert_equal(self, first, second, msg=None):
"""Asserts that the two values are equal.
Will raise an exception if the values are not equal."""
self.assertEqual(first, second, msg=msg)
def assert_not_equal(self, first, second, msg=None):
"""Asserts that the two values are not equal.
Will raise an exception if the values are equal."""
self.assertNotEqual(first, second, msg=msg)
def assert_in(self, first, second, msg=None):
"""Asserts that the first string is in the second string.
Will raise an exception if the first string is not in the second."""
self.assertIn(first, second, msg=msg)
def assert_not_in(self, first, second, msg=None):
"""Asserts that the first string is not in the second string.
Will raise an exception if the first string is in the second string."""
self.assertNotIn(first, second, msg=msg)
def assert_raises(self, *args, **kwargs):
"""Asserts that the following block of code raises an exception.
Will raise an exception if the block of code has no exception.
Usage Example =>
# Verify that the expected exception is raised.
with self.assert_raises(Exception):
raise Exception("Expected Exception!")
"""
return self.assertRaises(*args, **kwargs)
def wait_for_attribute(
self, selector, attribute, value=None, by=By.CSS_SELECTOR, timeout=None
):
"""Raises an exception if the element attribute/value is not found.
If the value is not specified, the attribute only needs to exist.
Returns the element that contains the attribute if successful.
Default timeout = LARGE_TIMEOUT."""
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
if self.__is_shadow_selector(selector):
return self.__wait_for_shadow_attribute_present(
selector, attribute, value=value, timeout=timeout
)
return page_actions.wait_for_attribute(
self.driver,
selector,
attribute,
value=value,
by=by,
timeout=timeout,
)
def assert_attribute(
self, selector, attribute, value=None, by=By.CSS_SELECTOR, timeout=None
):
"""Raises an exception if the element attribute/value is not found.
If the value is not specified, the attribute only needs to exist.
Returns True if successful. Default timeout = SMALL_TIMEOUT."""
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
self.wait_for_attribute(
selector, attribute, value=value, by=by, timeout=timeout
)
if (
self.demo_mode
and not self.__is_shadow_selector(selector)
and self.is_element_visible(selector, by=by)
):
a_a = "ASSERT ATTRIBUTE"
i_n = "in"
if self._language != "English":
from seleniumbase.fixtures.words import SD
a_a = SD.translate_assert_attribute(self._language)
i_n = SD.translate_in(self._language)
if not value:
messenger_post = "%s: {%s} %s %s: %s" % (
a_a,
attribute,
i_n,
by.upper(),
selector,
)
else:
messenger_post = '%s: {%s == "%s"} %s %s: %s' % (
a_a,
attribute,
value,
i_n,
by.upper(),
selector,
)
self.__highlight_with_assert_success(messenger_post, selector, by)
if self.recorder_mode:
url = self.get_current_url()
if url and len(url) > 0:
if ("http:") in url or ("https:") in url or ("file:") in url:
if self.get_session_storage_item("pause_recorder") == "no":
time_stamp = self.execute_script("return Date.now();")
origin = self.get_origin()
value = value.replace("\\", "\\\\")
sel_att_val = [selector, attribute, value]
action = ["as_at", sel_att_val, origin, time_stamp]
self.__extra_actions.append(action)
return True
def assert_title(self, title):
"""Asserts that the web page title matches the expected title.
When a web page initially loads, the title starts as the URL,
but then the title switches over to the actual page title.
In Recorder Mode, this assertion is skipped because the Recorder
changes the page title to the selector of the hovered element.
"""
self.wait_for_ready_state_complete()
expected = title.strip()
actual = self.get_page_title().strip()
error = (
"Expected page title [%s] does not match the actual title [%s]!"
)
try:
if not self.recorder_mode:
self.assertEqual(expected, actual, error % (expected, actual))
except Exception:
self.wait_for_ready_state_complete()
self.sleep(settings.MINI_TIMEOUT)
actual = self.get_page_title().strip()
try:
self.assertEqual(expected, actual, error % (expected, actual))
except Exception:
self.wait_for_ready_state_complete()
self.sleep(settings.MINI_TIMEOUT)
actual = self.get_page_title().strip()
self.assertEqual(expected, actual, error % (expected, actual))
if self.demo_mode and not self.recorder_mode:
a_t = "ASSERT TITLE"
if self._language != "English":
from seleniumbase.fixtures.words import SD
a_t = SD.translate_assert_title(self._language)
messenger_post = "%s: {%s}" % (a_t, title)
self.__highlight_with_assert_success(messenger_post, "html")
if self.recorder_mode:
url = self.get_current_url()
if url and len(url) > 0:
if ("http:") in url or ("https:") in url or ("file:") in url:
if self.get_session_storage_item("pause_recorder") == "no":
time_stamp = self.execute_script("return Date.now();")
origin = self.get_origin()
action = ["as_ti", title, origin, time_stamp]
self.__extra_actions.append(action)
return True
def assert_no_js_errors(self):
"""Asserts that there are no JavaScript "SEVERE"-level page errors.
Works ONLY on Chromium browsers (Chrome or Edge).
Does NOT work on Firefox, IE, Safari, or some other browsers:
* See https://github.com/SeleniumHQ/selenium/issues/1161
Based on the following Stack Overflow solution:
* https://stackoverflow.com/a/41150512/7058266
"""
self.__check_scope()
time.sleep(0.1) # May take a moment for errors to appear after loads.
try:
browser_logs = self.driver.get_log("browser")
except (ValueError, WebDriverException):
# If unable to get browser logs, skip the assert and return.
return
messenger_library = "//cdnjs.cloudflare.com/ajax/libs/messenger"
underscore_library = "//cdnjs.cloudflare.com/ajax/libs/underscore"
errors = []
for entry in browser_logs:
if entry["level"] == "SEVERE":
if (
messenger_library not in entry["message"]
and underscore_library not in entry["message"]
):
# Add errors if not caused by SeleniumBase dependencies
errors.append(entry)
if len(errors) > 0:
for n in range(len(errors)):
f_t_l_r = " - Failed to load resource"
u_c_t_e = " Uncaught TypeError: "
if f_t_l_r in errors[n]["message"]:
url = errors[n]["message"].split(f_t_l_r)[0]
errors[n] = {"Error 404 (broken link)": url}
elif u_c_t_e in errors[n]["message"]:
url = errors[n]["message"].split(u_c_t_e)[0]
error = errors[n]["message"].split(u_c_t_e)[1]
errors[n] = {"Uncaught TypeError (%s)" % error: url}
er_str = str(errors)
er_str = er_str.replace("[{", "[\n{").replace("}, {", "},\n{")
current_url = self.get_current_url()
raise Exception(
"JavaScript errors found on %s => %s" % (current_url, er_str)
)
if self.demo_mode:
if self.browser == "chrome" or self.browser == "edge":
a_t = "ASSERT NO JS ERRORS"
if self._language != "English":
from seleniumbase.fixtures.words import SD
a_t = SD.translate_assert_no_js_errors(self._language)
messenger_post = "%s" % a_t
self.__highlight_with_assert_success(messenger_post, "html")
def __activate_html_inspector(self):
self.wait_for_ready_state_complete()
time.sleep(0.05)
js_utils.activate_html_inspector(self.driver)
def inspect_html(self):
"""Inspects the Page HTML with HTML-Inspector.
(https://github.com/philipwalton/html-inspector)
(https://cdnjs.com/libraries/html-inspector)
Prints the results and also returns them."""
self.__activate_html_inspector()
self.wait_for_ready_state_complete()
script = """HTMLInspector.inspect();"""
try:
self.execute_script(script)
except Exception:
# If unable to load the JavaScript, skip inspection and return.
msg = "(Unable to load HTML-Inspector JS! Inspection Skipped!)"
print("\n" + msg)
return msg
time.sleep(0.1)
browser_logs = []
try:
browser_logs = self.driver.get_log("browser")
except (ValueError, WebDriverException):
# If unable to get browser logs, skip the assert and return.
msg = "(Unable to Inspect HTML! -> Only works on Chromium!)"
print("\n" + msg)
return msg
messenger_library = "//cdnjs.cloudflare.com/ajax/libs/messenger"
url = self.get_current_url()
header = "\n* HTML Inspection Results: %s" % url
results = [header]
row_count = 0
for entry in browser_logs:
message = entry["message"]
if "0:6053 " in message:
message = message.split("0:6053")[1]
message = message.replace("\\u003C", "<")
if message.startswith(' "') and message.count('"') == 2:
message = message.split('"')[1]
message = "X - " + message
if messenger_library not in message:
if message not in results:
results.append(message)
row_count += 1
if row_count > 0:
results.append("* (See the Console output for details!)")
else:
results.append("* (No issues detected!)")
results = "\n".join(results)
print(results)
return results
def is_valid_url(self, url):
""" Return True if the url is a valid url. """
return page_utils.is_valid_url(url)
def is_chromium(self):
""" Return True if the browser is Chrome, Edge, or Opera. """
self.__check_scope()
chromium = False
browser_name = self.driver.capabilities["browserName"]
if browser_name.lower() in ("chrome", "edge", "msedge", "opera"):
chromium = True
return chromium
def __fail_if_not_using_chrome(self, method):
chrome = False
browser_name = self.driver.capabilities["browserName"]
if browser_name.lower() == "chrome":
chrome = True
if not chrome:
from seleniumbase.common.exceptions import NotUsingChromeException
message = (
'Error: "%s" should only be called '
'by tests running with self.browser == "chrome"! '
'You should add an "if" statement to your code before calling '
"this method if using browsers that are Not Chrome! "
'The browser detected was: "%s".' % (method, browser_name)
)
raise NotUsingChromeException(message)
def get_chrome_version(self):
self.__check_scope()
self.__fail_if_not_using_chrome("get_chrome_version()")
driver_capabilities = self.driver.capabilities
if "version" in driver_capabilities:
chrome_version = driver_capabilities["version"]
else:
chrome_version = driver_capabilities["browserVersion"]
return chrome_version
def get_chromedriver_version(self):
self.__check_scope()
self.__fail_if_not_using_chrome("get_chromedriver_version()")
chrome_dict = self.driver.capabilities["chrome"]
chromedriver_version = chrome_dict["chromedriverVersion"]
chromedriver_version = chromedriver_version.split(" ")[0]
return chromedriver_version
def is_chromedriver_too_old(self):
"""There are known issues with chromedriver versions below 73.
This can impact tests that need to hover over an element, or ones
that require a custom downloads folder ("./downloaded_files").
Due to the situation that newer versions of chromedriver require
an exact match to the version of Chrome, an "old" version of
chromedriver is installed by default. It is then up to the user
to upgrade to the correct version of chromedriver from there.
This method can be used to change test behavior when trying
to perform an action that is impacted by having an old version
of chromedriver installed."""
self.__check_scope()
self.__fail_if_not_using_chrome("is_chromedriver_too_old()")
if int(self.get_chromedriver_version().split(".")[0]) < 73:
return True # chromedriver is too old! Please upgrade!
return False
def get_mfa_code(self, totp_key=None):
"""Same as get_totp_code() and get_google_auth_password().
Returns a time-based one-time password based on the
Google Authenticator algorithm for multi-factor authentication.
If the "totp_key" is not specified, this method defaults
to using the one provided in [seleniumbase/config/settings.py].
Google Authenticator codes expire & change at 30-sec intervals.
If the fetched password expires in the next 1.5 seconds, waits
for a new one before returning it (may take up to 1.5 seconds).
See https://pyotp.readthedocs.io/en/latest/ for details."""
import pyotp
if not totp_key:
totp_key = settings.TOTP_KEY
epoch_interval = time.time() / 30.0
cycle_lifespan = float(epoch_interval) - int(epoch_interval)
if float(cycle_lifespan) > 0.95:
# Password expires in the next 1.5 seconds. Wait for a new one.
for i in range(30):
time.sleep(0.05)
epoch_interval = time.time() / 30.0
cycle_lifespan = float(epoch_interval) - int(epoch_interval)
if not float(cycle_lifespan) > 0.95:
# The new password cycle has begun
break
totp = pyotp.TOTP(totp_key)
return str(totp.now())
def enter_mfa_code(
self, selector, totp_key=None, by=By.CSS_SELECTOR, timeout=None
):
"""Enters into the field a Multi-Factor Authentication TOTP Code.
If the "totp_key" is not specified, this method defaults
to using the one provided in [seleniumbase/config/settings.py].
The TOTP code is generated by the Google Authenticator Algorithm.
This method will automatically press ENTER after typing the code."""
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
self.wait_for_element_visible(selector, by=by, timeout=timeout)
if self.recorder_mode:
css_selector = self.convert_to_css_selector(selector, by=by)
url = self.get_current_url()
if url and len(url) > 0:
if ("http:") in url or ("https:") in url or ("file:") in url:
origin = self.get_origin()
if self.get_session_storage_item("pause_recorder") == "no":
time_stamp = self.execute_script("return Date.now();")
sel_key = [css_selector, totp_key]
action = ["e_mfa", sel_key, origin, time_stamp]
self.__extra_actions.append(action)
# Sometimes Sign-In leaves the origin... Save work first.
self.__origins_to_save.append(origin)
tab_actions = self.__get_recorded_actions_on_active_tab()
self.__actions_to_save.append(tab_actions)
mfa_code = self.get_mfa_code(totp_key)
self.update_text(selector, mfa_code + "\n", by=by, timeout=timeout)
def convert_css_to_xpath(self, css):
return css_to_xpath.convert_css_to_xpath(css)
def convert_xpath_to_css(self, xpath):
return xpath_to_css.convert_xpath_to_css(xpath)
def convert_to_css_selector(self, selector, by):
"""This method converts a selector to a CSS_SELECTOR.
jQuery commands require a CSS_SELECTOR for finding elements.
This method should only be used for jQuery/JavaScript actions.
Pure JavaScript doesn't support using a:contains("LINK_TEXT")."""
if by == By.CSS_SELECTOR:
return selector
elif by == By.ID:
return "#%s" % selector
elif by == By.CLASS_NAME:
return ".%s" % selector
elif by == By.NAME:
return '[name="%s"]' % selector
elif by == By.TAG_NAME:
return selector
elif by == By.XPATH:
return self.convert_xpath_to_css(selector)
elif by == By.LINK_TEXT:
return 'a:contains("%s")' % selector
elif by == By.PARTIAL_LINK_TEXT:
return 'a:contains("%s")' % selector
else:
raise Exception(
"Exception: Could not convert {%s}(by=%s) to CSS_SELECTOR!"
% (selector, by)
)
def set_value(
self, selector, text, by=By.CSS_SELECTOR, timeout=None, scroll=True
):
""" This method uses JavaScript to update a text field. """
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by, xp_ok=False)
self.wait_for_ready_state_complete()
self.wait_for_element_present(selector, by=by, timeout=timeout)
orginal_selector = selector
css_selector = self.convert_to_css_selector(selector, by=by)
self.__demo_mode_highlight_if_active(orginal_selector, by)
if scroll and not self.demo_mode and not self.slow_mode:
self.scroll_to(orginal_selector, by=by, timeout=timeout)
if type(text) is int or type(text) is float:
text = str(text)
value = re.escape(text)
value = self.__escape_quotes_if_needed(value)
pre_escape_css_selector = css_selector
css_selector = re.escape(css_selector) # Add "\\" to special chars
css_selector = self.__escape_quotes_if_needed(css_selector)
the_type = None
if ":contains\\(" not in css_selector:
get_type_script = (
"""return document.querySelector('%s').getAttribute('type');"""
% css_selector
)
the_type = self.execute_script(get_type_script) # Used later
script = """document.querySelector('%s').value='%s';""" % (
css_selector,
value,
)
self.execute_script(script)
if self.recorder_mode:
time_stamp = self.execute_script("return Date.now();")
origin = self.get_origin()
sel_tex = [pre_escape_css_selector, text]
action = ["js_ty", sel_tex, origin, time_stamp]
self.__extra_actions.append(action)
else:
script = """jQuery('%s')[0].value='%s';""" % (css_selector, value)
self.safe_execute_script(script)
if text.endswith("\n"):
element = self.wait_for_element_present(
orginal_selector, by=by, timeout=timeout
)
element.send_keys(Keys.RETURN)
if settings.WAIT_FOR_RSC_ON_PAGE_LOADS:
self.wait_for_ready_state_complete()
else:
if the_type == "range" and ":contains\\(" not in css_selector:
# Some input sliders need a mouse event to trigger listeners.
try:
mouse_move_script = (
"""m_elm = document.querySelector('%s');"""
"""m_evt = new Event('mousemove');"""
"""m_elm.dispatchEvent(m_evt);"""
% css_selector
)
self.execute_script(mouse_move_script)
except Exception:
pass
self.__demo_mode_pause_if_active()
def js_update_text(self, selector, text, by=By.CSS_SELECTOR, timeout=None):
"""JavaScript + send_keys are used to update a text field.
Performs self.set_value() and triggers event listeners.
If text ends in "\n", set_value() presses RETURN after.
Works faster than send_keys() alone due to the JS call.
"""
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
if type(text) is int or type(text) is float:
text = str(text)
self.set_value(selector, text, by=by, timeout=timeout)
if not text.endswith("\n"):
try:
element = page_actions.wait_for_element_present(
self.driver, selector, by, timeout=0.2
)
element.send_keys(" " + Keys.BACK_SPACE)
except Exception:
pass
def js_type(self, selector, text, by=By.CSS_SELECTOR, timeout=None):
"""Same as self.js_update_text()
JavaScript + send_keys are used to update a text field.
Performs self.set_value() and triggers event listeners.
If text ends in "\n", set_value() presses RETURN after.
Works faster than send_keys() alone due to the JS call.
"""
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
self.js_update_text(selector, text, by=by, timeout=timeout)
def set_text(self, selector, text, by=By.CSS_SELECTOR, timeout=None):
"""Same as self.js_update_text()
JavaScript + send_keys are used to update a text field.
Performs self.set_value() and triggers event listeners.
If text ends in "\n", set_value() presses RETURN after.
Works faster than send_keys() alone due to the JS call.
If not an input or textarea, sets textContent instead."""
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
self.wait_for_ready_state_complete()
element = page_actions.wait_for_element_present(
self.driver, selector, by, timeout
)
if element.tag_name == "input" or element.tag_name == "textarea":
self.js_update_text(selector, text, by=by, timeout=timeout)
else:
self.set_text_content(selector, text, by=by, timeout=timeout)
def set_text_content(
self, selector, text, by=By.CSS_SELECTOR, timeout=None, scroll=False
):
"""This method uses JavaScript to set an element's textContent.
If the element is an input or textarea, sets the value instead."""
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
self.wait_for_ready_state_complete()
element = page_actions.wait_for_element_present(
self.driver, selector, by, timeout
)
if element.tag_name == "input" or element.tag_name == "textarea":
self.js_update_text(selector, text, by=by, timeout=timeout)
return
orginal_selector = selector
css_selector = self.convert_to_css_selector(selector, by=by)
if scroll:
self.__demo_mode_highlight_if_active(orginal_selector, by)
if not self.demo_mode and not self.slow_mode:
self.scroll_to(orginal_selector, by=by, timeout=timeout)
if type(text) is int or type(text) is float:
text = str(text)
value = re.escape(text)
value = self.__escape_quotes_if_needed(value)
css_selector = re.escape(css_selector) # Add "\\" to special chars
css_selector = self.__escape_quotes_if_needed(css_selector)
if ":contains\\(" not in css_selector:
script = """document.querySelector('%s').textContent='%s';""" % (
css_selector,
value,
)
self.execute_script(script)
else:
script = """jQuery('%s')[0].textContent='%s';""" % (
css_selector,
value,
)
self.safe_execute_script(script)
self.__demo_mode_pause_if_active()
def jquery_update_text(
self, selector, text, by=By.CSS_SELECTOR, timeout=None
):
"""This method uses jQuery to update a text field.
If the text string ends with the newline character,
Selenium finishes the call, which simulates pressing
{Enter/Return} after the text is entered."""
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by, xp_ok=False)
element = self.wait_for_element_visible(
selector, by=by, timeout=timeout
)
self.__demo_mode_highlight_if_active(selector, by)
self.scroll_to(selector, by=by)
selector = self.convert_to_css_selector(selector, by=by)
selector = self.__make_css_match_first_element_only(selector)
selector = self.__escape_quotes_if_needed(selector)
text = re.escape(text)
text = self.__escape_quotes_if_needed(text)
update_text_script = """jQuery('%s').val('%s');""" % (selector, text)
self.safe_execute_script(update_text_script)
if text.endswith("\n"):
element.send_keys("\n")
self.__demo_mode_pause_if_active()
def get_value(
self, selector, by=By.CSS_SELECTOR, timeout=None
):
"""This method uses JavaScript to get the value of an input field.
(Works on both input fields and textarea fields.)"""
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
self.wait_for_ready_state_complete()
self.wait_for_element_present(selector, by=by, timeout=timeout)
orginal_selector = selector
css_selector = self.convert_to_css_selector(selector, by=by)
self.__demo_mode_highlight_if_active(orginal_selector, by)
if not self.demo_mode and not self.slow_mode:
self.scroll_to(orginal_selector, by=by, timeout=timeout)
css_selector = re.escape(css_selector) # Add "\\" to special chars
css_selector = self.__escape_quotes_if_needed(css_selector)
if ":contains\\(" not in css_selector:
script = """return document.querySelector('%s').value;""" % (
css_selector
)
value = self.execute_script(script)
else:
script = """return jQuery('%s')[0].value;""" % css_selector
value = self.safe_execute_script(script)
return value
def set_time_limit(self, time_limit):
self.__check_scope()
if time_limit:
try:
sb_config.time_limit = float(time_limit)
except Exception:
sb_config.time_limit = None
else:
sb_config.time_limit = None
if sb_config.time_limit and sb_config.time_limit > 0:
sb_config.time_limit_ms = int(sb_config.time_limit * 1000.0)
self.time_limit = sb_config.time_limit
else:
self.time_limit = None
sb_config.time_limit = None
sb_config.time_limit_ms = None
def set_default_timeout(self, timeout):
"""This method changes the default timeout values of test methods
for the duration of the current test.
Effected timeouts: (used by methods that wait for elements)
* settings.SMALL_TIMEOUT - (default value: 6 seconds)
* settings.LARGE_TIMEOUT - (default value: 10 seconds)
The minimum allowable default timeout is: 0.5 seconds.
The maximum allowable default timeout is: 60.0 seconds.
(Test methods can still override timeouts outside that range.)
"""
self.__check_scope()
if not type(timeout) is int and not type(timeout) is float:
raise Exception('Expecting a numeric value for "timeout"!')
if timeout < 0:
raise Exception('The "timeout" cannot be a negative number!')
timeout = float(timeout)
# Min default timeout: 0.5 seconds. Max default timeout: 60.0 seconds.
min_timeout = 0.5
max_timeout = 60.0
if timeout < min_timeout:
logging.info("Minimum default timeout = %s" % min_timeout)
timeout = min_timeout
elif timeout > max_timeout:
logging.info("Maximum default timeout = %s" % max_timeout)
timeout = max_timeout
self.__overrided_default_timeouts = True
sb_config._is_timeout_changed = True
settings.SMALL_TIMEOUT = timeout
settings.LARGE_TIMEOUT = timeout
def reset_default_timeout(self):
"""Reset default timeout values to the original from settings.py
This method reverts the changes made by set_default_timeout()"""
if self.__overrided_default_timeouts:
if sb_config._SMALL_TIMEOUT and sb_config._LARGE_TIMEOUT:
settings.SMALL_TIMEOUT = sb_config._SMALL_TIMEOUT
settings.LARGE_TIMEOUT = sb_config._LARGE_TIMEOUT
sb_config._is_timeout_changed = False
self.__overrided_default_timeouts = False
def skip(self, reason=""):
""" Mark the test as Skipped. """
self.__check_scope()
if self.dashboard:
test_id = self.__get_test_id_2()
if hasattr(self, "_using_sb_fixture"):
test_id = sb_config._test_id
if (
test_id in sb_config._results.keys()
and sb_config._results[test_id] == "Passed"
):
# Duplicate tearDown() called where test already passed
self.__passed_then_skipped = True
self.__will_be_skipped = True
sb_config._results[test_id] = "Skipped"
if self.with_db_reporting:
if self.is_pytest:
self.__skip_reason = reason
else:
self._nose_skip_reason = reason
# Add skip reason to the logs
if not hasattr(self, "_using_sb_fixture"):
test_id = self.__get_test_id() # Recalculate the test id
test_logpath = os.path.join(self.log_path, test_id)
self.__create_log_path_as_needed(test_logpath)
browser = self.browser
if not reason:
reason = "No skip reason given"
log_helper.log_skipped_test_data(self, test_logpath, browser, reason)
# Finally skip the test for real
self.skipTest(reason)
############
# Shadow DOM / Shadow-root methods
def __get_shadow_element(self, selector, timeout=None):
self.wait_for_ready_state_complete()
if timeout is None:
timeout = settings.SMALL_TIMEOUT
elif timeout == 0:
timeout = 0.1 # Use for: is_shadow_element_* (* = present/visible)
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
self.__fail_if_invalid_shadow_selector_usage(selector)
if "::shadow " not in selector:
raise Exception(
'A Shadow DOM selector must contain at least one "::shadow "!'
)
selectors = selector.split("::shadow ")
element = self.get_element(selectors[0])
selector_chain = selectors[0]
for selector_part in selectors[1:]:
shadow_root = None
if (
selenium4
and self.is_chromium()
and int(self.__get_major_browser_version()) >= 96
):
try:
shadow_root = element.shadow_root
except Exception:
if self.browser == "chrome":
chrome_dict = self.driver.capabilities["chrome"]
chrome_dr_version = chrome_dict["chromedriverVersion"]
chromedriver_version = chrome_dr_version.split(" ")[0]
major_c_dr_version = chromedriver_version.split(".")[0]
if int(major_c_dr_version) < 96:
message = (
"You need to upgrade to a newer version of "
"chromedriver to interact with Shadow root "
"elements!\n(Current driver version is: %s)"
"\n(Minimum driver version is: 96.*)"
"\nTo upgrade: "
'"seleniumbase install chromedriver latest"'
% chromedriver_version
)
raise Exception(message)
if timeout != 0.1: # Skip wait for special 0.1 (See above)
time.sleep(2)
try:
shadow_root = element.shadow_root
except Exception:
raise Exception(
"Element {%s} has no shadow root!" % selector_chain
)
else: # This part won't work on Chrome 96 or newer.
# If using Chrome 96 or newer (and on an old Python version),
# you'll need to upgrade in order to access Shadow roots.
# Firefox users will likely hit:
# https://github.com/mozilla/geckodriver/issues/1711
# When Firefox adds support, switch to element.shadow_root
shadow_root = self.execute_script(
"return arguments[0].shadowRoot", element
)
if timeout == 0.1 and not shadow_root:
raise Exception(
"Element {%s} has no shadow root!" % selector_chain
)
elif not shadow_root:
time.sleep(2) # Wait two seconds for the shadow root to appear
shadow_root = self.execute_script(
"return arguments[0].shadowRoot", element
)
if not shadow_root:
raise Exception(
"Element {%s} has no shadow root!" % selector_chain
)
selector_chain += "::shadow "
selector_chain += selector_part
try:
if (
selenium4
and self.is_chromium()
and int(self.__get_major_browser_version()) >= 96
):
element = shadow_root.find_element(
By.CSS_SELECTOR, value=selector_part)
else:
element = page_actions.wait_for_element_present(
shadow_root,
selector_part,
by=By.CSS_SELECTOR,
timeout=timeout,
)
except Exception:
msg = (
"Shadow DOM Element {%s} was not present after %s seconds!"
% (selector_chain, timeout)
)
page_actions.timeout_exception("NoSuchElementException", msg)
return element
def __fail_if_invalid_shadow_selector_usage(self, selector):
if selector.strip().endswith("::shadow"):
msg = (
"A Shadow DOM selector cannot end on a shadow root element!"
" End the selector with an element inside the shadow root!"
)
raise Exception(msg)
def __is_shadow_selector(self, selector):
self.__fail_if_invalid_shadow_selector_usage(selector)
if "::shadow " in selector:
return True
return False
def __shadow_click(self, selector):
element = self.__get_shadow_element(selector)
element.click()
def __shadow_type(self, selector, text, clear_first=True):
element = self.__get_shadow_element(selector)
if clear_first:
try:
element.clear()
backspaces = Keys.BACK_SPACE * 42 # Autofill Defense
element.send_keys(backspaces)
except Exception:
pass
if type(text) is int or type(text) is float:
text = str(text)
if not text.endswith("\n"):
element.send_keys(text)
if settings.WAIT_FOR_RSC_ON_PAGE_LOADS:
self.wait_for_ready_state_complete()
else:
element.send_keys(text[:-1])
element.send_keys(Keys.RETURN)
if settings.WAIT_FOR_RSC_ON_PAGE_LOADS:
self.wait_for_ready_state_complete()
def __shadow_clear(self, selector):
element = self.__get_shadow_element(selector)
try:
element.clear()
backspaces = Keys.BACK_SPACE * 42 # Autofill Defense
element.send_keys(backspaces)
except Exception:
pass
def __get_shadow_text(self, selector):
element = self.__get_shadow_element(selector)
return element.text
def __wait_for_shadow_text_visible(self, text, selector):
start_ms = time.time() * 1000.0
stop_ms = start_ms + (settings.SMALL_TIMEOUT * 1000.0)
for x in range(int(settings.SMALL_TIMEOUT * 10)):
try:
actual_text = self.__get_shadow_text(selector).strip()
text = text.strip()
if text not in actual_text:
msg = (
"Expected text {%s} in element {%s} was not visible!"
% (text, selector)
)
page_actions.timeout_exception(
"ElementNotVisibleException", msg
)
return True
except Exception:
now_ms = time.time() * 1000.0
if now_ms >= stop_ms:
break
time.sleep(0.1)
actual_text = self.__get_shadow_text(selector).strip()
text = text.strip()
if text not in actual_text:
msg = "Expected text {%s} in element {%s} was not visible!" % (
text,
selector,
)
page_actions.timeout_exception("ElementNotVisibleException", msg)
return True
def __wait_for_exact_shadow_text_visible(self, text, selector):
start_ms = time.time() * 1000.0
stop_ms = start_ms + (settings.SMALL_TIMEOUT * 1000.0)
for x in range(int(settings.SMALL_TIMEOUT * 10)):
try:
actual_text = self.__get_shadow_text(selector).strip()
text = text.strip()
if text != actual_text:
msg = (
"Expected exact text {%s} in element {%s} not visible!"
"" % (text, selector)
)
page_actions.timeout_exception(
"ElementNotVisibleException", msg
)
return True
except Exception:
now_ms = time.time() * 1000.0
if now_ms >= stop_ms:
break
time.sleep(0.1)
actual_text = self.__get_shadow_text(selector).strip()
text = text.strip()
if text != actual_text:
msg = (
"Expected exact text {%s} in element {%s} was not visible!"
% (text, selector)
)
page_actions.timeout_exception("ElementNotVisibleException", msg)
return True
def __assert_shadow_text_visible(self, text, selector):
self.__wait_for_shadow_text_visible(text, selector)
if self.demo_mode:
a_t = "ASSERT TEXT"
i_n = "in"
by = By.CSS_SELECTOR
if self._language != "English":
from seleniumbase.fixtures.words import SD
a_t = SD.translate_assert_text(self._language)
i_n = SD.translate_in(self._language)
messenger_post = "%s: {%s} %s %s: %s" % (
a_t,
text,
i_n,
by.upper(),
selector,
)
try:
js_utils.activate_jquery(self.driver)
js_utils.post_messenger_success_message(
self.driver, messenger_post, self.message_duration
)
except Exception:
pass
def __assert_exact_shadow_text_visible(self, text, selector):
self.__wait_for_exact_shadow_text_visible(text, selector)
if self.demo_mode:
a_t = "ASSERT EXACT TEXT"
i_n = "in"
by = By.CSS_SELECTOR
if self._language != "English":
from seleniumbase.fixtures.words import SD
a_t = SD.translate_assert_exact_text(self._language)
i_n = SD.translate_in(self._language)
messenger_post = "%s: {%s} %s %s: %s" % (
a_t,
text,
i_n,
by.upper(),
selector,
)
try:
js_utils.activate_jquery(self.driver)
js_utils.post_messenger_success_message(
self.driver, messenger_post, self.message_duration
)
except Exception:
pass
def __is_shadow_element_present(self, selector):
try:
element = self.__get_shadow_element(selector, timeout=0.1)
return element is not None
except Exception:
return False
def __is_shadow_element_visible(self, selector):
try:
element = self.__get_shadow_element(selector, timeout=0.1)
return element.is_displayed()
except Exception:
return False
def __wait_for_shadow_element_present(self, selector):
element = self.__get_shadow_element(selector)
return element
def __wait_for_shadow_element_visible(self, selector):
element = self.__get_shadow_element(selector)
if not element.is_displayed():
msg = "Shadow DOM Element {%s} was not visible!" % selector
page_actions.timeout_exception("NoSuchElementException", msg)
return element
def __wait_for_shadow_attribute_present(
self, selector, attribute, value=None, timeout=None
):
element = self.__get_shadow_element(selector, timeout=timeout)
actual_value = element.get_attribute(attribute)
plural = "s"
if timeout == 1:
plural = ""
if value is None:
# The element attribute only needs to exist
if actual_value is not None:
return element
else:
# The element does not have the attribute
message = (
"Expected attribute {%s} of element {%s} "
"was not present after %s second%s!"
% (attribute, selector, timeout, plural)
)
page_actions.timeout_exception(
"NoSuchAttributeException", message
)
else:
if actual_value == value:
return element
else:
message = (
"Expected value {%s} for attribute {%s} of element "
"{%s} was not present after %s second%s! "
"(The actual value was {%s})"
% (
value,
attribute,
selector,
timeout,
plural,
actual_value,
)
)
page_actions.timeout_exception(
"NoSuchAttributeException", message
)
def __assert_shadow_element_present(self, selector):
self.__get_shadow_element(selector)
if self.demo_mode:
a_t = "ASSERT"
by = By.CSS_SELECTOR
if self._language != "English":
from seleniumbase.fixtures.words import SD
a_t = SD.translate_assert(self._language)
messenger_post = "%s %s: %s" % (a_t, by.upper(), selector)
try:
js_utils.activate_jquery(self.driver)
js_utils.post_messenger_success_message(
self.driver, messenger_post, self.message_duration
)
except Exception:
pass
def __assert_shadow_element_visible(self, selector):
element = self.__get_shadow_element(selector)
if not element.is_displayed():
msg = "Shadow DOM Element {%s} was not visible!" % selector
page_actions.timeout_exception("NoSuchElementException", msg)
if self.demo_mode:
a_t = "ASSERT"
by = By.CSS_SELECTOR
if self._language != "English":
from seleniumbase.fixtures.words import SD
a_t = SD.translate_assert(self._language)
messenger_post = "%s %s: %s" % (a_t, by.upper(), selector)
try:
js_utils.activate_jquery(self.driver)
js_utils.post_messenger_success_message(
self.driver, messenger_post, self.message_duration
)
except Exception:
pass
############
# Application "Local Storage" controls
def set_local_storage_item(self, key, value):
self.__check_scope()
self.execute_script(
"window.localStorage.setItem('{}', '{}');".format(key, value)
)
def get_local_storage_item(self, key):
self.__check_scope()
return self.execute_script(
"return window.localStorage.getItem('{}');".format(key)
)
def remove_local_storage_item(self, key):
self.__check_scope()
self.execute_script(
"window.localStorage.removeItem('{}');".format(key)
)
def clear_local_storage(self):
self.__check_scope()
self.execute_script("window.localStorage.clear();")
if self.recorder_mode:
time_stamp = self.execute_script("return Date.now();")
origin = self.get_origin()
action = ["c_l_s", "", origin, time_stamp]
self.__extra_actions.append(action)
def get_local_storage_keys(self):
self.__check_scope()
return self.execute_script(
"var ls = window.localStorage, keys = []; "
"for (var i = 0; i < ls.length; ++i) "
" keys[i] = ls.key(i); "
"return keys;"
)
def get_local_storage_items(self):
self.__check_scope()
return self.execute_script(
r"var ls = window.localStorage, items = {}; "
"for (var i = 0, k; i < ls.length; ++i) "
" items[k = ls.key(i)] = ls.getItem(k); "
"return items;"
)
# Application "Session Storage" controls
def set_session_storage_item(self, key, value):
self.__check_scope()
self.execute_script(
"window.sessionStorage.setItem('{}', '{}');".format(key, value)
)
def get_session_storage_item(self, key):
self.__check_scope()
return self.execute_script(
"return window.sessionStorage.getItem('{}');".format(key)
)
def remove_session_storage_item(self, key):
self.__check_scope()
self.execute_script(
"window.sessionStorage.removeItem('{}');".format(key)
)
def clear_session_storage(self):
self.__check_scope()
self.execute_script("window.sessionStorage.clear();")
def get_session_storage_keys(self):
self.__check_scope()
return self.execute_script(
"var ls = window.sessionStorage, keys = []; "
"for (var i = 0; i < ls.length; ++i) "
" keys[i] = ls.key(i); "
"return keys;"
)
def get_session_storage_items(self):
self.__check_scope()
return self.execute_script(
r"var ls = window.sessionStorage, items = {}; "
"for (var i = 0, k; i < ls.length; ++i) "
" items[k = ls.key(i)] = ls.getItem(k); "
"return items;"
)
############
# Duplicates (Avoids name confusion when migrating from other frameworks.)
def open_url(self, url):
""" Same as self.open() """
self.open(url)
def visit(self, url):
""" Same as self.open() """
self.open(url)
def visit_url(self, url):
""" Same as self.open() """
self.open(url)
def goto(self, url):
""" Same as self.open() """
self.open(url)
def go_to(self, url):
""" Same as self.open() """
self.open(url)
def reload(self):
""" Same as self.refresh_page() """
self.refresh_page()
def reload_page(self):
""" Same as self.refresh_page() """
self.refresh_page()
def open_new_tab(self, switch_to=True):
""" Same as self.open_new_window() """
self.open_new_window(switch_to=switch_to)
def switch_to_tab(self, tab, timeout=None):
""" Same as self.switch_to_window()
Switches control of the browser to the specified window.
The window can be an integer: 0 -> 1st tab, 1 -> 2nd tab, etc...
Or it can be a list item from self.driver.window_handles """
self.switch_to_window(window=tab, timeout=timeout)
def switch_to_default_tab(self):
""" Same as self.switch_to_default_window() """
self.switch_to_default_window()
def switch_to_newest_tab(self):
""" Same as self.switch_to_newest_window() """
self.switch_to_newest_window()
def input(
self, selector, text, by=By.CSS_SELECTOR, timeout=None, retry=False
):
""" Same as self.update_text() """
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
self.update_text(selector, text, by=by, timeout=timeout, retry=retry)
def fill(
self, selector, text, by=By.CSS_SELECTOR, timeout=None, retry=False
):
""" Same as self.update_text() """
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
self.update_text(selector, text, by=by, timeout=timeout, retry=retry)
def write(
self, selector, text, by=By.CSS_SELECTOR, timeout=None, retry=False
):
""" Same as self.update_text() """
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
self.update_text(selector, text, by=by, timeout=timeout, retry=retry)
def send_keys(self, selector, text, by=By.CSS_SELECTOR, timeout=None):
""" Same as self.add_text() """
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
self.add_text(selector, text, by=by, timeout=timeout)
def click_link(self, link_text, timeout=None):
""" Same as self.click_link_text() """
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
self.click_link_text(link_text, timeout=timeout)
def click_partial_link(self, partial_link_text, timeout=None):
""" Same as self.click_partial_link_text() """
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
self.click_partial_link_text(partial_link_text, timeout=timeout)
def wait_for_element_visible(
self, selector, by=By.CSS_SELECTOR, timeout=None
):
""" Same as self.wait_for_element() """
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
if self.__is_shadow_selector(selector):
return self.__wait_for_shadow_element_visible(selector)
return page_actions.wait_for_element_visible(
self.driver, selector, by, timeout
)
def wait_for_element_not_present(
self, selector, by=By.CSS_SELECTOR, timeout=None
):
"""Same as self.wait_for_element_absent()
Waits for an element to no longer appear in the HTML of a page.
A hidden element still counts as appearing in the page HTML.
If waiting for elements to be hidden instead of nonexistent,
use wait_for_element_not_visible() instead.
"""
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
return page_actions.wait_for_element_absent(
self.driver, selector, by, timeout
)
def assert_element_not_present(
self, selector, by=By.CSS_SELECTOR, timeout=None
):
"""Same as self.assert_element_absent()
Will raise an exception if the element stays present.
A hidden element counts as a present element, which fails this assert.
If you want to assert that elements are hidden instead of nonexistent,
use assert_element_not_visible() instead.
(Note that hidden elements are still present in the HTML of the page.)
Returns True if successful. Default timeout = SMALL_TIMEOUT."""
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
self.wait_for_element_absent(selector, by=by, timeout=timeout)
return True
def get_google_auth_password(self, totp_key=None):
""" Same as self.get_mfa_code() """
return self.get_mfa_code(totp_key=totp_key)
def get_google_auth_code(self, totp_key=None):
""" Same as self.get_mfa_code() """
return self.get_mfa_code(totp_key=totp_key)
def get_totp_code(self, totp_key=None):
""" Same as self.get_mfa_code() """
return self.get_mfa_code(totp_key=totp_key)
def enter_totp_code(
self, selector, totp_key=None, by=By.CSS_SELECTOR, timeout=None
):
""" Same as self.enter_mfa_code() """
return self.enter_mfa_code(
selector=selector, totp_key=totp_key, by=by, timeout=timeout
)
def assert_no_broken_links(self, multithreaded=True):
""" Same as self.assert_no_404_errors() """
self.assert_no_404_errors(multithreaded=multithreaded)
def wait(self, seconds):
""" Same as self.sleep() - Some JS frameworks use this method name. """
self.sleep(seconds)
def block_ads(self):
""" Same as self.ad_block() """
self.ad_block()
def _print(self, msg):
"""Same as Python's print(), but won't print during multithreaded runs
because overlapping print() commands may lead to unexpected output.
In most cases, the print() command won't print for multithreaded tests,
but there are some exceptions, and this will take care of those.
Here's an example of running tests multithreaded: "pytest -n=4".
To force a print during multithreaded tests, use: "sys.stderr.write()".
To print without the new-line character end, use: "sys.stdout.write()".
"""
if not sb_config._multithreaded:
print(msg)
def start_tour(self, name=None, interval=0):
self.play_tour(name=name, interval=interval)
############
def add_css_link(self, css_link):
self.__check_scope()
self.__check_browser()
js_utils.add_css_link(self.driver, css_link)
def add_js_link(self, js_link):
self.__check_scope()
self.__check_browser()
js_utils.add_js_link(self.driver, js_link)
def add_css_style(self, css_style):
self.__check_scope()
self.__check_browser()
js_utils.add_css_style(self.driver, css_style)
def add_js_code_from_link(self, js_link):
self.__check_scope()
self.__check_browser()
js_utils.add_js_code_from_link(self.driver, js_link)
def add_js_code(self, js_code):
self.__check_scope()
self.__check_browser()
js_utils.add_js_code(self.driver, js_code)
def add_meta_tag(self, http_equiv=None, content=None):
self.__check_scope()
self.__check_browser()
js_utils.add_meta_tag(
self.driver, http_equiv=http_equiv, content=content
)
############
def create_presentation(
self, name=None, theme="default", transition="default"
):
"""Creates a Reveal-JS presentation that you can add slides to.
@Params
name - If creating multiple presentations at the same time,
use this to specify the name of the current presentation.
theme - Set a theme with a unique style for the presentation.
Valid themes: "serif" (default), "sky", "white", "black",
"simple", "league", "moon", "night",
"beige", "blood", and "solarized".
transition - Set a transition between slides.
Valid transitions: "none" (default), "slide", "fade",
"zoom", "convex", and "concave".
"""
if not name:
name = "default"
if not theme or theme == "default":
theme = "serif"
valid_themes = [
"serif",
"white",
"black",
"beige",
"simple",
"sky",
"league",
"moon",
"night",
"blood",
"solarized",
]
theme = theme.lower()
if theme not in valid_themes:
raise Exception(
"Theme {%s} not found! Valid themes: %s"
% (theme, valid_themes)
)
if not transition or transition == "default":
transition = "none"
valid_transitions = [
"none",
"slide",
"fade",
"zoom",
"convex",
"concave",
]
transition = transition.lower()
if transition not in valid_transitions:
raise Exception(
"Transition {%s} not found! Valid transitions: %s"
% (transition, valid_transitions)
)
reveal_theme_css = None
if theme == "serif":
reveal_theme_css = constants.Reveal.SERIF_MIN_CSS
elif theme == "sky":
reveal_theme_css = constants.Reveal.SKY_MIN_CSS
elif theme == "white":
reveal_theme_css = constants.Reveal.WHITE_MIN_CSS
elif theme == "black":
reveal_theme_css = constants.Reveal.BLACK_MIN_CSS
elif theme == "simple":
reveal_theme_css = constants.Reveal.SIMPLE_MIN_CSS
elif theme == "league":
reveal_theme_css = constants.Reveal.LEAGUE_MIN_CSS
elif theme == "moon":
reveal_theme_css = constants.Reveal.MOON_MIN_CSS
elif theme == "night":
reveal_theme_css = constants.Reveal.NIGHT_MIN_CSS
elif theme == "beige":
reveal_theme_css = constants.Reveal.BEIGE_MIN_CSS
elif theme == "blood":
reveal_theme_css = constants.Reveal.BLOOD_MIN_CSS
elif theme == "solarized":
reveal_theme_css = constants.Reveal.SOLARIZED_MIN_CSS
else:
# Use the default if unable to determine the theme
reveal_theme_css = constants.Reveal.SERIF_MIN_CSS
new_presentation = (
"<html>\n"
"<head>\n"
'<meta charset="utf-8">\n'
'<meta http-equiv="Content-Type" content="text/html">\n'
'<meta name="viewport" content="shrink-to-fit=no">\n'
'<link rel="stylesheet" href="%s">\n'
'<link rel="stylesheet" href="%s">\n'
"<style>\n"
"pre{background-color:#fbe8d4;border-radius:8px;}\n"
"div[flex_div]{height:68vh;margin:0;align-items:center;"
"justify-content:center;}\n"
"img[rounded]{border-radius:16px;max-width:64%%;}\n"
"</style>\n"
"</head>\n\n"
"<body>\n"
"<!-- Generated by SeleniumBase - https://seleniumbase.io -->\n"
'<div class="reveal">\n'
'<div class="slides">\n'
% (constants.Reveal.MIN_CSS, reveal_theme_css)
)
self._presentation_slides[name] = []
self._presentation_slides[name].append(new_presentation)
self._presentation_transition[name] = transition
def add_slide(
self,
content=None,
image=None,
code=None,
iframe=None,
content2=None,
notes=None,
transition=None,
name=None,
):
"""Allows the user to add slides to a presentation.
@Params
content - The HTML content to display on the presentation slide.
image - Attach an image (from a URL link) to the slide.
code - Attach code of any programming language to the slide.
Language-detection will be used to add syntax formatting.
iframe - Attach an iFrame (from a URL link) to the slide.
content2 - HTML content to display after adding an image or code.
notes - Additional notes to include with the slide.
ONLY SEEN if show_notes is set for the presentation.
transition - Set a transition between slides. (overrides previous)
Valid transitions: "none" (default), "slide", "fade",
"zoom", "convex", and "concave".
name - If creating multiple presentations at the same time,
use this to select the presentation to add slides to.
"""
if not name:
name = "default"
if name not in self._presentation_slides:
# Create a presentation if it doesn't already exist
self.create_presentation(name=name)
if not content:
content = ""
if not content2:
content2 = ""
if not notes:
notes = ""
if not transition:
transition = self._presentation_transition[name]
elif transition == "default":
transition = "none"
valid_transitions = [
"none",
"slide",
"fade",
"zoom",
"convex",
"concave",
]
transition = transition.lower()
if transition not in valid_transitions:
raise Exception(
"Transition {%s} not found! Valid transitions: %s"
"" % (transition, valid_transitions)
)
add_line = ""
if content.startswith("<"):
add_line = "\n"
html = '\n<section data-transition="%s">%s%s' % (
transition,
add_line,
content,
)
if image:
html += '\n<div flex_div><img rounded src="%s" /></div>' % image
if code:
html += "\n<div></div>"
html += '\n<pre class="prettyprint">\n%s</pre>' % code
if iframe:
html += (
"\n<div></div>"
'\n<iframe src="%s" style="width:92%%;height:550px;" '
'title="iframe content"></iframe>' % iframe
)
add_line = ""
if content2.startswith("<"):
add_line = "\n"
if content2:
html += "%s%s" % (add_line, content2)
html += '\n<aside class="notes">%s</aside>' % notes
html += "\n</section>\n"
self._presentation_slides[name].append(html)
def save_presentation(
self, name=None, filename=None, show_notes=False, interval=0
):
"""Saves a Reveal-JS Presentation to a file for later use.
@Params
name - If creating multiple presentations at the same time,
use this to select the one you wish to use.
filename - The name of the HTML file that you wish to
save the presentation to. (filename must end in ".html")
show_notes - When set to True, the Notes feature becomes enabled,
which allows presenters to see notes next to slides.
interval - The delay time between autoplaying slides. (in seconds)
If set to 0 (default), autoplay is disabled.
"""
if not name:
name = "default"
if not filename:
filename = "my_presentation.html"
if name not in self._presentation_slides:
raise Exception("Presentation {%s} does not exist!" % name)
if not filename.endswith(".html"):
raise Exception('Presentation file must end in ".html"!')
if not interval:
interval = 0
if interval == 0 and self.interval:
interval = float(self.interval)
if not type(interval) is int and not type(interval) is float:
raise Exception('Expecting a numeric value for "interval"!')
if interval < 0:
raise Exception('The "interval" cannot be a negative number!')
interval_ms = float(interval) * 1000.0
show_notes_str = "false"
if show_notes:
show_notes_str = "true"
the_html = ""
for slide in self._presentation_slides[name]:
the_html += slide
the_html += (
"\n</div>\n"
"</div>\n"
'<script src="%s"></script>\n'
'<script src="%s"></script>\n'
"<script>Reveal.initialize("
"{showNotes: %s, slideNumber: true, progress: true, hash: false, "
"autoSlide: %s,});"
"</script>\n"
"</body>\n"
"</html>\n"
% (
constants.Reveal.MIN_JS,
constants.PrettifyJS.RUN_PRETTIFY_JS,
show_notes_str,
interval_ms,
)
)
# Remove duplicate ChartMaker library declarations
chart_libs = """
<script src="%s"></script>
<script src="%s"></script>
<script src="%s"></script>
<script src="%s"></script>
""" % (
constants.HighCharts.HC_JS,
constants.HighCharts.EXPORTING_JS,
constants.HighCharts.EXPORT_DATA_JS,
constants.HighCharts.ACCESSIBILITY_JS,
)
if the_html.count(chart_libs) > 1:
chart_libs_comment = "<!-- HighCharts Libraries Imported -->"
the_html = the_html.replace(chart_libs, chart_libs_comment)
# Only need to import the HighCharts libraries once
the_html = the_html.replace(chart_libs_comment, chart_libs, 1)
saved_presentations_folder = constants.Presentations.SAVED_FOLDER
if saved_presentations_folder.endswith("/"):
saved_presentations_folder = saved_presentations_folder[:-1]
if not os.path.exists(saved_presentations_folder):
try:
os.makedirs(saved_presentations_folder)
except Exception:
pass
file_path = saved_presentations_folder + "/" + filename
out_file = codecs.open(file_path, "w+", encoding="utf-8")
out_file.writelines(the_html)
out_file.close()
print("\n>>> [%s] was saved!\n" % file_path)
return file_path
def begin_presentation(
self, name=None, filename=None, show_notes=False, interval=0
):
"""Begin a Reveal-JS Presentation in the web browser.
@Params
name - If creating multiple presentations at the same time,
use this to select the one you wish to use.
filename - The name of the HTML file that you wish to
save the presentation to. (filename must end in ".html")
show_notes - When set to True, the Notes feature becomes enabled,
which allows presenters to see notes next to slides.
interval - The delay time between autoplaying slides. (in seconds)
If set to 0 (default), autoplay is disabled.
"""
if self.headless or self.xvfb:
return # Presentations should not run in headless mode.
if not name:
name = "default"
if not filename:
filename = "my_presentation.html"
if name not in self._presentation_slides:
raise Exception("Presentation {%s} does not exist!" % name)
if not filename.endswith(".html"):
raise Exception('Presentation file must end in ".html"!')
if not interval:
interval = 0
if interval == 0 and self.interval:
interval = float(self.interval)
if not type(interval) is int and not type(interval) is float:
raise Exception('Expecting a numeric value for "interval"!')
if interval < 0:
raise Exception('The "interval" cannot be a negative number!')
end_slide = (
'\n<section data-transition="none">\n'
'<p class="End_Presentation_Now"> </p>\n</section>\n'
)
self._presentation_slides[name].append(end_slide)
file_path = self.save_presentation(
name=name,
filename=filename,
show_notes=show_notes,
interval=interval,
)
self._presentation_slides[name].pop()
self.open_html_file(file_path)
presentation_folder = constants.Presentations.SAVED_FOLDER
try:
while (
len(self.driver.window_handles) > 0
and presentation_folder in self.get_current_url()
):
time.sleep(0.05)
if self.is_element_visible(
"section.present p.End_Presentation_Now"
):
break
time.sleep(0.05)
except Exception:
pass
############
def create_pie_chart(
self,
chart_name=None,
title=None,
subtitle=None,
data_name=None,
unit=None,
libs=True,
labels=True,
legend=True,
):
"""Creates a JavaScript pie chart using "HighCharts".
@Params
chart_name - If creating multiple charts,
use this to select which one.
title - The title displayed for the chart.
subtitle - The subtitle displayed for the chart.
data_name - The series name. Useful for multi-series charts.
If no data_name, will default to using "Series 1".
unit - The description label given to the chart's y-axis values.
libs - The option to include Chart libraries (JS and CSS files).
Should be set to True (default) for the first time creating
a chart on a web page. If creating multiple charts on the
same web page, you won't need to re-import the libraries
when creating additional charts.
labels - If True, displays labels on the chart for data points.
legend - If True, displays the data point legend on the chart.
"""
if not chart_name:
chart_name = "default"
if not data_name:
data_name = ""
style = "pie"
self.__create_highchart(
chart_name=chart_name,
title=title,
subtitle=subtitle,
style=style,
data_name=data_name,
unit=unit,
libs=libs,
labels=labels,
legend=legend,
)
def create_bar_chart(
self,
chart_name=None,
title=None,
subtitle=None,
data_name=None,
unit=None,
libs=True,
labels=True,
legend=True,
):
"""Creates a JavaScript bar chart using "HighCharts".
@Params
chart_name - If creating multiple charts,
use this to select which one.
title - The title displayed for the chart.
subtitle - The subtitle displayed for the chart.
data_name - The series name. Useful for multi-series charts.
If no data_name, will default to using "Series 1".
unit - The description label given to the chart's y-axis values.
libs - The option to include Chart libraries (JS and CSS files).
Should be set to True (default) for the first time creating
a chart on a web page. If creating multiple charts on the
same web page, you won't need to re-import the libraries
when creating additional charts.
labels - If True, displays labels on the chart for data points.
legend - If True, displays the data point legend on the chart.
"""
if not chart_name:
chart_name = "default"
if not data_name:
data_name = ""
style = "bar"
self.__create_highchart(
chart_name=chart_name,
title=title,
subtitle=subtitle,
style=style,
data_name=data_name,
unit=unit,
libs=libs,
labels=labels,
legend=legend,
)
def create_column_chart(
self,
chart_name=None,
title=None,
subtitle=None,
data_name=None,
unit=None,
libs=True,
labels=True,
legend=True,
):
"""Creates a JavaScript column chart using "HighCharts".
@Params
chart_name - If creating multiple charts,
use this to select which one.
title - The title displayed for the chart.
subtitle - The subtitle displayed for the chart.
data_name - The series name. Useful for multi-series charts.
If no data_name, will default to using "Series 1".
unit - The description label given to the chart's y-axis values.
libs - The option to include Chart libraries (JS and CSS files).
Should be set to True (default) for the first time creating
a chart on a web page. If creating multiple charts on the
same web page, you won't need to re-import the libraries
when creating additional charts.
labels - If True, displays labels on the chart for data points.
legend - If True, displays the data point legend on the chart.
"""
if not chart_name:
chart_name = "default"
if not data_name:
data_name = ""
style = "column"
self.__create_highchart(
chart_name=chart_name,
title=title,
subtitle=subtitle,
style=style,
data_name=data_name,
unit=unit,
libs=libs,
labels=labels,
legend=legend,
)
def create_line_chart(
self,
chart_name=None,
title=None,
subtitle=None,
data_name=None,
unit=None,
zero=False,
libs=True,
labels=True,
legend=True,
):
"""Creates a JavaScript line chart using "HighCharts".
@Params
chart_name - If creating multiple charts,
use this to select which one.
title - The title displayed for the chart.
subtitle - The subtitle displayed for the chart.
data_name - The series name. Useful for multi-series charts.
If no data_name, will default to using "Series 1".
unit - The description label given to the chart's y-axis values.
zero - If True, the y-axis always starts at 0. (Default: False).
libs - The option to include Chart libraries (JS and CSS files).
Should be set to True (default) for the first time creating
a chart on a web page. If creating multiple charts on the
same web page, you won't need to re-import the libraries
when creating additional charts.
labels - If True, displays labels on the chart for data points.
legend - If True, displays the data point legend on the chart.
"""
if not chart_name:
chart_name = "default"
if not data_name:
data_name = ""
style = "line"
self.__create_highchart(
chart_name=chart_name,
title=title,
subtitle=subtitle,
style=style,
data_name=data_name,
unit=unit,
zero=zero,
libs=libs,
labels=labels,
legend=legend,
)
def create_area_chart(
self,
chart_name=None,
title=None,
subtitle=None,
data_name=None,
unit=None,
zero=False,
libs=True,
labels=True,
legend=True,
):
"""Creates a JavaScript area chart using "HighCharts".
@Params
chart_name - If creating multiple charts,
use this to select which one.
title - The title displayed for the chart.
subtitle - The subtitle displayed for the chart.
data_name - The series name. Useful for multi-series charts.
If no data_name, will default to using "Series 1".
unit - The description label given to the chart's y-axis values.
zero - If True, the y-axis always starts at 0. (Default: False).
libs - The option to include Chart libraries (JS and CSS files).
Should be set to True (default) for the first time creating
a chart on a web page. If creating multiple charts on the
same web page, you won't need to re-import the libraries
when creating additional charts.
labels - If True, displays labels on the chart for data points.
legend - If True, displays the data point legend on the chart.
"""
if not chart_name:
chart_name = "default"
if not data_name:
data_name = ""
style = "area"
self.__create_highchart(
chart_name=chart_name,
title=title,
subtitle=subtitle,
style=style,
data_name=data_name,
unit=unit,
zero=zero,
libs=libs,
labels=labels,
legend=legend,
)
def __create_highchart(
self,
chart_name=None,
title=None,
subtitle=None,
style=None,
data_name=None,
unit=None,
zero=False,
libs=True,
labels=True,
legend=True,
):
""" Creates a JavaScript chart using the "HighCharts" library. """
if not chart_name:
chart_name = "default"
if not title:
title = ""
if not subtitle:
subtitle = ""
if not style:
style = "pie"
if not data_name:
data_name = "Series 1"
if not unit:
unit = "Values"
if labels:
labels = "true"
else:
labels = "false"
if legend:
legend = "true"
else:
legend = "false"
title = title.replace("'", "\\'")
subtitle = subtitle.replace("'", "\\'")
unit = unit.replace("'", "\\'")
self._chart_count += 1
# If chart_libs format is changed, also change: save_presentation()
chart_libs = """
<script src="%s"></script>
<script src="%s"></script>
<script src="%s"></script>
<script src="%s"></script>
""" % (
constants.HighCharts.HC_JS,
constants.HighCharts.EXPORTING_JS,
constants.HighCharts.EXPORT_DATA_JS,
constants.HighCharts.ACCESSIBILITY_JS,
)
if not libs:
chart_libs = ""
chart_css = """
<style>
.highcharts-figure, .highcharts-data-table table {
min-width: 320px;
max-width: 660px;
margin: 1em auto;
}
.highcharts-data-table table {
font-family: Verdana, sans-serif;
border-collapse: collapse;
border: 1px solid #EBEBEB;
margin: 10px auto;
text-align: center;
width: 100%;
max-width: 500px;
}
.highcharts-data-table caption {
padding: 1em 0;
font-size: 1.2em;
color: #555;
}
.highcharts-data-table th {
font-weight: 600;
padding: 0.5em;
}
.highcharts-data-table td, .highcharts-data-table th,
.highcharts-data-table caption {
padding: 0.5em;
}
.highcharts-data-table thead tr,
.highcharts-data-table tr:nth-child(even) {
background: #f8f8f8;
}
.highcharts-data-table tr:hover {
background: #f1f7ff;
}
</style>
"""
if not libs:
chart_css = ""
chart_description = ""
chart_figure = """
<figure class="highcharts-figure">
<div id="chartcontainer_num_%s"></div>
<p class="highcharts-description">%s</p>
</figure>
""" % (
self._chart_count,
chart_description,
)
min_zero = ""
if zero:
min_zero = "min: 0,"
chart_init_1 = """
<script>
// Build the chart
Highcharts.chart('chartcontainer_num_%s', {
credits: {
enabled: false
},
title: {
text: '%s'
},
subtitle: {
text: '%s'
},
xAxis: { },
yAxis: {
%s
title: {
text: '%s',
style: {
fontSize: '14px'
}
},
labels: {
useHTML: true,
style: {
fontSize: '14px'
}
}
},
chart: {
renderTo: 'statusChart',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: '%s'
},
""" % (
self._chart_count,
title,
subtitle,
min_zero,
unit,
style,
)
# "{series.name}:"
point_format = (
r"<b>{point.y}</b><br />" r"<b>{point.percentage:.1f}%</b>"
)
if style != "pie":
point_format = r"<b>{point.y}</b>"
chart_init_2 = (
"""
tooltip: {
enabled: true,
useHTML: true,
style: {
padding: '6px',
fontSize: '14px'
},
backgroundColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops: [
[0, 'rgba(255, 255, 255, 0.78)'],
[0.5, 'rgba(235, 235, 235, 0.76)'],
[1, 'rgba(244, 252, 255, 0.74)']
]
},
hideDelay: 40,
pointFormat: '%s'
},
"""
% point_format
)
chart_init_3 = """
accessibility: {
point: {
valueSuffix: '%%'
}
},
plotOptions: {
series: {
states: {
inactive: {
opacity: 0.85
}
}
},
pie: {
size: "95%%",
allowPointSelect: true,
animation: false,
cursor: 'pointer',
dataLabels: {
enabled: %s,
formatter: function() {
if (this.y > 0) {
return this.point.name + ': ' + this.point.y
}
}
},
states: {
hover: {
enabled: true
}
},
showInLegend: %s
}
},
""" % (
labels,
legend,
)
if style != "pie":
chart_init_3 = """
allowPointSelect: true,
cursor: 'pointer',
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
states: {
hover: {
enabled: true
}
},
plotOptions: {
series: {
dataLabels: {
enabled: %s
},
showInLegend: %s,
animation: false,
shadow: false,
lineWidth: 3,
fillOpacity: 0.5,
marker: {
enabled: true
}
}
},
""" % (
labels,
legend,
)
chart_init = chart_init_1 + chart_init_2 + chart_init_3
color_by_point = "true"
if style != "pie":
color_by_point = "false"
series = """
series: [{
name: '%s',
colorByPoint: %s,
data: [
""" % (
data_name,
color_by_point,
)
new_chart = chart_libs + chart_css + chart_figure + chart_init + series
self._chart_data[chart_name] = []
self._chart_label[chart_name] = []
self._chart_data[chart_name].append(new_chart)
self._chart_first_series[chart_name] = True
self._chart_series_count[chart_name] = 1
def add_series_to_chart(self, data_name=None, chart_name=None):
"""Add a new data series to an existing chart.
This allows charts to have multiple data sets.
@Params
data_name - Set the series name. Useful for multi-series charts.
chart_name - If creating multiple charts,
use this to select which one.
"""
if not chart_name:
chart_name = "default"
self._chart_series_count[chart_name] += 1
if not data_name:
data_name = "Series %s" % self._chart_series_count[chart_name]
series = (
"""
]
},
{
name: '%s',
colorByPoint: false,
data: [
"""
% data_name
)
self._chart_data[chart_name].append(series)
self._chart_first_series[chart_name] = False
def add_data_point(self, label, value, color=None, chart_name=None):
"""Add a data point to a SeleniumBase-generated chart.
@Params
label - The label name for the data point.
value - The numeric value of the data point.
color - The HTML color of the data point.
Can be an RGB color. Eg: "#55ACDC".
Can also be a named color. Eg: "Teal".
chart_name - If creating multiple charts,
use this to select which one.
"""
if not chart_name:
chart_name = "default"
if chart_name not in self._chart_data:
# Create a chart if it doesn't already exist
self.create_pie_chart(chart_name=chart_name)
if not value:
value = 0
if not type(value) is int and not type(value) is float:
raise Exception('Expecting a numeric value for "value"!')
if not color:
color = ""
label = label.replace("'", "\\'")
color = color.replace("'", "\\'")
data_point = """
{
name: '%s',
y: %s,
color: '%s'
},
""" % (
label,
value,
color,
)
self._chart_data[chart_name].append(data_point)
if self._chart_first_series[chart_name]:
self._chart_label[chart_name].append(label)
def save_chart(self, chart_name=None, filename=None, folder=None):
"""Saves a SeleniumBase-generated chart to a file for later use.
@Params
chart_name - If creating multiple charts at the same time,
use this to select the one you wish to use.
filename - The name of the HTML file that you wish to
save the chart to. (filename must end in ".html")
folder - The name of the folder where you wish to
save the HTML file. (Default: "./saved_charts/")
"""
if not chart_name:
chart_name = "default"
if not filename:
filename = "my_chart.html"
if chart_name not in self._chart_data:
raise Exception("Chart {%s} does not exist!" % chart_name)
if not filename.endswith(".html"):
raise Exception('Chart file must end in ".html"!')
the_html = '<meta charset="utf-8">\n'
the_html += '<meta http-equiv="Content-Type" content="text/html">\n'
the_html += '<meta name="viewport" content="shrink-to-fit=no">\n'
for chart_data_point in self._chart_data[chart_name]:
the_html += chart_data_point
the_html += """
]
}]
});
</script>
"""
axis = "xAxis: {\n"
axis += " labels: {\n"
axis += " useHTML: true,\n"
axis += " style: {\n"
axis += " fontSize: '14px',\n"
axis += " },\n"
axis += " },\n"
axis += " categories: ["
for label in self._chart_label[chart_name]:
axis += "'%s'," % label
axis += "], crosshair: false},"
the_html = the_html.replace("xAxis: { },", axis)
if not folder:
saved_charts_folder = constants.Charts.SAVED_FOLDER
else:
saved_charts_folder = folder
if saved_charts_folder.endswith("/"):
saved_charts_folder = saved_charts_folder[:-1]
if not os.path.exists(saved_charts_folder):
try:
os.makedirs(saved_charts_folder)
except Exception:
pass
file_path = saved_charts_folder + "/" + filename
out_file = codecs.open(file_path, "w+", encoding="utf-8")
out_file.writelines(the_html)
out_file.close()
print("\n>>> [%s] was saved!" % file_path)
return file_path
def display_chart(self, chart_name=None, filename=None, interval=0):
"""Displays a SeleniumBase-generated chart in the browser window.
@Params
chart_name - If creating multiple charts at the same time,
use this to select the one you wish to use.
filename - The name of the HTML file that you wish to
save the chart to. (filename must end in ".html")
interval - The delay time for auto-advancing charts. (in seconds)
If set to 0 (default), auto-advancing is disabled.
"""
if self.headless or self.xvfb:
interval = 1 # Race through chart if running in headless mode
if not chart_name:
chart_name = "default"
if not filename:
filename = "my_chart.html"
if not interval:
interval = 0
if interval == 0 and self.interval:
interval = float(self.interval)
if not type(interval) is int and not type(interval) is float:
raise Exception('Expecting a numeric value for "interval"!')
if interval < 0:
raise Exception('The "interval" cannot be a negative number!')
if chart_name not in self._chart_data:
raise Exception("Chart {%s} does not exist!" % chart_name)
if not filename.endswith(".html"):
raise Exception('Chart file must end in ".html"!')
file_path = self.save_chart(chart_name=chart_name, filename=filename)
self.open_html_file(file_path)
chart_folder = constants.Charts.SAVED_FOLDER
if interval == 0:
try:
print("\n*** Close the browser window to continue ***")
# Will also continue if manually navigating to a new page
while len(self.driver.window_handles) > 0 and (
chart_folder in self.get_current_url()
):
time.sleep(0.05)
except Exception:
pass
else:
try:
start_ms = time.time() * 1000.0
stop_ms = start_ms + (interval * 1000.0)
for x in range(int(interval * 10)):
now_ms = time.time() * 1000.0
if now_ms >= stop_ms:
break
if len(self.driver.window_handles) == 0:
break
if chart_folder not in self.get_current_url():
break
time.sleep(0.1)
except Exception:
pass
def extract_chart(self, chart_name=None):
"""Extracts the HTML from a SeleniumBase-generated chart.
@Params
chart_name - If creating multiple charts at the same time,
use this to select the one you wish to use.
"""
if not chart_name:
chart_name = "default"
if chart_name not in self._chart_data:
raise Exception("Chart {%s} does not exist!" % chart_name)
the_html = ""
for chart_data_point in self._chart_data[chart_name]:
the_html += chart_data_point
the_html += """
]
}]
});
</script>
"""
axis = "xAxis: {\n"
axis += " labels: {\n"
axis += " useHTML: true,\n"
axis += " style: {\n"
axis += " fontSize: '14px',\n"
axis += " },\n"
axis += " },\n"
axis += " categories: ["
for label in self._chart_label[chart_name]:
axis += "'%s'," % label
axis += "], crosshair: false},"
the_html = the_html.replace("xAxis: { },", axis)
self._chart_xcount += 1
the_html = the_html.replace(
"chartcontainer_num_", "chartcontainer_%s_" % self._chart_xcount
)
return the_html
############
def create_tour(self, name=None, theme=None):
"""Creates a guided tour for any website.
The default theme is the IntroJS Library.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
theme - Sets the default theme for the website tour. Available themes:
"Bootstrap", "DriverJS", "Hopscotch", "IntroJS", "Shepherd".
The "Shepherd" library also contains multiple variation themes:
"light"/"arrows", "dark", "default", "square", "square-dark".
"""
if not name:
name = "default"
if theme:
if theme.lower() == "bootstrap":
self.create_bootstrap_tour(name)
elif theme.lower() == "hopscotch":
self.create_hopscotch_tour(name)
elif theme.lower() == "intro":
self.create_introjs_tour(name)
elif theme.lower() == "introjs":
self.create_introjs_tour(name)
elif theme.lower() == "driver":
self.create_driverjs_tour(name)
elif theme.lower() == "driverjs":
self.create_driverjs_tour(name)
elif theme.lower() == "shepherd":
self.create_shepherd_tour(name, theme="light")
elif theme.lower() == "light":
self.create_shepherd_tour(name, theme="light")
elif theme.lower() == "arrows":
self.create_shepherd_tour(name, theme="light")
elif theme.lower() == "dark":
self.create_shepherd_tour(name, theme="dark")
elif theme.lower() == "square":
self.create_shepherd_tour(name, theme="square")
elif theme.lower() == "square-dark":
self.create_shepherd_tour(name, theme="square-dark")
elif theme.lower() == "default":
self.create_shepherd_tour(name, theme="default")
else:
self.create_introjs_tour(name)
else:
self.create_introjs_tour(name)
def create_shepherd_tour(self, name=None, theme=None):
"""Creates a Shepherd JS website tour.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
theme - Sets the default theme for the tour.
Choose from "light"/"arrows", "dark", "default", "square",
and "square-dark". ("light" is used if None is selected.)
"""
shepherd_theme = "shepherd-theme-arrows"
if theme:
if theme.lower() == "default":
shepherd_theme = "shepherd-theme-default"
elif theme.lower() == "dark":
shepherd_theme = "shepherd-theme-dark"
elif theme.lower() == "light":
shepherd_theme = "shepherd-theme-arrows"
elif theme.lower() == "arrows":
shepherd_theme = "shepherd-theme-arrows"
elif theme.lower() == "square":
shepherd_theme = "shepherd-theme-square"
elif theme.lower() == "square-dark":
shepherd_theme = "shepherd-theme-square-dark"
if not name:
name = "default"
new_tour = (
"""
// Shepherd Tour
var tour = new Shepherd.Tour({
defaults: {
classes: '%s',
scrollTo: true
}
});
var allButtons = {
skip: {
text: "Skip",
action: tour.cancel,
classes: 'shepherd-button-secondary tour-button-left'
},
back: {
text: "Back",
action: tour.back,
classes: 'shepherd-button-secondary'
},
next: {
text: "Next",
action: tour.next,
classes: 'shepherd-button-primary tour-button-right'
},
};
var firstStepButtons = [allButtons.skip, allButtons.next];
var midTourButtons = [allButtons.back, allButtons.next];
"""
% shepherd_theme
)
self._tour_steps[name] = []
self._tour_steps[name].append(new_tour)
def create_bootstrap_tour(self, name=None):
"""Creates a Bootstrap tour for a website.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
"""
if not name:
name = "default"
new_tour = """
// Bootstrap Tour
var tour = new Tour({
container: 'body',
animation: true,
keyboard: true,
orphan: true,
smartPlacement: true,
autoscroll: true,
backdrop: true,
backdropContainer: 'body',
backdropPadding: 3,
});
tour.addSteps([
"""
self._tour_steps[name] = []
self._tour_steps[name].append(new_tour)
def create_driverjs_tour(self, name=None):
"""Creates a DriverJS tour for a website.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
"""
if not name:
name = "default"
new_tour = """
// DriverJS Tour
var tour = new Driver({
opacity: 0.24, // Background opacity (0: no popover / overlay)
padding: 6, // Distance of element from around the edges
allowClose: false, // Whether clicking on overlay should close
overlayClickNext: false, // Move to next step on overlay click
doneBtnText: 'Done', // Text that appears on the Done button
closeBtnText: 'Close', // Text appearing on the Close button
nextBtnText: 'Next', // Text that appears on the Next button
prevBtnText: 'Previous', // Text appearing on Previous button
showButtons: true, // This shows control buttons in the footer
keyboardControl: true, // (escape to close, arrow keys to move)
animate: true, // Animate while changing highlighted element
});
tour.defineSteps([
"""
self._tour_steps[name] = []
self._tour_steps[name].append(new_tour)
def create_hopscotch_tour(self, name=None):
"""Creates a Hopscotch tour for a website.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
"""
if not name:
name = "default"
new_tour = """
// Hopscotch Tour
var tour = {
id: "hopscotch_tour",
steps: [
"""
self._tour_steps[name] = []
self._tour_steps[name].append(new_tour)
def create_introjs_tour(self, name=None):
"""Creates an IntroJS tour for a website.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
"""
if not hasattr(sb_config, "introjs_theme_color"):
sb_config.introjs_theme_color = constants.TourColor.theme_color
if not hasattr(sb_config, "introjs_hover_color"):
sb_config.introjs_hover_color = constants.TourColor.hover_color
if not name:
name = "default"
new_tour = """
// IntroJS Tour
function startIntro(){
var intro = introJs();
intro.setOptions({
steps: [
"""
self._tour_steps[name] = []
self._tour_steps[name].append(new_tour)
def set_introjs_colors(self, theme_color=None, hover_color=None):
"""Use this method to set the theme colors for IntroJS tours.
Args must be hex color values that start with a "#" sign.
If a color isn't specified, the color will reset to the default.
The border color of buttons is set to the hover color.
@Params
theme_color - The color of buttons.
hover_color - The color of buttons after hovering over them.
"""
if not hasattr(sb_config, "introjs_theme_color"):
sb_config.introjs_theme_color = constants.TourColor.theme_color
if not hasattr(sb_config, "introjs_hover_color"):
sb_config.introjs_hover_color = constants.TourColor.hover_color
if theme_color:
match = re.search(r'^#(?:[0-9a-fA-F]{3}){1,2}$', theme_color)
if not match:
raise Exception(
'Expecting a hex value color that starts with "#"!')
sb_config.introjs_theme_color = theme_color
else:
sb_config.introjs_theme_color = constants.TourColor.theme_color
if hover_color:
match = re.search(r'^#(?:[0-9a-fA-F]{3}){1,2}$', hover_color)
if not match:
raise Exception(
'Expecting a hex value color that starts with "#"!')
sb_config.introjs_hover_color = hover_color
else:
sb_config.introjs_hover_color = constants.TourColor.hover_color
def add_tour_step(
self,
message,
selector=None,
name=None,
title=None,
theme=None,
alignment=None,
duration=None,
):
"""Allows the user to add tour steps for a website.
@Params
message - The message to display.
selector - The CSS Selector of the Element to attach to.
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
title - Additional header text that appears above the message.
theme - (Shepherd Tours ONLY) The styling of the tour step.
Choose from "light"/"arrows", "dark", "default", "square",
and "square-dark". ("arrows" is used if None is selected.)
alignment - Choose from "top", "bottom", "left", and "right".
("top" is default, except for Hopscotch and DriverJS).
duration - (Bootstrap Tours ONLY) The amount of time, in seconds,
before automatically advancing to the next tour step.
"""
if not selector:
selector = "html"
if page_utils.is_name_selector(selector):
name = page_utils.get_name_from_selector(selector)
selector = '[name="%s"]' % name
if page_utils.is_xpath_selector(selector):
selector = self.convert_to_css_selector(selector, By.XPATH)
selector = self.__escape_quotes_if_needed(selector)
if not name:
name = "default"
if name not in self._tour_steps:
# By default, will create an IntroJS tour if no tours exist
self.create_tour(name=name, theme="introjs")
if not title:
title = ""
title = self.__escape_quotes_if_needed(title)
if message:
message = self.__escape_quotes_if_needed(message)
else:
message = ""
if not alignment or alignment not in [
"top",
"bottom",
"left",
"right",
]:
t_name = self._tour_steps[name][0]
if "Hopscotch" not in t_name and "DriverJS" not in t_name:
alignment = "top"
else:
alignment = "bottom"
if "Bootstrap" in self._tour_steps[name][0]:
self.__add_bootstrap_tour_step(
message,
selector=selector,
name=name,
title=title,
alignment=alignment,
duration=duration,
)
elif "DriverJS" in self._tour_steps[name][0]:
self.__add_driverjs_tour_step(
message,
selector=selector,
name=name,
title=title,
alignment=alignment,
)
elif "Hopscotch" in self._tour_steps[name][0]:
self.__add_hopscotch_tour_step(
message,
selector=selector,
name=name,
title=title,
alignment=alignment,
)
elif "IntroJS" in self._tour_steps[name][0]:
self.__add_introjs_tour_step(
message,
selector=selector,
name=name,
title=title,
alignment=alignment,
)
else:
self.__add_shepherd_tour_step(
message,
selector=selector,
name=name,
title=title,
theme=theme,
alignment=alignment,
)
def __add_shepherd_tour_step(
self,
message,
selector=None,
name=None,
title=None,
theme=None,
alignment=None,
):
"""Allows the user to add tour steps for a website.
@Params
message - The message to display.
selector - The CSS Selector of the Element to attach to.
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
title - Additional header text that appears above the message.
theme - (Shepherd Tours ONLY) The styling of the tour step.
Choose from "light"/"arrows", "dark", "default", "square",
and "square-dark". ("arrows" is used if None is selected.)
alignment - Choose from "top", "bottom", "left", and "right".
("top" is the default alignment).
"""
if theme == "default":
shepherd_theme = "shepherd-theme-default"
elif theme == "dark":
shepherd_theme = "shepherd-theme-dark"
elif theme == "light":
shepherd_theme = "shepherd-theme-arrows"
elif theme == "arrows":
shepherd_theme = "shepherd-theme-arrows"
elif theme == "square":
shepherd_theme = "shepherd-theme-square"
elif theme == "square-dark":
shepherd_theme = "shepherd-theme-square-dark"
else:
shepherd_base_theme = re.search(
r"[\S\s]+classes: '([\S\s]+)',[\S\s]+",
self._tour_steps[name][0],
).group(1)
shepherd_theme = shepherd_base_theme
shepherd_classes = shepherd_theme
if selector == "html":
shepherd_classes += " shepherd-orphan"
buttons = "firstStepButtons"
if len(self._tour_steps[name]) > 1:
buttons = "midTourButtons"
step = """tour.addStep('%s', {
title: '%s',
classes: '%s',
text: '%s',
attachTo: {element: '%s', on: '%s'},
buttons: %s,
advanceOn: '.docs-link click'
});""" % (
name,
title,
shepherd_classes,
message,
selector,
alignment,
buttons,
)
self._tour_steps[name].append(step)
def __add_bootstrap_tour_step(
self,
message,
selector=None,
name=None,
title=None,
alignment=None,
duration=None,
):
"""Allows the user to add tour steps for a website.
@Params
message - The message to display.
selector - The CSS Selector of the Element to attach to.
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
title - Additional header text that appears above the message.
alignment - Choose from "top", "bottom", "left", and "right".
("top" is the default alignment).
duration - (Bootstrap Tours ONLY) The amount of time, in seconds,
before automatically advancing to the next tour step.
"""
if selector != "html":
selector = self.__make_css_match_first_element_only(selector)
element_row = "element: '%s'," % selector
else:
element_row = ""
if not duration:
duration = "0"
else:
duration = str(float(duration) * 1000.0)
bd = "backdrop: true,"
if selector == "html":
bd = "backdrop: false,"
step = """{
%s
title: '%s',
content: '%s',
orphan: true,
autoscroll: true,
%s
placement: 'auto %s',
smartPlacement: true,
duration: %s,
},""" % (
element_row,
title,
message,
bd,
alignment,
duration,
)
self._tour_steps[name].append(step)
def __add_driverjs_tour_step(
self, message, selector=None, name=None, title=None, alignment=None
):
"""Allows the user to add tour steps for a website.
@Params
message - The message to display.
selector - The CSS Selector of the Element to attach to.
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
title - Additional header text that appears above the message.
alignment - Choose from "top", "bottom", "left", and "right".
("top" is the default alignment).
"""
message = (
'<font size="3" color="#33477B"><b>' + message + "</b></font>"
)
title_row = ""
if not title:
title_row = "title: '%s'," % message
message = ""
else:
title_row = "title: '%s'," % title
align_row = "position: '%s'," % alignment
ani_row = "animate: true,"
if not selector or selector == "html" or selector == "body":
selector = "body"
ani_row = "animate: false,"
align_row = "position: '%s'," % "mid-center"
element_row = "element: '%s'," % selector
desc_row = "description: '%s'," % message
step = """{
%s
%s
popover: {
className: 'popover-class',
%s
%s
%s
}
},""" % (
element_row,
ani_row,
title_row,
desc_row,
align_row,
)
self._tour_steps[name].append(step)
def __add_hopscotch_tour_step(
self, message, selector=None, name=None, title=None, alignment=None
):
"""Allows the user to add tour steps for a website.
@Params
message - The message to display.
selector - The CSS Selector of the Element to attach to.
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
title - Additional header text that appears above the message.
alignment - Choose from "top", "bottom", "left", and "right".
("bottom" is the default alignment).
"""
arrow_offset_row = None
if not selector or selector == "html":
selector = "head"
alignment = "bottom"
arrow_offset_row = "arrowOffset: '200',"
else:
arrow_offset_row = ""
step = """{
target: '%s',
title: '%s',
content: '%s',
%s
showPrevButton: 'true',
scrollDuration: '550',
placement: '%s'},
""" % (
selector,
title,
message,
arrow_offset_row,
alignment,
)
self._tour_steps[name].append(step)
def __add_introjs_tour_step(
self, message, selector=None, name=None, title=None, alignment=None
):
"""Allows the user to add tour steps for a website.
@Params
message - The message to display.
selector - The CSS Selector of the Element to attach to.
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
title - Additional header text that appears above the message.
alignment - Choose from "top", "bottom", "left", and "right".
("top" is the default alignment).
"""
if selector != "html":
element_row = "element: '%s'," % selector
else:
element_row = ""
if title:
message = "<center><b>" + title + "</b></center><hr>" + message
message = '<font size="3" color="#33477B">' + message + "</font>"
step = """{%s
intro: '%s',
position: '%s'},""" % (
element_row,
message,
alignment,
)
self._tour_steps[name].append(step)
def play_tour(self, name=None, interval=0):
"""Plays a tour on the current website.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
interval - The delay time between autoplaying tour steps. (Seconds)
If set to 0 (default), the tour is fully manual control.
"""
from seleniumbase.core import tour_helper
if self.headless or self.xvfb:
return # Tours should not run in headless mode.
self.wait_for_ready_state_complete()
if not interval:
interval = 0
if interval == 0 and self.interval:
interval = float(self.interval)
if not name:
name = "default"
if name not in self._tour_steps:
raise Exception("Tour {%s} does not exist!" % name)
if "Bootstrap" in self._tour_steps[name][0]:
tour_helper.play_bootstrap_tour(
self.driver,
self._tour_steps,
self.browser,
self.message_duration,
name=name,
interval=interval,
)
elif "DriverJS" in self._tour_steps[name][0]:
tour_helper.play_driverjs_tour(
self.driver,
self._tour_steps,
self.browser,
self.message_duration,
name=name,
interval=interval,
)
elif "Hopscotch" in self._tour_steps[name][0]:
tour_helper.play_hopscotch_tour(
self.driver,
self._tour_steps,
self.browser,
self.message_duration,
name=name,
interval=interval,
)
elif "IntroJS" in self._tour_steps[name][0]:
tour_helper.play_introjs_tour(
self.driver,
self._tour_steps,
self.browser,
self.message_duration,
name=name,
interval=interval,
)
else:
# "Shepherd"
tour_helper.play_shepherd_tour(
self.driver,
self._tour_steps,
self.message_duration,
name=name,
interval=interval,
)
def export_tour(self, name=None, filename="my_tour.js", url=None):
"""Exports a tour as a JS file.
You can call self.export_tour() anywhere where you would
normally use self.play_tour() to play a website tour.
It will include necessary resources as well, such as jQuery.
You'll be able to copy the tour directly into the Console of
any web browser to play the tour outside of SeleniumBase runs.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
filename - The name of the JavaScript file that you wish to
save the tour to.
url - The URL where the tour starts. If not specified, the URL
of the current page will be used.
"""
from seleniumbase.core import tour_helper
if not url:
url = self.get_current_url()
tour_helper.export_tour(
self._tour_steps, name=name, filename=filename, url=url
)
############
def activate_jquery_confirm(self):
""" See https://craftpip.github.io/jquery-confirm/ for usage. """
self.__check_scope()
self.__check_browser()
js_utils.activate_jquery_confirm(self.driver)
self.wait_for_ready_state_complete()
def set_jqc_theme(self, theme, color=None, width=None):
""" Sets the default jquery-confirm theme and width (optional).
Available themes: "bootstrap", "modern", "material", "supervan",
"light", "dark", and "seamless".
Available colors: (This sets the BORDER color, NOT the button color.)
"blue", "default", "green", "red", "purple", "orange", "dark".
Width can be set using percent or pixels. Eg: "36.0%", "450px".
"""
if not self.__changed_jqc_theme:
self.__jqc_default_theme = constants.JqueryConfirm.DEFAULT_THEME
self.__jqc_default_color = constants.JqueryConfirm.DEFAULT_COLOR
self.__jqc_default_width = constants.JqueryConfirm.DEFAULT_WIDTH
valid_themes = [
"bootstrap",
"modern",
"material",
"supervan",
"light",
"dark",
"seamless",
]
if theme.lower() not in valid_themes:
raise Exception(
"%s is not a valid jquery-confirm theme! "
"Select from %s" % (theme.lower(), valid_themes)
)
constants.JqueryConfirm.DEFAULT_THEME = theme.lower()
if color:
valid_colors = [
"blue",
"default",
"green",
"red",
"purple",
"orange",
"dark",
]
if color.lower() not in valid_colors:
raise Exception(
"%s is not a valid jquery-confirm border color! "
"Select from %s" % (color.lower(), valid_colors)
)
constants.JqueryConfirm.DEFAULT_COLOR = color.lower()
if width:
if type(width) is int or type(width) is float:
# Convert to a string if a number is given
width = str(width)
if width.isnumeric():
if int(width) <= 0:
raise Exception("Width must be set to a positive number!")
elif int(width) <= 100:
width = str(width) + "%"
else:
width = str(width) + "px" # Use pixels if width is > 100
if not width.endswith("%") and not width.endswith("px"):
raise Exception(
"jqc width must end with %% for percent or px for pixels!"
)
value = None
if width.endswith("%"):
value = width[:-1]
if width.endswith("px"):
value = width[:-2]
try:
value = float(value)
except Exception:
raise Exception("%s is not a numeric value!" % value)
if value <= 0:
raise Exception("%s is not a positive number!" % value)
constants.JqueryConfirm.DEFAULT_WIDTH = width
def reset_jqc_theme(self):
""" Resets the jqc theme settings to factory defaults. """
if self.__changed_jqc_theme:
constants.JqueryConfirm.DEFAULT_THEME = self.__jqc_default_theme
constants.JqueryConfirm.DEFAULT_COLOR = self.__jqc_default_color
constants.JqueryConfirm.DEFAULT_WIDTH = self.__jqc_default_width
self.__changed_jqc_theme = False
def get_jqc_button_input(self, message, buttons, options=None):
"""
Pop up a jquery-confirm box and return the text of the button clicked.
If running in headless mode, the last button text is returned.
@Params
message: The message to display in the jquery-confirm dialog.
buttons: A list of tuples for text and color.
Example: [("Yes!", "green"), ("No!", "red")]
Available colors: blue, green, red, orange, purple, default, dark.
A simple text string also works: "My Button". (Uses default color.)
options: A list of tuples for options to set.
Example: [("theme", "bootstrap"), ("width", "450px")]
Available theme options: bootstrap, modern, material, supervan,
light, dark, and seamless.
Available colors: (For the BORDER color, NOT the button color.)
"blue", "default", "green", "red", "purple", "orange", "dark".
Example option for changing the border color: ("color", "default")
Width can be set using percent or pixels. Eg: "36.0%", "450px".
"""
from seleniumbase.core import jqc_helper
if message and type(message) is not str:
raise Exception('Expecting a string for arg: "message"!')
if not type(buttons) is list and not type(buttons) is tuple:
raise Exception('Expecting a list or tuple for arg: "button"!')
if len(buttons) < 1:
raise Exception('List "buttons" requires at least one button!')
new_buttons = []
for button in buttons:
if (
(type(button) is list or type(button) is tuple) and (
len(button) == 1)
):
new_buttons.append(button[0])
elif (
(type(button) is list or type(button) is tuple) and (
len(button) > 1)
):
new_buttons.append((button[0], str(button[1]).lower()))
else:
new_buttons.append((str(button), ""))
buttons = new_buttons
if options:
for option in options:
if not type(option) is list and not type(option) is tuple:
raise Exception('"options" should be a list of tuples!')
if self.headless or self.xvfb:
return buttons[-1][0]
jqc_helper.jquery_confirm_button_dialog(
self.driver, message, buttons, options
)
self.sleep(0.02)
jf = "document.querySelector('.jconfirm-box').focus();"
try:
self.execute_script(jf)
except Exception:
pass
waiting_for_response = True
while waiting_for_response:
self.sleep(0.05)
jqc_open = self.execute_script(
"return jconfirm.instances.length"
)
if str(jqc_open) == "0":
break
self.sleep(0.1)
status = None
try:
status = self.execute_script("return $jqc_status")
except Exception:
status = self.execute_script(
"return jconfirm.lastButtonText"
)
return status
def get_jqc_text_input(self, message, button=None, options=None):
"""
Pop up a jquery-confirm box and return the text submitted by the input.
If running in headless mode, the text returned is "" by default.
@Params
message: The message to display in the jquery-confirm dialog.
button: A 2-item list or tuple for text and color. Or just the text.
Example: ["Submit", "blue"] -> (default button if not specified)
Available colors: blue, green, red, orange, purple, default, dark.
A simple text string also works: "My Button". (Uses default color.)
options: A list of tuples for options to set.
Example: [("theme", "bootstrap"), ("width", "450px")]
Available theme options: bootstrap, modern, material, supervan,
light, dark, and seamless.
Available colors: (For the BORDER color, NOT the button color.)
"blue", "default", "green", "red", "purple", "orange", "dark".
Example option for changing the border color: ("color", "default")
Width can be set using percent or pixels. Eg: "36.0%", "450px".
"""
from seleniumbase.core import jqc_helper
if message and type(message) is not str:
raise Exception('Expecting a string for arg: "message"!')
if button:
if (
(type(button) is list or type(button) is tuple) and (
len(button) == 1)
):
button = (str(button[0]), "")
elif (
(type(button) is list or type(button) is tuple) and (
len(button) > 1)
):
valid_colors = [
"blue",
"default",
"green",
"red",
"purple",
"orange",
"dark",
]
detected_color = str(button[1]).lower()
if str(button[1]).lower() not in valid_colors:
raise Exception(
"%s is an invalid jquery-confirm button color!\n"
"Select from %s" % (detected_color, valid_colors)
)
button = (str(button[0]), str(button[1]).lower())
else:
button = (str(button), "")
else:
button = ("Submit", "blue")
if options:
for option in options:
if not type(option) is list and not type(option) is tuple:
raise Exception('"options" should be a list of tuples!')
if self.headless or self.xvfb:
return ""
jqc_helper.jquery_confirm_text_dialog(
self.driver, message, button, options
)
self.sleep(0.02)
jf = "document.querySelector('.jconfirm-box input.jqc_input').focus();"
try:
self.execute_script(jf)
except Exception:
pass
waiting_for_response = True
while waiting_for_response:
self.sleep(0.05)
jqc_open = self.execute_script(
"return jconfirm.instances.length"
)
if str(jqc_open) == "0":
break
self.sleep(0.1)
status = None
try:
status = self.execute_script("return $jqc_input")
except Exception:
status = self.execute_script(
"return jconfirm.lastInputText"
)
return status
def get_jqc_form_inputs(self, message, buttons, options=None):
"""
Pop up a jquery-confirm box and return the input/button texts as tuple.
If running in headless mode, returns the ("", buttons[-1][0]) tuple.
@Params
message: The message to display in the jquery-confirm dialog.
buttons: A list of tuples for text and color.
Example: [("Yes!", "green"), ("No!", "red")]
Available colors: blue, green, red, orange, purple, default, dark.
A simple text string also works: "My Button". (Uses default color.)
options: A list of tuples for options to set.
Example: [("theme", "bootstrap"), ("width", "450px")]
Available theme options: bootstrap, modern, material, supervan,
light, dark, and seamless.
Available colors: (For the BORDER color, NOT the button color.)
"blue", "default", "green", "red", "purple", "orange", "dark".
Example option for changing the border color: ("color", "default")
Width can be set using percent or pixels. Eg: "36.0%", "450px".
"""
from seleniumbase.core import jqc_helper
if message and type(message) is not str:
raise Exception('Expecting a string for arg: "message"!')
if not type(buttons) is list and not type(buttons) is tuple:
raise Exception('Expecting a list or tuple for arg: "button"!')
if len(buttons) < 1:
raise Exception('List "buttons" requires at least one button!')
new_buttons = []
for button in buttons:
if (
(type(button) is list or type(button) is tuple) and (
len(button) == 1)
):
new_buttons.append(button[0])
elif (
(type(button) is list or type(button) is tuple) and (
len(button) > 1)
):
new_buttons.append((button[0], str(button[1]).lower()))
else:
new_buttons.append((str(button), ""))
buttons = new_buttons
if options:
for option in options:
if not type(option) is list and not type(option) is tuple:
raise Exception('"options" should be a list of tuples!')
if self.headless or self.xvfb:
return ("", buttons[-1][0])
jqc_helper.jquery_confirm_full_dialog(
self.driver, message, buttons, options
)
self.sleep(0.02)
jf = "document.querySelector('.jconfirm-box input.jqc_input').focus();"
try:
self.execute_script(jf)
except Exception:
pass
waiting_for_response = True
while waiting_for_response:
self.sleep(0.05)
jqc_open = self.execute_script(
"return jconfirm.instances.length"
)
if str(jqc_open) == "0":
break
self.sleep(0.1)
text_status = None
button_status = None
try:
text_status = self.execute_script("return $jqc_input")
button_status = self.execute_script("return $jqc_status")
except Exception:
text_status = self.execute_script(
"return jconfirm.lastInputText"
)
button_status = self.execute_script(
"return jconfirm.lastButtonText"
)
return (text_status, button_status)
############
def activate_messenger(self):
self.__check_scope()
self.__check_browser()
js_utils.activate_messenger(self.driver)
self.wait_for_ready_state_complete()
def set_messenger_theme(
self, theme="default", location="default", max_messages="default"
):
"""Sets a theme for posting messages.
Themes: ["flat", "future", "block", "air", "ice"]
Locations: ["top_left", "top_center", "top_right",
"bottom_left", "bottom_center", "bottom_right"]
max_messages is the limit of concurrent messages to display.
"""
self.__check_scope()
self.__check_browser()
if not theme:
theme = "default" # "flat"
if not location:
location = "default" # "bottom_right"
if not max_messages:
max_messages = "default" # "8"
else:
max_messages = str(max_messages) # Value must be in string format
js_utils.set_messenger_theme(
self.driver,
theme=theme,
location=location,
max_messages=max_messages,
)
def post_message(self, message, duration=None, pause=True, style="info"):
"""Post a message on the screen with Messenger.
Arguments:
message: The message to display.
duration: The time until the message vanishes. (Default: 2.55s)
pause: If True, the program waits until the message completes.
style: "info", "success", or "error".
You can also post messages by using =>
self.execute_script('Messenger().post("My Message")')
"""
self.__check_scope()
self.__check_browser()
if style not in ["info", "success", "error"]:
style = "info"
if not duration:
if not self.message_duration:
duration = settings.DEFAULT_MESSAGE_DURATION
else:
duration = self.message_duration
if (self.headless or self.xvfb) and float(duration) > 0.75:
duration = 0.75
try:
js_utils.post_message(self.driver, message, duration, style=style)
except Exception:
print(" * %s message: %s" % (style.upper(), message))
if pause:
duration = float(duration) + 0.15
time.sleep(float(duration))
def post_message_and_highlight(
self, message, selector, by=By.CSS_SELECTOR
):
"""Post a message on the screen and highlight an element.
Arguments:
message: The message to display.
selector: The selector of the Element to highlight.
by: The type of selector to search by. (Default: CSS Selector)
"""
self.__check_scope()
self.__highlight_with_assert_success(message, selector, by=by)
def post_success_message(self, message, duration=None, pause=True):
"""Post a success message on the screen with Messenger.
Arguments:
message: The success message to display.
duration: The time until the message vanishes. (Default: 2.55s)
pause: If True, the program waits until the message completes.
"""
self.__check_scope()
self.__check_browser()
if not duration:
if not self.message_duration:
duration = settings.DEFAULT_MESSAGE_DURATION
else:
duration = self.message_duration
if (self.headless or self.xvfb) and float(duration) > 0.75:
duration = 0.75
try:
js_utils.post_message(
self.driver, message, duration, style="success"
)
except Exception:
print(" * SUCCESS message: %s" % message)
if pause:
duration = float(duration) + 0.15
time.sleep(float(duration))
def post_error_message(self, message, duration=None, pause=True):
"""Post an error message on the screen with Messenger.
Arguments:
message: The error message to display.
duration: The time until the message vanishes. (Default: 2.55s)
pause: If True, the program waits until the message completes.
"""
self.__check_scope()
self.__check_browser()
if not duration:
if not self.message_duration:
duration = settings.DEFAULT_MESSAGE_DURATION
else:
duration = self.message_duration
if (self.headless or self.xvfb) and float(duration) > 0.75:
duration = 0.75
try:
js_utils.post_message(
self.driver, message, duration, style="error"
)
except Exception:
print(" * ERROR message: %s" % message)
if pause:
duration = float(duration) + 0.15
time.sleep(float(duration))
############
def generate_referral(self, start_page, destination_page, selector=None):
"""This method opens the start_page, creates a referral link there,
and clicks on that link, which goes to the destination_page.
If a selector is given, clicks that on the destination_page,
which can prevent an artificial rise in website bounce-rate.
(This generates real traffic for testing analytics software.)"""
self.__check_scope()
if not page_utils.is_valid_url(destination_page):
raise Exception(
"Exception: destination_page {%s} is not a valid URL!"
% destination_page
)
if start_page:
if not page_utils.is_valid_url(start_page):
raise Exception(
"Exception: start_page {%s} is not a valid URL! "
"(Use an empty string or None to start from current page.)"
% start_page
)
self.open(start_page)
time.sleep(0.08)
self.wait_for_ready_state_complete()
referral_link = (
"""<body>"""
"""<a class='analytics referral test' href='%s' """
"""style='font-family: Arial,sans-serif; """
"""font-size: 30px; color: #18a2cd'>"""
"""Magic Link Button</a></body>""" % destination_page
)
self.execute_script(
'''document.body.outerHTML = \"%s\"''' % referral_link
)
# Now click the generated button
self.click("a.analytics.referral.test", timeout=2)
time.sleep(0.15)
if selector:
self.click(selector)
time.sleep(0.15)
def generate_traffic(
self, start_page, destination_page, loops=1, selector=None
):
"""Similar to generate_referral(), but can do multiple loops.
If a selector is given, clicks that on the destination_page,
which can prevent an artificial rise in website bounce-rate."""
self.__check_scope()
for loop in range(loops):
self.generate_referral(
start_page, destination_page, selector=selector
)
time.sleep(0.05)
def generate_referral_chain(self, pages):
"""Use this method to chain the action of creating button links on
one website page that will take you to the next page.
(When you want to create a referral to a website for traffic
generation without increasing the bounce rate, you'll want to visit
at least one additional page on that site with a button click.)"""
self.__check_scope()
if not type(pages) is tuple and not type(pages) is list:
raise Exception(
"Exception: Expecting a list of website pages for chaining!"
)
if len(pages) < 2:
raise Exception(
"Exception: At least two website pages required for chaining!"
)
for page in pages:
# Find out if any of the web pages are invalid before continuing
if not page_utils.is_valid_url(page):
raise Exception(
"Exception: Website page {%s} is not a valid URL!" % page
)
for page in pages:
self.generate_referral(None, page)
def generate_traffic_chain(self, pages, loops=1):
""" Similar to generate_referral_chain(), but for multiple loops. """
self.__check_scope()
for loop in range(loops):
self.generate_referral_chain(pages)
time.sleep(0.05)
############
def wait_for_element_present(
self, selector, by=By.CSS_SELECTOR, timeout=None
):
"""Waits for an element to appear in the HTML of a page.
The element does not need be visible (it may be hidden)."""
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
if self.__is_shadow_selector(selector):
return self.__wait_for_shadow_element_present(selector)
return page_actions.wait_for_element_present(
self.driver, selector, by, timeout
)
def wait_for_element(self, selector, by=By.CSS_SELECTOR, timeout=None):
"""Waits for an element to appear in the HTML of a page.
The element must be visible (it cannot be hidden)."""
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
if self.__is_shadow_selector(selector):
return self.__wait_for_shadow_element_visible(selector)
return page_actions.wait_for_element_visible(
self.driver, selector, by, timeout
)
def get_element(self, selector, by=By.CSS_SELECTOR, timeout=None):
"""Same as wait_for_element_present() - returns the element.
The element does not need be visible (it may be hidden)."""
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
return self.wait_for_element_present(selector, by=by, timeout=timeout)
def assert_element_present(
self, selector, by=By.CSS_SELECTOR, timeout=None
):
"""Similar to wait_for_element_present(), but returns nothing.
Waits for an element to appear in the HTML of a page.
The element does not need be visible (it may be hidden).
Returns True if successful. Default timeout = SMALL_TIMEOUT."""
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
if type(selector) is list:
self.assert_elements_present(selector, by=by, timeout=timeout)
return True
if self.__is_shadow_selector(selector):
self.__assert_shadow_element_present(selector)
return True
self.wait_for_element_present(selector, by=by, timeout=timeout)
if self.recorder_mode:
url = self.get_current_url()
if url and len(url) > 0:
if ("http:") in url or ("https:") in url or ("file:") in url:
if self.get_session_storage_item("pause_recorder") == "no":
time_stamp = self.execute_script("return Date.now();")
origin = self.get_origin()
action = ["as_ep", selector, origin, time_stamp]
self.__extra_actions.append(action)
return True
def assert_elements_present(self, *args, **kwargs):
"""Similar to self.assert_element_present(),
but can assert that multiple elements are present in the HTML.
The input is a list of elements.
Optional kwargs include "by" and "timeout" (used by all selectors).
Raises an exception if any of the elements are not visible.
Examples:
self.assert_elements_present("head", "style", "script", "body")
OR
self.assert_elements_present(["head", "body", "h1", "h2"])
"""
self.__check_scope()
selectors = []
timeout = None
by = By.CSS_SELECTOR
for kwarg in kwargs:
if kwarg == "timeout":
timeout = kwargs["timeout"]
elif kwarg == "by":
by = kwargs["by"]
elif kwarg == "selector":
selector = kwargs["selector"]
if type(selector) is str:
selectors.append(selector)
elif type(selector) is list:
selectors_list = selector
for selector in selectors_list:
if type(selector) is str:
selectors.append(selector)
else:
raise Exception('Unknown kwarg: "%s"!' % kwarg)
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
for arg in args:
if type(arg) is list:
for selector in arg:
if type(selector) is str:
selectors.append(selector)
elif type(arg) is str:
selectors.append(arg)
for selector in selectors:
if self.__is_shadow_selector(selector):
self.__assert_shadow_element_visible(selector)
continue
self.wait_for_element_present(selector, by=by, timeout=timeout)
continue
return True
def find_element(self, selector, by=By.CSS_SELECTOR, timeout=None):
""" Same as wait_for_element_visible() - returns the element """
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
return self.wait_for_element_visible(selector, by=by, timeout=timeout)
def assert_element(self, selector, by=By.CSS_SELECTOR, timeout=None):
"""Similar to wait_for_element_visible(), but returns nothing.
As above, will raise an exception if nothing can be found.
Returns True if successful. Default timeout = SMALL_TIMEOUT."""
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
if type(selector) is list:
self.assert_elements(selector, by=by, timeout=timeout)
return True
if self.__is_shadow_selector(selector):
self.__assert_shadow_element_visible(selector)
return True
self.wait_for_element_visible(selector, by=by, timeout=timeout)
if self.demo_mode:
selector, by = self.__recalculate_selector(
selector, by, xp_ok=False
)
a_t = "ASSERT"
if self._language != "English":
from seleniumbase.fixtures.words import SD
a_t = SD.translate_assert(self._language)
messenger_post = "%s %s: %s" % (a_t, by.upper(), selector)
self.__highlight_with_assert_success(messenger_post, selector, by)
if self.recorder_mode:
url = self.get_current_url()
if url and len(url) > 0:
if ("http:") in url or ("https:") in url or ("file:") in url:
if self.get_session_storage_item("pause_recorder") == "no":
time_stamp = self.execute_script("return Date.now();")
origin = self.get_origin()
action = ["as_el", selector, origin, time_stamp]
self.__extra_actions.append(action)
return True
def assert_element_visible(
self, selector, by=By.CSS_SELECTOR, timeout=None
):
"""Same as self.assert_element()
As above, will raise an exception if nothing can be found."""
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
self.assert_element(selector, by=by, timeout=timeout)
return True
def assert_elements(self, *args, **kwargs):
"""Similar to self.assert_element(), but can assert multiple elements.
The input is a list of elements.
Optional kwargs include "by" and "timeout" (used by all selectors).
Raises an exception if any of the elements are not visible.
Examples:
self.assert_elements("h1", "h2", "h3")
OR
self.assert_elements(["h1", "h2", "h3"])"""
self.__check_scope()
selectors = []
timeout = None
by = By.CSS_SELECTOR
for kwarg in kwargs:
if kwarg == "timeout":
timeout = kwargs["timeout"]
elif kwarg == "by":
by = kwargs["by"]
elif kwarg == "selector":
selector = kwargs["selector"]
if type(selector) is str:
selectors.append(selector)
elif type(selector) is list:
selectors_list = selector
for selector in selectors_list:
if type(selector) is str:
selectors.append(selector)
else:
raise Exception('Unknown kwarg: "%s"!' % kwarg)
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
for arg in args:
if type(arg) is list:
for selector in arg:
if type(selector) is str:
selectors.append(selector)
elif type(arg) is str:
selectors.append(arg)
for selector in selectors:
if self.__is_shadow_selector(selector):
self.__assert_shadow_element_visible(selector)
continue
self.wait_for_element_visible(selector, by=by, timeout=timeout)
if self.demo_mode:
selector, by = self.__recalculate_selector(selector, by)
a_t = "ASSERT"
if self._language != "English":
from seleniumbase.fixtures.words import SD
a_t = SD.translate_assert(self._language)
messenger_post = "%s %s: %s" % (a_t, by.upper(), selector)
self.__highlight_with_assert_success(
messenger_post, selector, by
)
continue
return True
def assert_elements_visible(self, *args, **kwargs):
"""Same as self.assert_elements()
Raises an exception if any element cannot be found."""
return self.assert_elements(*args, **kwargs)
############
def wait_for_text_visible(
self, text, selector="html", by=By.CSS_SELECTOR, timeout=None
):
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
if self.__is_shadow_selector(selector):
return self.__wait_for_shadow_text_visible(text, selector)
return page_actions.wait_for_text_visible(
self.driver, text, selector, by, timeout
)
def wait_for_exact_text_visible(
self, text, selector="html", by=By.CSS_SELECTOR, timeout=None
):
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
if self.__is_shadow_selector(selector):
return self.__wait_for_exact_shadow_text_visible(text, selector)
return page_actions.wait_for_exact_text_visible(
self.driver, text, selector, by, timeout
)
def wait_for_text(
self, text, selector="html", by=By.CSS_SELECTOR, timeout=None
):
""" The shorter version of wait_for_text_visible() """
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
return self.wait_for_text_visible(
text, selector, by=by, timeout=timeout
)
def find_text(
self, text, selector="html", by=By.CSS_SELECTOR, timeout=None
):
""" Same as wait_for_text_visible() - returns the element """
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
return self.wait_for_text_visible(
text, selector, by=by, timeout=timeout
)
def assert_text_visible(
self, text, selector="html", by=By.CSS_SELECTOR, timeout=None
):
""" Same as assert_text() """
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
return self.assert_text(text, selector, by=by, timeout=timeout)
def assert_text(
self, text, selector="html", by=By.CSS_SELECTOR, timeout=None
):
"""Similar to wait_for_text_visible()
Raises an exception if the element or the text is not found.
The text only needs to be a subset within the complete text.
Returns True if successful. Default timeout = SMALL_TIMEOUT."""
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
if self.__is_shadow_selector(selector):
self.__assert_shadow_text_visible(text, selector)
return True
self.wait_for_text_visible(text, selector, by=by, timeout=timeout)
if self.demo_mode:
a_t = "ASSERT TEXT"
i_n = "in"
if self._language != "English":
from seleniumbase.fixtures.words import SD
a_t = SD.translate_assert_text(self._language)
i_n = SD.translate_in(self._language)
messenger_post = "%s: {%s} %s %s: %s" % (
a_t,
text,
i_n,
by.upper(),
selector,
)
self.__highlight_with_assert_success(messenger_post, selector, by)
if self.recorder_mode:
url = self.get_current_url()
if url and len(url) > 0:
if ("http:") in url or ("https:") in url or ("file:") in url:
if self.get_session_storage_item("pause_recorder") == "no":
time_stamp = self.execute_script("return Date.now();")
origin = self.get_origin()
text_selector = [text, selector]
action = ["as_te", text_selector, origin, time_stamp]
self.__extra_actions.append(action)
return True
def assert_exact_text(
self, text, selector="html", by=By.CSS_SELECTOR, timeout=None
):
"""Similar to assert_text(), but the text must be exact,
rather than exist as a subset of the full text.
(Extra whitespace at the beginning or the end doesn't count.)
Raises an exception if the element or the text is not found.
Returns True if successful. Default timeout = SMALL_TIMEOUT."""
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
if self.__is_shadow_selector(selector):
self.__assert_exact_shadow_text_visible(text, selector)
return True
self.wait_for_exact_text_visible(
text, selector, by=by, timeout=timeout
)
if self.demo_mode:
a_t = "ASSERT EXACT TEXT"
i_n = "in"
if self._language != "English":
from seleniumbase.fixtures.words import SD
a_t = SD.translate_assert_exact_text(self._language)
i_n = SD.translate_in(self._language)
messenger_post = "%s: {%s} %s %s: %s" % (
a_t,
text,
i_n,
by.upper(),
selector,
)
self.__highlight_with_assert_success(messenger_post, selector, by)
if self.recorder_mode:
url = self.get_current_url()
if url and len(url) > 0:
if ("http:") in url or ("https:") in url or ("file:") in url:
if self.get_session_storage_item("pause_recorder") == "no":
time_stamp = self.execute_script("return Date.now();")
origin = self.get_origin()
text_selector = [text, selector]
action = ["as_et", text_selector, origin, time_stamp]
self.__extra_actions.append(action)
return True
############
def wait_for_link_text_present(self, link_text, timeout=None):
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
start_ms = time.time() * 1000.0
stop_ms = start_ms + (timeout * 1000.0)
for x in range(int(timeout * 5)):
shared_utils.check_if_time_limit_exceeded()
try:
if not self.is_link_text_present(link_text):
raise Exception(
"Link text {%s} was not found!" % link_text
)
return
except Exception:
now_ms = time.time() * 1000.0
if now_ms >= stop_ms:
break
time.sleep(0.2)
message = "Link text {%s} was not present after %s seconds!" % (
link_text,
timeout,
)
page_actions.timeout_exception("NoSuchElementException", message)
def wait_for_partial_link_text_present(self, link_text, timeout=None):
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
start_ms = time.time() * 1000.0
stop_ms = start_ms + (timeout * 1000.0)
for x in range(int(timeout * 5)):
shared_utils.check_if_time_limit_exceeded()
try:
if not self.is_partial_link_text_present(link_text):
raise Exception(
"Partial Link text {%s} was not found!" % link_text
)
return
except Exception:
now_ms = time.time() * 1000.0
if now_ms >= stop_ms:
break
time.sleep(0.2)
message = (
"Partial Link text {%s} was not present after %s seconds!"
"" % (link_text, timeout)
)
page_actions.timeout_exception("NoSuchElementException", message)
def wait_for_link_text_visible(self, link_text, timeout=None):
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
return self.wait_for_element_visible(
link_text, by=By.LINK_TEXT, timeout=timeout
)
def wait_for_link_text(self, link_text, timeout=None):
""" The shorter version of wait_for_link_text_visible() """
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
return self.wait_for_link_text_visible(link_text, timeout=timeout)
def find_link_text(self, link_text, timeout=None):
""" Same as wait_for_link_text_visible() - returns the element """
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
return self.wait_for_link_text_visible(link_text, timeout=timeout)
def assert_link_text(self, link_text, timeout=None):
"""Similar to wait_for_link_text_visible(), but returns nothing.
As above, will raise an exception if nothing can be found.
Returns True if successful. Default timeout = SMALL_TIMEOUT."""
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
self.wait_for_link_text_visible(link_text, timeout=timeout)
if self.demo_mode:
a_t = "ASSERT LINK TEXT"
if self._language != "English":
from seleniumbase.fixtures.words import SD
a_t = SD.translate_assert_link_text(self._language)
messenger_post = "%s: {%s}" % (a_t, link_text)
self.__highlight_with_assert_success(
messenger_post, link_text, by=By.LINK_TEXT
)
if self.recorder_mode:
url = self.get_current_url()
if url and len(url) > 0:
if ("http:") in url or ("https:") in url or ("file:") in url:
if self.get_session_storage_item("pause_recorder") == "no":
time_stamp = self.execute_script("return Date.now();")
origin = self.get_origin()
action = ["as_lt", link_text, origin, time_stamp]
self.__extra_actions.append(action)
return True
def wait_for_partial_link_text(self, partial_link_text, timeout=None):
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
return self.wait_for_element_visible(
partial_link_text, by=By.PARTIAL_LINK_TEXT, timeout=timeout
)
def find_partial_link_text(self, partial_link_text, timeout=None):
""" Same as wait_for_partial_link_text() - returns the element """
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
return self.wait_for_partial_link_text(
partial_link_text, timeout=timeout
)
def assert_partial_link_text(self, partial_link_text, timeout=None):
"""Similar to wait_for_partial_link_text(), but returns nothing.
As above, will raise an exception if nothing can be found.
Returns True if successful. Default timeout = SMALL_TIMEOUT."""
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
self.wait_for_partial_link_text(partial_link_text, timeout=timeout)
if self.demo_mode:
a_t = "ASSERT PARTIAL LINK TEXT"
if self._language != "English":
from seleniumbase.fixtures.words import SD
a_t = SD.translate_assert_link_text(self._language)
messenger_post = "%s: {%s}" % (a_t, partial_link_text)
self.__highlight_with_assert_success(
messenger_post, partial_link_text, by=By.PARTIAL_LINK_TEXT
)
return True
############
def wait_for_element_absent(
self, selector, by=By.CSS_SELECTOR, timeout=None
):
"""Waits for an element to no longer appear in the HTML of a page.
A hidden element counts as a present element, which fails this assert.
If waiting for elements to be hidden instead of nonexistent,
use wait_for_element_not_visible() instead.
"""
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
return page_actions.wait_for_element_absent(
self.driver, selector, by, timeout
)
def assert_element_absent(
self, selector, by=By.CSS_SELECTOR, timeout=None
):
"""Similar to wait_for_element_absent()
As above, will raise an exception if the element stays present.
A hidden element counts as a present element, which fails this assert.
If you want to assert that elements are hidden instead of nonexistent,
use assert_element_not_visible() instead.
(Note that hidden elements are still present in the HTML of the page.)
Returns True if successful. Default timeout = SMALL_TIMEOUT."""
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
self.wait_for_element_absent(selector, by=by, timeout=timeout)
return True
############
def wait_for_element_not_visible(
self, selector, by=By.CSS_SELECTOR, timeout=None
):
"""Waits for an element to no longer be visible on a page.
The element can be non-existent in the HTML or hidden on the page
to qualify as not visible."""
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
return page_actions.wait_for_element_not_visible(
self.driver, selector, by, timeout
)
def assert_element_not_visible(
self, selector, by=By.CSS_SELECTOR, timeout=None
):
"""Similar to wait_for_element_not_visible()
As above, will raise an exception if the element stays visible.
Returns True if successful. Default timeout = SMALL_TIMEOUT."""
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
self.wait_for_element_not_visible(selector, by=by, timeout=timeout)
if self.recorder_mode:
url = self.get_current_url()
if url and len(url) > 0:
if ("http:") in url or ("https:") in url or ("file:") in url:
if self.get_session_storage_item("pause_recorder") == "no":
time_stamp = self.execute_script("return Date.now();")
origin = self.get_origin()
action = ["asenv", selector, origin, time_stamp]
self.__extra_actions.append(action)
return True
############
def wait_for_text_not_visible(
self, text, selector="html", by=By.CSS_SELECTOR, timeout=None
):
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
return page_actions.wait_for_text_not_visible(
self.driver, text, selector, by, timeout
)
def assert_text_not_visible(
self, text, selector="html", by=By.CSS_SELECTOR, timeout=None
):
"""Similar to wait_for_text_not_visible()
Raises an exception if the text is still visible after timeout.
Returns True if successful. Default timeout = SMALL_TIMEOUT."""
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
return self.wait_for_text_not_visible(
text, selector, by=by, timeout=timeout
)
############
def wait_for_attribute_not_present(
self, selector, attribute, value=None, by=By.CSS_SELECTOR, timeout=None
):
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
selector, by = self.__recalculate_selector(selector, by)
return page_actions.wait_for_attribute_not_present(
self.driver, selector, attribute, value, by, timeout
)
def assert_attribute_not_present(
self, selector, attribute, value=None, by=By.CSS_SELECTOR, timeout=None
):
"""Similar to wait_for_attribute_not_present()
Raises an exception if the attribute is still present after timeout.
Returns True if successful. Default timeout = SMALL_TIMEOUT."""
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
return self.wait_for_attribute_not_present(
selector, attribute, value=value, by=by, timeout=timeout
)
############
def wait_for_and_accept_alert(self, timeout=None):
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
return page_actions.wait_for_and_accept_alert(self.driver, timeout)
def wait_for_and_dismiss_alert(self, timeout=None):
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
return page_actions.wait_for_and_dismiss_alert(self.driver, timeout)
def wait_for_and_switch_to_alert(self, timeout=None):
self.__check_scope()
if not timeout:
timeout = settings.LARGE_TIMEOUT
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
return page_actions.wait_for_and_switch_to_alert(self.driver, timeout)
############
def accept_alert(self, timeout=None):
""" Same as wait_for_and_accept_alert(), but smaller default T_O """
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
return page_actions.wait_for_and_accept_alert(self.driver, timeout)
def dismiss_alert(self, timeout=None):
""" Same as wait_for_and_dismiss_alert(), but smaller default T_O """
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
return page_actions.wait_for_and_dismiss_alert(self.driver, timeout)
def switch_to_alert(self, timeout=None):
""" Same as wait_for_and_switch_to_alert(), but smaller default T_O """
self.__check_scope()
if not timeout:
timeout = settings.SMALL_TIMEOUT
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
return page_actions.wait_for_and_switch_to_alert(self.driver, timeout)
############
def __assert_eq(self, *args, **kwargs):
""" Minified assert_equal() using only the list diff. """
minified_exception = None
try:
self.assertEqual(*args, **kwargs)
except Exception as e:
str_e = str(e)
minified_exception = "\nAssertionError:\n"
lines = str_e.split("\n")
countdown = 3
countdown_on = False
first_differing = False
skip_lines = False
for line in lines:
if countdown_on:
if not skip_lines:
minified_exception += line + "\n"
countdown = countdown - 1
if countdown == 0:
countdown_on = False
skip_lines = False
elif line.startswith("First differing"):
first_differing = True
countdown_on = True
countdown = 3
minified_exception += line + "\n"
elif line.startswith("First list"):
countdown_on = True
countdown = 3
if not first_differing:
minified_exception += line + "\n"
else:
skip_lines = True
elif line.startswith("F"):
countdown_on = True
countdown = 3
minified_exception += line + "\n"
elif line.startswith("+") or line.startswith("-"):
minified_exception += line + "\n"
elif line.startswith("?"):
minified_exception += line + "\n"
elif line.strip().startswith("*"):
minified_exception += line + "\n"
if minified_exception:
raise Exception(minified_exception)
def __process_visual_baseline_logs(self):
""" Save copies of baseline PNGs in "./latest_logs" during failures.
Also create a side_by_side.html file for visual comparisons. """
test_logpath = os.path.join(self.log_path, self.__get_test_id())
for baseline_copy_tuple in self.__visual_baseline_copies:
baseline_path = baseline_copy_tuple[0]
baseline_copy_name = baseline_copy_tuple[1]
b_c_alt_name = baseline_copy_tuple[2]
latest_png_path = baseline_copy_tuple[3]
latest_copy_name = baseline_copy_tuple[4]
l_c_alt_name = baseline_copy_tuple[5]
baseline_copy_path = os.path.join(test_logpath, baseline_copy_name)
b_c_alt_path = os.path.join(test_logpath, b_c_alt_name)
latest_copy_path = os.path.join(test_logpath, latest_copy_name)
l_c_alt_path = os.path.join(test_logpath, l_c_alt_name)
if len(self.__visual_baseline_copies) == 1:
baseline_copy_path = b_c_alt_path
latest_copy_path = l_c_alt_path
if (
os.path.exists(baseline_path)
and not os.path.exists(baseline_copy_path)
):
self.__create_log_path_as_needed(test_logpath)
shutil.copy(baseline_path, baseline_copy_path)
if (
os.path.exists(latest_png_path)
and not os.path.exists(latest_copy_path)
):
self.__create_log_path_as_needed(test_logpath)
shutil.copy(latest_png_path, latest_copy_path)
if len(self.__visual_baseline_copies) != 1:
return # Only possible when deferred visual asserts are used
head = (
'<head><meta charset="utf-8">'
'<meta name="viewport" content="shrink-to-fit=no">'
'<link rel="shortcut icon" href="%s">'
"<title>Visual Comparison</title>"
"</head>"
% (constants.SideBySide.SIDE_BY_SIDE_PNG)
)
table_html = (
'<table border="3px solid #E6E6E6;" width="100%;" padding: 12px;'
' font-size="16px;" text-align="left;" id="results-table"'
' style="background-color: #FAFAFA;">'
'<thead id="results-table-head">'
'<tr>'
'<th style="background-color: rgba(0, 128, 0, 0.25);"'
' col="baseline">Baseline Screenshot</th>'
'<th style="background-color: rgba(128, 0, 0, 0.25);"'
' col="failure">Visual Diff Failure Screenshot</th>'
"</tr></thead>"
)
row = (
'<tbody class="compare results-table-row">'
'<tr style="background-color: #F4F4FE;">'
'<td><img src="%s" width="100%%" /></td>'
'<td><img src="%s" width="100%%" /></td>'
"</tr></tbody>"
"" % ("baseline.png", "baseline_diff.png")
)
header_text = "SeleniumBase Visual Comparison"
header = '<h3 align="center">%s</h3>' % header_text
table_html += row
table_html += "</table>"
footer = "<br /><b>Last updated:</b> "
timestamp, the_date, the_time = log_helper.get_master_time()
last_updated = "%s at %s" % (the_date, the_time)
footer = footer + "%s" % last_updated
gen_by = (
'<p><div>Generated by: <b><a href="https://seleniumbase.io/">'
"SeleniumBase</a></b></div></p><p></p>"
)
footer = footer + gen_by
the_html = (
'<html lang="en">'
+ head
+ '<body style="background-color: #FCFCF4;">'
+ header
+ table_html
+ footer
+ "</body>"
)
file_path = os.path.join(test_logpath, constants.SideBySide.HTML_FILE)
out_file = codecs.open(file_path, "w+", encoding="utf-8")
out_file.writelines(the_html)
out_file.close()
def check_window(
self,
name="default",
level=0,
baseline=False,
check_domain=True,
full_diff=False,
):
"""*** Automated Visual Testing with SeleniumBase ***
The first time a test calls self.check_window() for a unique "name"
parameter provided, it will set a visual baseline, meaning that it
creates a folder, saves the URL to a file, saves the current window
screenshot to a file, and creates the following three files
with the listed data saved:
tags_level1.txt -> HTML tags from the window
tags_level2.txt -> HTML tags + attributes from the window
tags_level3.txt -> HTML tags + attributes/values from the window
Baseline folders are named based on the test name and the name
parameter passed to self.check_window(). The same test can store
multiple baseline folders.
If the baseline is being set/reset, the "level" doesn't matter.
After the first run of self.check_window(), it will compare the
HTML tags of the latest window to the one from the initial run.
Here's how the level system works:
* level=0 ->
DRY RUN ONLY - Will perform comparisons to the baseline (and
print out any differences that are found) but
won't fail the test even if differences exist.
* level=1 ->
HTML tags are compared to tags_level1.txt
* level=2 ->
HTML tags are compared to tags_level1.txt and
HTML tags/attributes are compared to tags_level2.txt
* level=3 ->
HTML tags are compared to tags_level1.txt and
HTML tags + attributes are compared to tags_level2.txt and
HTML tags + attributes/values are compared to tags_level3.txt
As shown, Level-3 is the most strict, Level-1 is the least strict.
If the comparisons from the latest window to the existing baseline
don't match, the current test will fail, except for Level-0 tests.
You can reset the visual baseline on the command line by using:
--visual_baseline
As long as "--visual_baseline" is used on the command line while
running tests, the self.check_window() method cannot fail because
it will rebuild the visual baseline rather than comparing the html
tags of the latest run to the existing baseline. If there are any
expected layout changes to a website that you're testing, you'll
need to reset the baseline to prevent unnecessary failures.
self.check_window() will fail with "Page Domain Mismatch Failure"
if the page domain doesn't match the domain of the baseline,
unless "check_domain" is set to False when calling check_window().
If you want to use self.check_window() to compare a web page to
a later version of itself from within the same test run, you can
add the parameter "baseline=True" to the first time you call
self.check_window() in a test to use that as the baseline. This
only makes sense if you're calling self.check_window() more than
once with the same name parameter in the same test.
If "full_diff" is set to False, the error output will only
include the first differing element in the list comparison.
Set "full_diff" to True if you want to see the full output.
Automated Visual Testing with self.check_window() is not very
effective for websites that have dynamic content that changes
the layout and structure of web pages. For those, you're much
better off using regular SeleniumBase functional testing.
Example usage:
self.check_window(name="testing", level=0)
self.check_window(name="xkcd_home", level=1)
self.check_window(name="github_page", level=2)
self.check_window(name="wikipedia_page", level=3)
"""
self.wait_for_ready_state_complete()
if level == "0":
level = 0
if level == "1":
level = 1
if level == "2":
level = 2
if level == "3":
level = 3
if level != 0 and level != 1 and level != 2 and level != 3:
raise Exception('Parameter "level" must be set to 0, 1, 2, or 3!')
if self.demo_mode:
message = (
"WARNING: Using check_window() from Demo Mode may lead "
"to unexpected results caused by Demo Mode HTML changes."
)
logging.info(message)
test_id = self.__get_display_id().split("::")[-1]
if not name or len(name) < 1:
name = "default"
name = str(name)
from seleniumbase.core import visual_helper
visual_helper.visual_baseline_folder_setup()
baseline_dir = constants.VisualBaseline.STORAGE_FOLDER
visual_baseline_path = baseline_dir + "/" + test_id + "/" + name
page_url_file = visual_baseline_path + "/page_url.txt"
baseline_png = "baseline.png"
baseline_png_path = visual_baseline_path + "/%s" % baseline_png
latest_png = "latest.png"
latest_png_path = visual_baseline_path + "/%s" % latest_png
level_1_file = visual_baseline_path + "/tags_level_1.txt"
level_2_file = visual_baseline_path + "/tags_level_2.txt"
level_3_file = visual_baseline_path + "/tags_level_3.txt"
set_baseline = False
if baseline or self.visual_baseline:
set_baseline = True
if not os.path.exists(visual_baseline_path):
set_baseline = True
try:
os.makedirs(visual_baseline_path)
except Exception:
pass # Only reachable during multi-threaded test runs
if not os.path.exists(page_url_file):
set_baseline = True
if not os.path.exists(baseline_png_path):
set_baseline = True
if not os.path.exists(level_1_file):
set_baseline = True
if not os.path.exists(level_2_file):
set_baseline = True
if not os.path.exists(level_3_file):
set_baseline = True
page_url = self.get_current_url()
soup = self.get_beautiful_soup()
html_tags = soup.body.find_all()
level_1 = [[tag.name] for tag in html_tags]
level_1 = json.loads(json.dumps(level_1)) # Tuples become lists
level_2 = [[tag.name, sorted(tag.attrs.keys())] for tag in html_tags]
level_2 = json.loads(json.dumps(level_2)) # Tuples become lists
level_3 = [[tag.name, sorted(tag.attrs.items())] for tag in html_tags]
level_3 = json.loads(json.dumps(level_3)) # Tuples become lists
if set_baseline:
self.save_screenshot(
baseline_png, visual_baseline_path, selector="body"
)
out_file = codecs.open(page_url_file, "w+", encoding="utf-8")
out_file.writelines(page_url)
out_file.close()
out_file = codecs.open(level_1_file, "w+", encoding="utf-8")
out_file.writelines(json.dumps(level_1))
out_file.close()
out_file = codecs.open(level_2_file, "w+", encoding="utf-8")
out_file.writelines(json.dumps(level_2))
out_file.close()
out_file = codecs.open(level_3_file, "w+", encoding="utf-8")
out_file.writelines(json.dumps(level_3))
out_file.close()
baseline_path = os.path.join(visual_baseline_path, baseline_png)
baseline_copy_name = "baseline_%s.png" % name
b_c_alt_name = "baseline.png"
latest_copy_name = "baseline_diff_%s.png" % name
l_c_alt_name = "baseline_diff.png"
baseline_copy_tuple = (
baseline_path, baseline_copy_name, b_c_alt_name,
latest_png_path, latest_copy_name, l_c_alt_name,
)
self.__visual_baseline_copies.append(baseline_copy_tuple)
if not set_baseline:
self.save_screenshot(
latest_png, visual_baseline_path, selector="body"
)
f = open(page_url_file, "r")
page_url_data = f.read().strip()
f.close()
f = open(level_1_file, "r")
level_1_data = json.loads(f.read())
f.close()
f = open(level_2_file, "r")
level_2_data = json.loads(f.read())
f.close()
f = open(level_3_file, "r")
level_3_data = json.loads(f.read())
f.close()
domain_fail = (
"\n*\nPage Domain Mismatch Failure: "
"Current Page Domain doesn't match the Page Domain of the "
"Baseline! Can't compare two completely different sites! "
"Run with --visual_baseline to reset the baseline!"
)
level_1_failure = (
"\n*\n*** Exception: <Level 1> Visual Diff Failure:\n"
"* HTML tags don't match the baseline!"
)
level_2_failure = (
"\n*\n*** Exception: <Level 2> Visual Diff Failure:\n"
"* HTML tag attribute names don't match the baseline!"
)
level_3_failure = (
"\n*\n*** Exception: <Level 3> Visual Diff Failure:\n"
"* HTML tag attribute values don't match the baseline!"
)
page_domain = self.get_domain_url(page_url)
page_data_domain = self.get_domain_url(page_url_data)
unittest.TestCase.maxDiff = 3200
if level != 0 and check_domain:
self.assertEqual(page_data_domain, page_domain, domain_fail)
unittest.TestCase.maxDiff = 6400 # Use `None` for no limit
if level == 3:
if not full_diff:
self.__assert_eq(level_3_data, level_3, level_3_failure)
else:
self.assertEqual(level_3_data, level_3, level_3_failure)
unittest.TestCase.maxDiff = 3200
if level == 2:
if not full_diff:
self.__assert_eq(level_2_data, level_2, level_2_failure)
else:
self.assertEqual(level_2_data, level_2, level_2_failure)
if level == 1:
if not full_diff:
self.__assert_eq(level_1_data, level_1, level_1_failure)
else:
self.assertEqual(level_1_data, level_1, level_1_failure)
unittest.TestCase.maxDiff = 6400 # Use `None` for no limit
if level == 0:
try:
unittest.TestCase.maxDiff = 3200
if check_domain:
self.assertEqual(
page_domain, page_data_domain, domain_fail
)
try:
if not full_diff:
self.__assert_eq(
level_1_data, level_1, level_1_failure
)
else:
self.assertEqual(
level_1_data, level_1, level_1_failure
)
except Exception as e:
print(e)
try:
if not full_diff:
self.__assert_eq(
level_2_data, level_2, level_2_failure
)
else:
self.assertEqual(
level_2_data, level_2, level_2_failure
)
except Exception as e:
print(e)
unittest.TestCase.maxDiff = 6400 # Use `None` for no limit
if not full_diff:
self.__assert_eq(
level_3_data, level_3, level_3_failure
)
else:
self.assertEqual(
level_3_data, level_3, level_3_failure
)
except Exception as e:
print(e) # Level-0 Dry Run (Only print the differences)
unittest.TestCase.maxDiff = None # Reset unittest.TestCase.maxDiff
# Since the check passed, do not save an extra copy of the baseline
del self.__visual_baseline_copies[-1] # .pop() returns the element
############
def __get_new_timeout(self, timeout):
""" When using --timeout_multiplier=#.# """
import math
self.__check_scope()
try:
timeout_multiplier = float(self.timeout_multiplier)
if timeout_multiplier <= 0.5:
timeout_multiplier = 0.5
timeout = int(math.ceil(timeout_multiplier * timeout))
return timeout
except Exception:
# Wrong data type for timeout_multiplier (expecting int or float)
return timeout
############
def __check_scope(self):
if hasattr(self, "browser"): # self.browser stores the type of browser
return # All good: setUp() already initialized variables in "self"
else:
from seleniumbase.common.exceptions import OutOfScopeException
message = (
"\n It looks like you are trying to call a SeleniumBase method"
"\n from outside the scope of your test class's `self` object,"
"\n which is initialized by calling BaseCase's setUp() method."
"\n The `self` object is where all test variables are defined."
"\n If you created a custom setUp() method (that overrided the"
"\n the default one), make sure to call super().setUp() in it."
"\n When using page objects, be sure to pass the `self` object"
"\n from your test class into your page object methods so that"
"\n they can call BaseCase class methods with all the required"
"\n variables, which are initialized during the setUp() method"
"\n that runs automatically before all tests called by pytest."
)
raise OutOfScopeException(message)
############
def __check_browser(self):
"""This method raises an exception if the window was already closed."""
active_window = None
try:
active_window = self.driver.current_window_handle # Fails if None
except Exception:
pass
if not active_window:
raise NoSuchWindowException("Active window was already closed!")
############
def __get_exception_message(self):
"""This method extracts the message from an exception if there
was an exception that occurred during the test, assuming
that the exception was in a try/except block and not thrown."""
exception_info = sys.exc_info()[1]
if hasattr(exception_info, "msg"):
exc_message = exception_info.msg
elif hasattr(exception_info, "message"):
exc_message = exception_info.message
else:
exc_message = sys.exc_info()
return exc_message
def __add_deferred_assert_failure(self):
""" Add a deferred_assert failure to a list for future processing. """
self.__check_scope()
current_url = self.driver.current_url
message = self.__get_exception_message()
self.__deferred_assert_failures.append(
"CHECK #%s: (%s) %s\n"
% (self.__deferred_assert_count, current_url, message)
)
############
def deferred_assert_element(
self, selector, by=By.CSS_SELECTOR, timeout=None
):
"""A non-terminating assertion for an element on a page.
Failures will be saved until the process_deferred_asserts()
method is called from inside a test, likely at the end of it."""
self.__check_scope()
if not timeout:
timeout = settings.MINI_TIMEOUT
if self.timeout_multiplier and timeout == settings.MINI_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
self.__deferred_assert_count += 1
try:
url = self.get_current_url()
if url == self.__last_url_of_deferred_assert:
timeout = 1 # Was already on page (full wait not needed)
else:
self.__last_url_of_deferred_assert = url
except Exception:
pass
try:
self.wait_for_element_visible(selector, by=by, timeout=timeout)
return True
except Exception:
self.__add_deferred_assert_failure()
return False
def deferred_assert_text(
self, text, selector="html", by=By.CSS_SELECTOR, timeout=None
):
"""A non-terminating assertion for text from an element on a page.
Failures will be saved until the process_deferred_asserts()
method is called from inside a test, likely at the end of it."""
self.__check_scope()
if not timeout:
timeout = settings.MINI_TIMEOUT
if self.timeout_multiplier and timeout == settings.MINI_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
self.__deferred_assert_count += 1
try:
url = self.get_current_url()
if url == self.__last_url_of_deferred_assert:
timeout = 1 # Was already on page (full wait not needed)
else:
self.__last_url_of_deferred_assert = url
except Exception:
pass
try:
self.wait_for_text_visible(text, selector, by=by, timeout=timeout)
return True
except Exception:
self.__add_deferred_assert_failure()
return False
def deferred_assert_exact_text(
self, text, selector="html", by=By.CSS_SELECTOR, timeout=None
):
"""A non-terminating assertion for exact text from an element.
Failures will be saved until the process_deferred_asserts()
method is called from inside a test, likely at the end of it."""
self.__check_scope()
if not timeout:
timeout = settings.MINI_TIMEOUT
if self.timeout_multiplier and timeout == settings.MINI_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
self.__deferred_assert_count += 1
try:
url = self.get_current_url()
if url == self.__last_url_of_deferred_assert:
timeout = 1 # Was already on page (full wait not needed)
else:
self.__last_url_of_deferred_assert = url
except Exception:
pass
try:
self.wait_for_exact_text_visible(
text, selector, by=by, timeout=timeout
)
return True
except Exception:
self.__add_deferred_assert_failure()
return False
def deferred_check_window(
self,
name="default",
level=0,
baseline=False,
check_domain=True,
full_diff=False,
):
"""A non-terminating assertion for the check_window() method.
Failures will be saved until the process_deferred_asserts()
method is called from inside a test, likely at the end of it."""
self.__check_scope()
self.__deferred_assert_count += 1
try:
self.check_window(
name=name,
level=level,
baseline=baseline,
check_domain=check_domain,
full_diff=full_diff,
)
return True
except Exception:
self.__add_deferred_assert_failure()
return False
def process_deferred_asserts(self, print_only=False):
"""To be used with any test that uses deferred_asserts, which are
non-terminating verifications that only raise exceptions
after this method is called.
This is useful for pages with multiple elements to be checked when
you want to find as many bugs as possible in a single test run
before having all the exceptions get raised simultaneously.
Might be more useful if this method is called after processing all
the deferred asserts on a single html page so that the failure
screenshot matches the location of the deferred asserts.
If "print_only" is set to True, the exception won't get raised."""
if self.__deferred_assert_failures:
exception_output = ""
exception_output += "\n***** DEFERRED ASSERTION FAILURES:\n"
exception_output += "TEST: %s\n\n" % self.id()
all_failing_checks = self.__deferred_assert_failures
self.__deferred_assert_failures = []
for tb in all_failing_checks:
exception_output += "%s\n" % tb
if print_only:
print(exception_output)
else:
raise Exception(exception_output.replace("\\n", "\n"))
############
# Alternate naming scheme for the "deferred_assert" methods.
def delayed_assert_element(
self, selector, by=By.CSS_SELECTOR, timeout=None
):
""" Same as self.deferred_assert_element() """
return self.deferred_assert_element(
selector=selector, by=by, timeout=timeout
)
def delayed_assert_text(
self, text, selector="html", by=By.CSS_SELECTOR, timeout=None
):
""" Same as self.deferred_assert_text() """
return self.deferred_assert_text(
text=text, selector=selector, by=by, timeout=timeout
)
def delayed_assert_exact_text(
self, text, selector="html", by=By.CSS_SELECTOR, timeout=None
):
""" Same as self.deferred_assert_exact_text() """
return self.deferred_assert_exact_text(
text=text, selector=selector, by=by, timeout=timeout
)
def delayed_check_window(
self,
name="default",
level=0,
baseline=False,
check_domain=True,
full_diff=False
):
""" Same as self.deferred_check_window() """
return self.deferred_check_window(
name=name,
level=level,
baseline=baseline,
check_domain=check_domain,
full_diff=full_diff,
)
def process_delayed_asserts(self, print_only=False):
""" Same as self.process_deferred_asserts() """
self.process_deferred_asserts(print_only=print_only)
############
def __js_click(self, selector, by=By.CSS_SELECTOR):
""" Clicks an element using pure JS. Does not use jQuery. """
selector, by = self.__recalculate_selector(selector, by)
css_selector = self.convert_to_css_selector(selector, by=by)
css_selector = re.escape(css_selector) # Add "\\" to special chars
css_selector = self.__escape_quotes_if_needed(css_selector)
script = (
"""var simulateClick = function (elem) {
var evt = new MouseEvent('click', {
bubbles: true,
cancelable: true,
view: window
});
var canceled = !elem.dispatchEvent(evt);
};
var someLink = document.querySelector('%s');
simulateClick(someLink);"""
% css_selector
)
self.execute_script(script)
def __js_click_all(self, selector, by=By.CSS_SELECTOR):
""" Clicks all matching elements using pure JS. (No jQuery) """
selector, by = self.__recalculate_selector(selector, by)
css_selector = self.convert_to_css_selector(selector, by=by)
css_selector = re.escape(css_selector) # Add "\\" to special chars
css_selector = self.__escape_quotes_if_needed(css_selector)
script = (
"""var simulateClick = function (elem) {
var evt = new MouseEvent('click', {
bubbles: true,
cancelable: true,
view: window
});
var canceled = !elem.dispatchEvent(evt);
};
var $elements = document.querySelectorAll('%s');
var index = 0, length = $elements.length;
for(; index < length; index++){
simulateClick($elements[index]);}"""
% css_selector
)
self.execute_script(script)
def __jquery_slow_scroll_to(self, selector, by=By.CSS_SELECTOR):
selector, by = self.__recalculate_selector(selector, by)
element = self.wait_for_element_present(
selector, by=by, timeout=settings.SMALL_TIMEOUT
)
dist = js_utils.get_scroll_distance_to_element(self.driver, element)
time_offset = 0
try:
if dist and abs(dist) > constants.Values.SSMD:
time_offset = int(
float(abs(dist) - constants.Values.SSMD) / 12.5
)
if time_offset > 950:
time_offset = 950
except Exception:
time_offset = 0
scroll_time_ms = 550 + time_offset
sleep_time = 0.625 + (float(time_offset) / 1000.0)
selector = self.convert_to_css_selector(selector, by=by)
selector = self.__make_css_match_first_element_only(selector)
scroll_script = (
"""jQuery([document.documentElement, document.body]).animate({"""
"""scrollTop: jQuery('%s').offset().top - 130}, %s);"""
% (selector, scroll_time_ms)
)
if js_utils.is_jquery_activated(self.driver):
self.execute_script(scroll_script)
else:
self.__slow_scroll_to_element(element)
self.sleep(sleep_time)
def __jquery_click(self, selector, by=By.CSS_SELECTOR):
""" Clicks an element using jQuery. Different from using pure JS. """
selector, by = self.__recalculate_selector(selector, by)
self.wait_for_element_present(
selector, by=by, timeout=settings.SMALL_TIMEOUT
)
selector = self.convert_to_css_selector(selector, by=by)
selector = self.__make_css_match_first_element_only(selector)
click_script = """jQuery('%s')[0].click();""" % selector
self.safe_execute_script(click_script)
def __get_major_browser_version(self):
try:
version = self.driver.__dict__["caps"]["browserVersion"]
except Exception:
version = self.driver.__dict__["caps"]["version"]
self.driver.__dict__["caps"]["browserVersion"] = version
major_browser_version = version.split(".")[0]
return major_browser_version
def __get_href_from_link_text(self, link_text, hard_fail=True):
href = self.get_link_attribute(link_text, "href", hard_fail)
if not href:
return None
if href.startswith("//"):
link = "http:" + href
elif href.startswith("/"):
url = self.driver.current_url
domain_url = self.get_domain_url(url)
link = domain_url + href
else:
link = href
return link
def __click_dropdown_link_text(self, link_text, link_css):
""" When a link may be hidden under a dropdown menu, use this. """
soup = self.get_beautiful_soup()
drop_down_list = []
for item in soup.select("li[class]"):
drop_down_list.append(item)
csstype = link_css.split("[")[1].split("=")[0]
for item in drop_down_list:
item_text_list = item.text.split("\n")
if link_text in item_text_list and csstype in item.decode():
dropdown_css = ""
try:
for css_class in item["class"]:
dropdown_css += "."
dropdown_css += css_class
except Exception:
continue
dropdown_css = item.name + dropdown_css
matching_dropdowns = self.find_visible_elements(dropdown_css)
for dropdown in matching_dropdowns:
# The same class names might be used for multiple dropdowns
if dropdown.is_displayed():
try:
try:
page_actions.hover_element(
self.driver,
dropdown,
)
except Exception:
# If hovering fails, driver is likely outdated
# Time to go directly to the hidden link text
self.open(
self.__get_href_from_link_text(link_text)
)
return True
page_actions.hover_element_and_click(
self.driver,
dropdown,
link_text,
click_by=By.LINK_TEXT,
timeout=0.12,
)
return True
except Exception:
pass
return False
def __get_href_from_partial_link_text(self, link_text, hard_fail=True):
href = self.get_partial_link_text_attribute(
link_text, "href", hard_fail
)
if not href:
return None
if href.startswith("//"):
link = "http:" + href
elif href.startswith("/"):
url = self.driver.current_url
domain_url = self.get_domain_url(url)
link = domain_url + href
else:
link = href
return link
def __click_dropdown_partial_link_text(self, link_text, link_css):
""" When a partial link may be hidden under a dropdown, use this. """
soup = self.get_beautiful_soup()
drop_down_list = []
for item in soup.select("li[class]"):
drop_down_list.append(item)
csstype = link_css.split("[")[1].split("=")[0]
for item in drop_down_list:
item_text_list = item.text.split("\n")
if link_text in item_text_list and csstype in item.decode():
dropdown_css = ""
try:
for css_class in item["class"]:
dropdown_css += "."
dropdown_css += css_class
except Exception:
continue
dropdown_css = item.name + dropdown_css
matching_dropdowns = self.find_visible_elements(dropdown_css)
for dropdown in matching_dropdowns:
# The same class names might be used for multiple dropdowns
if dropdown.is_displayed():
try:
try:
page_actions.hover_element(
self.driver, dropdown
)
except Exception:
# If hovering fails, driver is likely outdated
# Time to go directly to the hidden link text
self.open(
self.__get_href_from_partial_link_text(
link_text
)
)
return True
page_actions.hover_element_and_click(
self.driver,
dropdown,
link_text,
click_by=By.LINK_TEXT,
timeout=0.12,
)
return True
except Exception:
pass
return False
def __recalculate_selector(self, selector, by, xp_ok=True):
"""Use autodetection to return the correct selector with "by" updated.
If "xp_ok" is False, don't call convert_css_to_xpath(), which is
used to make the ":contains()" selector valid outside JS calls."""
_type = type(selector) # First make sure the selector is a string
not_string = False
if not python3:
if _type is not str and _type is not unicode: # noqa: F821
not_string = True
else:
if _type is not str:
not_string = True
if not_string:
msg = "Expecting a selector of type: \"<class 'str'>\" (string)!"
raise Exception('Invalid selector type: "%s"\n%s' % (_type, msg))
if page_utils.is_xpath_selector(selector):
by = By.XPATH
if page_utils.is_link_text_selector(selector):
selector = page_utils.get_link_text_from_selector(selector)
by = By.LINK_TEXT
if page_utils.is_partial_link_text_selector(selector):
selector = page_utils.get_partial_link_text_from_selector(selector)
by = By.PARTIAL_LINK_TEXT
if page_utils.is_name_selector(selector):
name = page_utils.get_name_from_selector(selector)
selector = '[name="%s"]' % name
by = By.CSS_SELECTOR
if xp_ok:
if ":contains(" in selector and by == By.CSS_SELECTOR:
selector = self.convert_css_to_xpath(selector)
by = By.XPATH
return (selector, by)
def __looks_like_a_page_url(self, url):
"""Returns True if the url parameter looks like a URL. This method
is slightly more lenient than page_utils.is_valid_url(url) due to
possible typos when calling self.get(url), which will try to
navigate to the page if a URL is detected, but will instead call
self.get_element(URL_AS_A_SELECTOR) if the input in not a URL."""
if (
url.startswith("http:")
or url.startswith("https:")
or url.startswith("://")
or url.startswith("chrome:")
or url.startswith("about:")
or url.startswith("data:")
or url.startswith("file:")
or url.startswith("edge:")
or url.startswith("opera:")
or url.startswith("view-source:")
):
return True
else:
return False
def __make_css_match_first_element_only(self, selector):
# Only get the first match
return page_utils.make_css_match_first_element_only(selector)
def __demo_mode_pause_if_active(self, tiny=False):
if self.demo_mode:
wait_time = settings.DEFAULT_DEMO_MODE_TIMEOUT
if self.demo_sleep:
wait_time = float(self.demo_sleep)
if not tiny:
time.sleep(wait_time)
else:
time.sleep(wait_time / 3.4)
elif self.slow_mode:
self.__slow_mode_pause_if_active()
def __slow_mode_pause_if_active(self):
if self.slow_mode:
wait_time = settings.DEFAULT_DEMO_MODE_TIMEOUT
if self.demo_sleep:
wait_time = float(self.demo_sleep)
time.sleep(wait_time)
def __demo_mode_scroll_if_active(self, selector, by):
if self.demo_mode:
self.slow_scroll_to(selector, by=by)
def __demo_mode_highlight_if_active(self, selector, by):
if self.demo_mode:
# Includes self.slow_scroll_to(selector, by=by) by default
self.highlight(selector, by=by)
elif self.slow_mode:
# Just do the slow scroll part of the highlight() method
time.sleep(0.08)
selector, by = self.__recalculate_selector(selector, by)
element = self.wait_for_element_visible(
selector, by=by, timeout=settings.SMALL_TIMEOUT
)
try:
scroll_distance = js_utils.get_scroll_distance_to_element(
self.driver, element
)
if abs(scroll_distance) > constants.Values.SSMD:
self.__jquery_slow_scroll_to(selector, by)
else:
self.__slow_scroll_to_element(element)
except (StaleElementReferenceException, ENI_Exception):
self.wait_for_ready_state_complete()
time.sleep(0.12)
element = self.wait_for_element_visible(
selector, by=by, timeout=settings.SMALL_TIMEOUT
)
self.__slow_scroll_to_element(element)
time.sleep(0.12)
def __scroll_to_element(self, element, selector=None, by=By.CSS_SELECTOR):
success = js_utils.scroll_to_element(self.driver, element)
if not success and selector:
self.wait_for_ready_state_complete()
element = page_actions.wait_for_element_visible(
self.driver, selector, by, timeout=settings.SMALL_TIMEOUT
)
self.__demo_mode_pause_if_active(tiny=True)
def __slow_scroll_to_element(self, element):
try:
js_utils.slow_scroll_to_element(self.driver, element, self.browser)
except Exception:
# Scroll to the element instantly if the slow scroll fails
js_utils.scroll_to_element(self.driver, element)
def __highlight_with_assert_success(
self, message, selector, by=By.CSS_SELECTOR
):
selector, by = self.__recalculate_selector(selector, by, xp_ok=False)
element = self.wait_for_element_visible(
selector, by=by, timeout=settings.SMALL_TIMEOUT
)
try:
scroll_distance = js_utils.get_scroll_distance_to_element(
self.driver, element
)
if abs(scroll_distance) > constants.Values.SSMD:
self.__jquery_slow_scroll_to(selector, by)
else:
self.__slow_scroll_to_element(element)
except Exception:
self.wait_for_ready_state_complete()
time.sleep(0.12)
element = self.wait_for_element_visible(
selector, by=by, timeout=settings.SMALL_TIMEOUT
)
self.__slow_scroll_to_element(element)
try:
selector = self.convert_to_css_selector(selector, by=by)
except Exception:
# Don't highlight if can't convert to CSS_SELECTOR
return
o_bs = "" # original_box_shadow
try:
style = element.get_attribute("style")
except Exception:
self.wait_for_ready_state_complete()
time.sleep(0.12)
element = self.wait_for_element_visible(
selector, by=By.CSS_SELECTOR, timeout=settings.SMALL_TIMEOUT
)
style = element.get_attribute("style")
if style:
if "box-shadow: " in style:
box_start = style.find("box-shadow: ")
box_end = style.find(";", box_start) + 1
original_box_shadow = style[box_start:box_end]
o_bs = original_box_shadow
if ":contains" not in selector and ":first" not in selector:
selector = re.escape(selector)
selector = self.__escape_quotes_if_needed(selector)
self.__highlight_with_js_2(message, selector, o_bs)
else:
selector = self.__make_css_match_first_element_only(selector)
selector = re.escape(selector)
selector = self.__escape_quotes_if_needed(selector)
try:
self.__highlight_with_jquery_2(message, selector, o_bs)
except Exception:
pass # JQuery probably couldn't load. Skip highlighting.
time.sleep(0.065)
def __highlight_with_js_2(self, message, selector, o_bs):
duration = self.message_duration
if not duration:
duration = settings.DEFAULT_MESSAGE_DURATION
if (self.headless or self.xvfb) and float(duration) > 0.75:
duration = 0.75
js_utils.highlight_with_js_2(
self.driver, message, selector, o_bs, duration
)
def __highlight_with_jquery_2(self, message, selector, o_bs):
duration = self.message_duration
if not duration:
duration = settings.DEFAULT_MESSAGE_DURATION
if (self.headless or self.xvfb) and float(duration) > 0.75:
duration = 0.75
js_utils.highlight_with_jquery_2(
self.driver, message, selector, o_bs, duration
)
############
from seleniumbase.common import decorators
@decorators.deprecated("You should use re.escape() instead.")
def jq_format(self, code):
# DEPRECATED - re.escape() already performs the intended action.
return js_utils._jq_format(code)
############
def setUp(self, masterqa_mode=False):
"""
Be careful if a subclass of BaseCase overrides setUp()
You'll need to add the following line to the subclass setUp() method:
super(SubClassOfBaseCase, self).setUp()
"""
if not hasattr(self, "_using_sb_fixture") and self.__called_setup:
# This test already called setUp()
return
self.__called_setup = True
self.__called_teardown = False
self.masterqa_mode = masterqa_mode
self.is_pytest = None
try:
# This raises an exception if the test is not coming from pytest
self.is_pytest = sb_config.is_pytest
except Exception:
# Not using pytest (probably nosetests)
self.is_pytest = False
if self.is_pytest:
# pytest-specific code
test_id = self.__get_test_id()
self.test_id = test_id
if hasattr(self, "_using_sb_fixture"):
self.test_id = sb_config._test_id
self.browser = sb_config.browser
self.data = sb_config.data
self.var1 = sb_config.var1
self.var2 = sb_config.var2
self.var3 = sb_config.var3
self.slow_mode = sb_config.slow_mode
self.demo_mode = sb_config.demo_mode
self.demo_sleep = sb_config.demo_sleep
self.highlights = sb_config.highlights
self.time_limit = sb_config._time_limit
sb_config.time_limit = sb_config._time_limit # Reset between tests
self.environment = sb_config.environment
self.env = self.environment # Add a shortened version
self.with_selenium = sb_config.with_selenium # Should be True
self.headless = sb_config.headless
self.headless_active = False
self.headed = sb_config.headed
self.xvfb = sb_config.xvfb
self.locale_code = sb_config.locale_code
self.interval = sb_config.interval
self.start_page = sb_config.start_page
self.log_path = sb_config.log_path
self.with_testing_base = sb_config.with_testing_base
self.with_basic_test_info = sb_config.with_basic_test_info
self.with_screen_shots = sb_config.with_screen_shots
self.with_page_source = sb_config.with_page_source
self.with_db_reporting = sb_config.with_db_reporting
self.with_s3_logging = sb_config.with_s3_logging
self.protocol = sb_config.protocol
self.servername = sb_config.servername
self.port = sb_config.port
self.proxy_string = sb_config.proxy_string
self.proxy_bypass_list = sb_config.proxy_bypass_list
self.user_agent = sb_config.user_agent
self.mobile_emulator = sb_config.mobile_emulator
self.device_metrics = sb_config.device_metrics
self.cap_file = sb_config.cap_file
self.cap_string = sb_config.cap_string
self.settings_file = sb_config.settings_file
self.database_env = sb_config.database_env
self.message_duration = sb_config.message_duration
self.js_checking_on = sb_config.js_checking_on
self.ad_block_on = sb_config.ad_block_on
self.block_images = sb_config.block_images
self.chromium_arg = sb_config.chromium_arg
self.firefox_arg = sb_config.firefox_arg
self.firefox_pref = sb_config.firefox_pref
self.verify_delay = sb_config.verify_delay
self.recorder_mode = sb_config.recorder_mode
self.recorder_ext = sb_config.recorder_mode
self.disable_csp = sb_config.disable_csp
self.disable_ws = sb_config.disable_ws
self.enable_ws = sb_config.enable_ws
if not self.disable_ws:
self.enable_ws = True
self.enable_sync = sb_config.enable_sync
self.use_auto_ext = sb_config.use_auto_ext
self.no_sandbox = sb_config.no_sandbox
self.disable_gpu = sb_config.disable_gpu
self.incognito = sb_config.incognito
self.guest_mode = sb_config.guest_mode
self.devtools = sb_config.devtools
self.remote_debug = sb_config.remote_debug
self._multithreaded = sb_config._multithreaded
self._reuse_session = sb_config.reuse_session
self._crumbs = sb_config.crumbs
self.dashboard = sb_config.dashboard
self._dash_initialized = sb_config._dashboard_initialized
if self.dashboard and self._multithreaded:
import fasteners
self.dash_lock = fasteners.InterProcessLock(
constants.Dashboard.LOCKFILE
)
self.swiftshader = sb_config.swiftshader
self.user_data_dir = sb_config.user_data_dir
self.extension_zip = sb_config.extension_zip
self.extension_dir = sb_config.extension_dir
self.maximize_option = sb_config.maximize_option
self.save_screenshot_after_test = sb_config.save_screenshot
self.visual_baseline = sb_config.visual_baseline
self.timeout_multiplier = sb_config.timeout_multiplier
self.pytest_html_report = sb_config.pytest_html_report
self.report_on = False
if self.pytest_html_report:
self.report_on = True
self.use_grid = False
if self.servername != "localhost":
# Use Selenium Grid (Use --server="127.0.0.1" for a local Grid)
self.use_grid = True
if self.with_db_reporting:
import getpass
import uuid
from seleniumbase.core.application_manager import (
ApplicationManager,
)
from seleniumbase.core.testcase_manager import (
ExecutionQueryPayload,
)
from seleniumbase.core.testcase_manager import (
TestcaseDataPayload,
)
from seleniumbase.core.testcase_manager import TestcaseManager
self.execution_guid = str(uuid.uuid4())
self.testcase_guid = None
self.execution_start_time = 0
self.case_start_time = 0
self.application = None
self.testcase_manager = None
self.error_handled = False
self.testcase_manager = TestcaseManager(self.database_env)
#
exec_payload = ExecutionQueryPayload()
exec_payload.execution_start_time = int(time.time() * 1000)
self.execution_start_time = exec_payload.execution_start_time
exec_payload.guid = self.execution_guid
exec_payload.username = getpass.getuser()
self.testcase_manager.insert_execution_data(exec_payload)
#
data_payload = TestcaseDataPayload()
self.testcase_guid = str(uuid.uuid4())
data_payload.guid = self.testcase_guid
data_payload.execution_guid = self.execution_guid
if self.with_selenium:
data_payload.browser = self.browser
else:
data_payload.browser = "N/A"
data_payload.test_address = test_id
application = ApplicationManager.generate_application_string(
self._testMethodName
)
data_payload.env = application.split(".")[0]
data_payload.start_time = application.split(".")[1]
data_payload.state = constants.State.UNTESTED
self.__skip_reason = None
self.testcase_manager.insert_testcase_data(data_payload)
self.case_start_time = int(time.time() * 1000)
if self.headless or self.xvfb:
width = settings.HEADLESS_START_WIDTH
height = settings.HEADLESS_START_HEIGHT
try:
# from pyvirtualdisplay import Display # Skip for own lib
from sbvirtualdisplay import Display
self.display = Display(visible=0, size=(width, height))
self.display.start()
self.headless_active = True
except Exception:
# pyvirtualdisplay might not be necessary anymore because
# Chrome and Firefox now have built-in headless displays
pass
else:
# (Nosetests / Not Pytest)
pass # Setup performed in plugins
# Verify that SeleniumBase is installed successfully
if not hasattr(self, "browser"):
raise Exception(
'SeleniumBase plugins DID NOT load! * Please REINSTALL!\n'
'*** Either install SeleniumBase in Dev Mode from a clone:\n'
' >>> "pip install -e ." (Run in DIR with setup.py)\n'
'*** Or install the latest SeleniumBase version from PyPI:\n'
' >>> "pip install -U seleniumbase" (Run in any DIR)'
)
if not hasattr(sb_config, "_is_timeout_changed"):
# Should only be reachable from pure Python runs
sb_config._is_timeout_changed = False
sb_config._SMALL_TIMEOUT = settings.SMALL_TIMEOUT
sb_config._LARGE_TIMEOUT = settings.LARGE_TIMEOUT
if sb_config._is_timeout_changed:
if sb_config._SMALL_TIMEOUT and sb_config._LARGE_TIMEOUT:
settings.SMALL_TIMEOUT = sb_config._SMALL_TIMEOUT
settings.LARGE_TIMEOUT = sb_config._LARGE_TIMEOUT
if not hasattr(sb_config, "_recorded_actions"):
# Only filled when Recorder Mode is enabled
sb_config._recorded_actions = {}
if not hasattr(settings, "SWITCH_TO_NEW_TABS_ON_CLICK"):
# If using an older settings file, set the new definitions manually
settings.SWITCH_TO_NEW_TABS_ON_CLICK = True
# Parse the settings file
if self.settings_file:
from seleniumbase.core import settings_parser
settings_parser.set_settings(self.settings_file)
# Set variables that may be useful to developers
self.log_abspath = os.path.abspath(self.log_path)
self.data_path = os.path.join(self.log_path, self.__get_test_id())
self.data_abspath = os.path.abspath(self.data_path)
# Mobile Emulator device metrics: CSS Width, CSS Height, & Pixel-Ratio
if self.device_metrics:
metrics_string = self.device_metrics
metrics_string = metrics_string.replace(" ", "")
metrics_list = metrics_string.split(",")
exception_string = (
"Invalid input for Mobile Emulator device metrics!\n"
"Expecting a comma-separated string with three\n"
"integer values for Width, Height, and Pixel-Ratio.\n"
'Example: --metrics="411,731,3" '
)
if len(metrics_list) != 3:
raise Exception(exception_string)
try:
self.__device_width = int(metrics_list[0])
self.__device_height = int(metrics_list[1])
self.__device_pixel_ratio = int(metrics_list[2])
self.mobile_emulator = True
except Exception:
raise Exception(exception_string)
if self.mobile_emulator:
if not self.user_agent:
# Use the Pixel 4 user agent by default if not specified
self.user_agent = (
"Mozilla/5.0 (Linux; Android 11; Pixel 4 XL) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/89.0.4389.105 Mobile Safari/537.36"
)
if self.browser in ["firefox", "ie", "safari", "opera"]:
# The Recorder Mode browser extension is only for Chrome/Edge.
if self.recorder_mode:
message = (
"Recorder Mode ONLY supports Chrome and Edge!\n"
'(Your browser choice was: "%s")' % self.browser)
raise Exception(message)
# Dashboard pre-processing:
if self.dashboard:
if self._multithreaded:
with self.dash_lock:
sb_config._sbase_detected = True
sb_config._only_unittest = False
if not self._dash_initialized:
sb_config._dashboard_initialized = True
self._dash_initialized = True
self.__process_dashboard(False, init=True)
else:
sb_config._sbase_detected = True
sb_config._only_unittest = False
if not self._dash_initialized:
sb_config._dashboard_initialized = True
self._dash_initialized = True
self.__process_dashboard(False, init=True)
# Set the JS start time for Recorder Mode if reusing the session.
# Use this to skip saving recorded actions from previous tests.
if self.recorder_mode and self._reuse_session:
self.__js_start_time = int(time.time() * 1000.0)
has_url = False
if self._reuse_session:
if not hasattr(sb_config, "shared_driver"):
sb_config.shared_driver = None
if sb_config.shared_driver:
try:
self._default_driver = sb_config.shared_driver
self.driver = sb_config.shared_driver
self._drivers_list = [sb_config.shared_driver]
url = self.get_current_url()
if url is not None:
has_url = True
if len(self.driver.window_handles) > 1:
while len(self.driver.window_handles) > 1:
self.switch_to_window(
len(self.driver.window_handles) - 1
)
self.driver.close()
self.switch_to_window(0)
if self._crumbs:
self.driver.delete_all_cookies()
except Exception:
pass
if self._reuse_session and sb_config.shared_driver and has_url:
good_start_page = False
if self.recorder_ext:
self.__js_start_time = int(time.time() * 1000.0)
if self.start_page and len(self.start_page) >= 4:
if page_utils.is_valid_url(self.start_page):
good_start_page = True
self.__new_window_on_rec_open = False
self.open(self.start_page)
self.__new_window_on_rec_open = True
else:
new_start_page = "https://" + self.start_page
if page_utils.is_valid_url(new_start_page):
good_start_page = True
self.__dont_record_open = True
self.open(new_start_page)
self.__dont_record_open = False
if self.recorder_ext or (self._crumbs and not good_start_page):
if self.get_current_url() != "data:,":
self.__new_window_on_rec_open = False
self.open("data:,")
self.__new_window_on_rec_open = True
if self.recorder_ext:
self.__js_start_time = int(time.time() * 1000.0)
else:
# Launch WebDriver for both Pytest and Nosetests
self.driver = self.get_new_driver(
browser=self.browser,
headless=self.headless,
locale_code=self.locale_code,
protocol=self.protocol,
servername=self.servername,
port=self.port,
proxy=self.proxy_string,
proxy_bypass_list=self.proxy_bypass_list,
agent=self.user_agent,
switch_to=True,
cap_file=self.cap_file,
cap_string=self.cap_string,
recorder_ext=self.recorder_ext,
disable_csp=self.disable_csp,
enable_ws=self.enable_ws,
enable_sync=self.enable_sync,
use_auto_ext=self.use_auto_ext,
no_sandbox=self.no_sandbox,
disable_gpu=self.disable_gpu,
incognito=self.incognito,
guest_mode=self.guest_mode,
devtools=self.devtools,
remote_debug=self.remote_debug,
swiftshader=self.swiftshader,
ad_block_on=self.ad_block_on,
block_images=self.block_images,
chromium_arg=self.chromium_arg,
firefox_arg=self.firefox_arg,
firefox_pref=self.firefox_pref,
user_data_dir=self.user_data_dir,
extension_zip=self.extension_zip,
extension_dir=self.extension_dir,
is_mobile=self.mobile_emulator,
d_width=self.__device_width,
d_height=self.__device_height,
d_p_r=self.__device_pixel_ratio,
)
self._default_driver = self.driver
if self._reuse_session:
sb_config.shared_driver = self.driver
if self.browser in ["firefox", "ie", "safari", "opera"]:
# Only Chrome and Edge browsers have the mobile emulator.
# Some actions such as hover-clicking are different on mobile.
self.mobile_emulator = False
# Configure the test time limit (if used).
self.set_time_limit(self.time_limit)
# Set the start time for the test (in ms).
# Although the pytest clock starts before setUp() begins,
# the time-limit clock starts at the end of the setUp() method.
sb_config.start_time_ms = int(time.time() * 1000.0)
if not self.__start_time_ms:
# Call this once in case of multiple setUp() calls in the same test
self.__start_time_ms = sb_config.start_time_ms
def __set_last_page_screenshot(self):
"""self.__last_page_screenshot is only for pytest html report logs.
self.__last_page_screenshot_png is for all screenshot log files."""
if not self.__last_page_screenshot and (
not self.__last_page_screenshot_png
):
try:
element = self.driver.find_element(
by=By.TAG_NAME, value="body"
)
if self.is_pytest and self.report_on:
self.__last_page_screenshot_png = (
self.driver.get_screenshot_as_png()
)
self.__last_page_screenshot = element.screenshot_as_base64
else:
self.__last_page_screenshot_png = element.screenshot_as_png
except Exception:
if not self.__last_page_screenshot:
if self.is_pytest and self.report_on:
try:
self.__last_page_screenshot = (
self.driver.get_screenshot_as_base64()
)
except Exception:
self.__last_page_screenshot = (
constants.Warnings.SCREENSHOT_UNDEFINED
)
if not self.__last_page_screenshot_png:
try:
self.__last_page_screenshot_png = (
self.driver.get_screenshot_as_png()
)
except Exception:
self.__last_page_screenshot_png = (
constants.Warnings.SCREENSHOT_UNDEFINED
)
def __set_last_page_url(self):
if not self.__last_page_url:
try:
self.__last_page_url = log_helper.get_last_page(self.driver)
except Exception:
self.__last_page_url = None
def __set_last_page_source(self):
if not self.__last_page_source:
try:
self.__last_page_source = (
log_helper.get_html_source_with_base_href(
self.driver, self.driver.page_source
)
)
except Exception:
self.__last_page_source = (
constants.Warnings.PAGE_SOURCE_UNDEFINED
)
def __get_exception_info(self):
exc_message = None
if (
python3
and hasattr(self, "_outcome")
and (hasattr(self._outcome, "errors") and self._outcome.errors)
):
try:
exc_message = self._outcome.errors[0][1][1]
except Exception:
exc_message = "(Unknown Exception)"
else:
try:
exc_message = sys.last_value
except Exception:
exc_message = "(Unknown Exception)"
return str(exc_message)
def __insert_test_result(self, state, err):
from seleniumbase.core.testcase_manager import TestcaseDataPayload
data_payload = TestcaseDataPayload()
data_payload.runtime = int(time.time() * 1000) - self.case_start_time
data_payload.guid = self.testcase_guid
data_payload.execution_guid = self.execution_guid
data_payload.state = state
if err:
import traceback
tb_string = traceback.format_exc()
if "Message: " in tb_string:
data_payload.message = (
"Message: " + tb_string.split("Message: ")[-1]
)
elif "Exception: " in tb_string:
data_payload.message = tb_string.split("Exception: ")[-1]
elif "Error: " in tb_string:
data_payload.message = tb_string.split("Error: ")[-1]
else:
data_payload.message = self.__get_exception_info()
else:
test_id = self.__get_test_id_2()
if (
self.is_pytest
and test_id in sb_config._results.keys()
and (sb_config._results[test_id] == "Skipped")
):
if self.__skip_reason:
data_payload.message = "Skipped: " + self.__skip_reason
else:
data_payload.message = "Skipped: (no reason given)"
self.testcase_manager.update_testcase_data(data_payload)
def __add_pytest_html_extra(self):
if not self.__added_pytest_html_extra:
try:
if self.with_selenium:
if not self.__last_page_screenshot:
self.__set_last_page_screenshot()
self.__set_last_page_url()
self.__set_last_page_source()
if self.report_on:
extra_url = {}
extra_url["name"] = "URL"
extra_url["format"] = "url"
extra_url["content"] = self.get_current_url()
extra_url["mime_type"] = None
extra_url["extension"] = None
extra_image = {}
extra_image["name"] = "Screenshot"
extra_image["format"] = "image"
extra_image["content"] = self.__last_page_screenshot
extra_image["mime_type"] = "image/png"
extra_image["extension"] = "png"
self.__added_pytest_html_extra = True
if self.__last_page_screenshot != (
constants.Warnings.SCREENSHOT_UNDEFINED
):
self._html_report_extra.append(extra_url)
self._html_report_extra.append(extra_image)
except Exception:
pass
def __quit_all_drivers(self):
if self._reuse_session and sb_config.shared_driver:
if len(self._drivers_list) > 0:
if self._drivers_list[0] != sb_config.shared_driver:
if sb_config.shared_driver in self._drivers_list:
self._drivers_list.remove(sb_config.shared_driver)
self._drivers_list.insert(0, sb_config.shared_driver)
self._default_driver = self._drivers_list[0]
self.switch_to_default_driver()
if len(self._drivers_list) > 1:
self._drivers_list = self._drivers_list[1:]
else:
self._drivers_list = []
# Close all open browser windows
self._drivers_list.reverse() # Last In, First Out
for driver in self._drivers_list:
try:
driver.quit()
except AttributeError:
pass
except Exception:
pass
self.driver = None
self._default_driver = None
self._drivers_list = []
def __has_exception(self):
has_exception = False
if hasattr(sys, "last_traceback") and sys.last_traceback is not None:
has_exception = True
elif python3 and hasattr(self, "_outcome"):
if hasattr(self._outcome, "errors") and self._outcome.errors:
has_exception = True
else:
if python3:
has_exception = sys.exc_info()[1] is not None
else:
if not hasattr(self, "_using_sb_fixture_class") and (
not hasattr(self, "_using_sb_fixture_no_class")
):
has_exception = sys.exc_info()[1] is not None
else:
has_exception = len(str(sys.exc_info()[1]).strip()) > 0
if (
self.__will_be_skipped
and (hasattr(self, "_using_sb_fixture") or not python3)
):
has_exception = False
return has_exception
def __get_test_id(self):
""" The id used in various places such as the test log path. """
test_id = "%s.%s.%s" % (
self.__class__.__module__,
self.__class__.__name__,
self._testMethodName,
)
if self._sb_test_identifier and len(str(self._sb_test_identifier)) > 6:
test_id = self._sb_test_identifier
test_id = test_id.replace(".py::", ".").replace("::", ".")
return test_id
def __get_test_id_2(self):
""" The id for SeleniumBase Dashboard entries. """
if "PYTEST_CURRENT_TEST" in os.environ:
return os.environ["PYTEST_CURRENT_TEST"].split(" ")[0]
test_id = "%s.%s.%s" % (
self.__class__.__module__.split(".")[-1],
self.__class__.__name__,
self._testMethodName,
)
if self._sb_test_identifier and len(str(self._sb_test_identifier)) > 6:
test_id = self._sb_test_identifier
if test_id.count(".") > 1:
test_id = ".".join(test_id.split(".")[1:])
return test_id
def __get_display_id(self):
""" The id for running a test from pytest. (Displayed on Dashboard) """
if "PYTEST_CURRENT_TEST" in os.environ:
return os.environ["PYTEST_CURRENT_TEST"].split(" ")[0]
test_id = "%s.py::%s::%s" % (
self.__class__.__module__.replace(".", "/"),
self.__class__.__name__,
self._testMethodName,
)
if self._sb_test_identifier and len(str(self._sb_test_identifier)) > 6:
test_id = self._sb_test_identifier
if hasattr(self, "_using_sb_fixture_class"):
if test_id.count(".") >= 2:
parts = test_id.split(".")
full = parts[-3] + ".py::" + parts[-2] + "::" + parts[-1]
test_id = full
elif hasattr(self, "_using_sb_fixture_no_class"):
if test_id.count(".") >= 1:
parts = test_id.split(".")
full = parts[-2] + ".py::" + parts[-1]
test_id = full
return test_id
def __get_filename(self):
""" The filename of the current SeleniumBase test. (NOT Path) """
filename = None
if "PYTEST_CURRENT_TEST" in os.environ:
test_id = os.environ["PYTEST_CURRENT_TEST"].split(" ")[0]
filename = test_id.split("::")[0].split("/")[-1]
else:
filename = self.__class__.__module__.split(".")[-1] + ".py"
return filename
def __create_log_path_as_needed(self, test_logpath):
if not os.path.exists(test_logpath):
try:
os.makedirs(test_logpath)
except Exception:
pass # Only reachable during multi-threaded runs
def __process_dashboard(self, has_exception, init=False):
""" SeleniumBase Dashboard Processing """
if self._multithreaded:
existing_res = sb_config._results # For recording "Skipped" tests
abs_path = os.path.abspath(".")
dash_json_loc = constants.Dashboard.DASH_JSON
dash_jsonpath = os.path.join(abs_path, dash_json_loc)
if not init and os.path.exists(dash_jsonpath):
with open(dash_jsonpath, "r") as f:
dash_json = f.read().strip()
dash_data, d_id, dash_rt, tlp, d_stats = json.loads(dash_json)
num_passed, num_failed, num_skipped, num_untested = d_stats
sb_config._results = dash_data
sb_config._display_id = d_id
sb_config._duration = dash_rt # Dashboard Run Time
sb_config._d_t_log_path = tlp # Test Log Path
sb_config.item_count_passed = num_passed
sb_config.item_count_failed = num_failed
sb_config.item_count_skipped = num_skipped
sb_config.item_count_untested = num_untested
if len(sb_config._extra_dash_entries) > 0:
# First take care of existing entries from non-SeleniumBase tests
for test_id in sb_config._extra_dash_entries:
if test_id in sb_config._results.keys():
if sb_config._results[test_id] == "Skipped":
sb_config.item_count_skipped += 1
sb_config.item_count_untested -= 1
elif sb_config._results[test_id] == "Failed":
sb_config.item_count_failed += 1
sb_config.item_count_untested -= 1
elif sb_config._results[test_id] == "Passed":
sb_config.item_count_passed += 1
sb_config.item_count_untested -= 1
else: # Mark "Skipped" if unknown
sb_config.item_count_skipped += 1
sb_config.item_count_untested -= 1
sb_config._extra_dash_entries = [] # Reset the list to empty
# Process new entries
log_dir = self.log_path
ft_id = self.__get_test_id() # Full test id with path to log files
test_id = self.__get_test_id_2() # The test id used by the DashBoard
dud = "seleniumbase/plugins/pytest_plugin.py::BaseClass::base_method"
dud2 = "pytest_plugin.BaseClass.base_method"
if hasattr(self, "_using_sb_fixture") and self.__will_be_skipped:
test_id = sb_config._test_id
if not init:
duration_ms = int(time.time() * 1000) - self.__start_time_ms
duration = float(duration_ms) / 1000.0
duration = "{:.2f}".format(duration)
sb_config._duration[test_id] = duration
if (
has_exception
or self.save_screenshot_after_test
or self.__screenshot_count > 0
or self.__will_be_skipped
):
sb_config._d_t_log_path[test_id] = os.path.join(log_dir, ft_id)
else:
sb_config._d_t_log_path[test_id] = None
if test_id not in sb_config._display_id.keys():
sb_config._display_id[test_id] = self.__get_display_id()
if sb_config._display_id[test_id] == dud:
return
if (
hasattr(self, "_using_sb_fixture")
and test_id not in sb_config._results.keys()
):
if test_id.count(".") > 1:
alt_test_id = ".".join(test_id.split(".")[1:])
if alt_test_id in sb_config._results.keys():
sb_config._results.pop(alt_test_id)
elif test_id.count(".") == 1:
alt_test_id = sb_config._display_id[test_id]
alt_test_id = alt_test_id.replace(".py::", ".")
alt_test_id = alt_test_id.replace("::", ".")
if alt_test_id in sb_config._results.keys():
sb_config._results.pop(alt_test_id)
if test_id in sb_config._results.keys() and (
sb_config._results[test_id] == "Skipped"
):
if self.__passed_then_skipped:
# Multiple calls of setUp() and tearDown() in the same test
sb_config.item_count_passed -= 1
sb_config.item_count_untested += 1
self.__passed_then_skipped = False
sb_config._results[test_id] = "Skipped"
sb_config.item_count_skipped += 1
sb_config.item_count_untested -= 1
elif (
self._multithreaded
and test_id in existing_res.keys()
and existing_res[test_id] == "Skipped"
):
sb_config._results[test_id] = "Skipped"
sb_config.item_count_skipped += 1
sb_config.item_count_untested -= 1
elif has_exception:
if test_id not in sb_config._results.keys():
sb_config._results[test_id] = "Failed"
sb_config.item_count_failed += 1
sb_config.item_count_untested -= 1
elif not sb_config._results[test_id] == "Failed":
# tearDown() was called more than once in the test
if sb_config._results[test_id] == "Passed":
# Passed earlier, but last run failed
sb_config._results[test_id] = "Failed"
sb_config.item_count_failed += 1
sb_config.item_count_passed -= 1
else:
sb_config._results[test_id] = "Failed"
sb_config.item_count_failed += 1
sb_config.item_count_untested -= 1
else:
# pytest-rerunfailures caused a duplicate failure
sb_config._results[test_id] = "Failed"
else:
if (
test_id in sb_config._results.keys()
and sb_config._results[test_id] == "Failed"
):
# pytest-rerunfailures reran a test that failed
sb_config._d_t_log_path[test_id] = os.path.join(
log_dir, ft_id
)
sb_config.item_count_failed -= 1
sb_config.item_count_untested += 1
elif (
test_id in sb_config._results.keys()
and sb_config._results[test_id] == "Passed"
):
# tearDown() was called more than once in the test
sb_config.item_count_passed -= 1
sb_config.item_count_untested += 1
sb_config._results[test_id] = "Passed"
sb_config.item_count_passed += 1
sb_config.item_count_untested -= 1
else:
pass # Only initialize the Dashboard on the first processing
num_passed = sb_config.item_count_passed
num_failed = sb_config.item_count_failed
num_skipped = sb_config.item_count_skipped
num_untested = sb_config.item_count_untested
self.create_pie_chart(title=constants.Dashboard.TITLE)
self.add_data_point("Passed", num_passed, color="#84d474")
self.add_data_point("Untested", num_untested, color="#eaeaea")
self.add_data_point("Skipped", num_skipped, color="#efd8b4")
self.add_data_point("Failed", num_failed, color="#f17476")
style = (
'<link rel="stylesheet" charset="utf-8" '
'href="%s">' % constants.Dashboard.STYLE_CSS
)
auto_refresh_html = ""
if num_untested > 0:
# Refresh every X seconds when waiting for more test results
auto_refresh_html = constants.Dashboard.META_REFRESH_HTML
else:
# The tests are complete
if sb_config._using_html_report:
# Add the pie chart to the pytest html report
sb_config._saved_dashboard_pie = self.extract_chart()
if self._multithreaded:
abs_path = os.path.abspath(".")
dash_pie = json.dumps(sb_config._saved_dashboard_pie)
dash_pie_loc = constants.Dashboard.DASH_PIE
pie_path = os.path.join(abs_path, dash_pie_loc)
pie_file = codecs.open(pie_path, "w+", encoding="utf-8")
pie_file.writelines(dash_pie)
pie_file.close()
head = (
'<head><meta charset="utf-8">'
'<meta name="viewport" content="shrink-to-fit=no">'
'<link rel="shortcut icon" href="%s">'
"%s"
"<title>Dashboard</title>"
"%s</head>"
% (constants.Dashboard.DASH_PIE_PNG_1, auto_refresh_html, style)
)
table_html = (
"<div></div>"
'<table border="1px solid #e6e6e6;" width="100%;" padding: 5px;'
' font-size="12px;" text-align="left;" id="results-table">'
'<thead id="results-table-head">'
'<tr style="background-color: #F7F7FD;">'
'<th col="result">Result</th><th col="name">Test</th>'
'<th col="duration">Duration</th><th col="links">Links</th>'
"</tr></thead>"
)
the_failed = []
the_skipped = []
the_passed_hl = [] # Passed and has logs
the_passed_nl = [] # Passed and no logs
the_untested = []
if dud2 in sb_config._results.keys():
sb_config._results.pop(dud2)
for key in sb_config._results.keys():
t_res = sb_config._results[key]
t_dur = sb_config._duration[key]
t_d_id = sb_config._display_id[key]
t_l_path = sb_config._d_t_log_path[key]
res_low = t_res.lower()
if sb_config._results[key] == "Failed":
if not sb_config._d_t_log_path[key]:
sb_config._d_t_log_path[key] = os.path.join(log_dir, ft_id)
the_failed.append([res_low, t_res, t_d_id, t_dur, t_l_path])
elif sb_config._results[key] == "Skipped":
the_skipped.append([res_low, t_res, t_d_id, t_dur, t_l_path])
elif sb_config._results[key] == "Passed" and t_l_path:
the_passed_hl.append([res_low, t_res, t_d_id, t_dur, t_l_path])
elif sb_config._results[key] == "Passed" and not t_l_path:
the_passed_nl.append([res_low, t_res, t_d_id, t_dur, t_l_path])
elif sb_config._results[key] == "Untested":
the_untested.append([res_low, t_res, t_d_id, t_dur, t_l_path])
for row in the_failed:
row = (
'<tbody class="%s results-table-row">'
'<tr style="background-color: #FFF8F8;">'
'<td class="col-result">%s</td><td>%s</td><td>%s</td>'
'<td><a href="%s">Logs</a> / <a href="%s/">Data</a>'
"</td></tr></tbody>"
"" % (row[0], row[1], row[2], row[3], log_dir, row[4])
)
table_html += row
for row in the_skipped:
if not row[4]:
row = (
'<tbody class="%s results-table-row">'
'<tr style="background-color: #FEFEF9;">'
'<td class="col-result">%s</td><td>%s</td><td>%s</td>'
"<td>-</td></tr></tbody>"
% (row[0], row[1], row[2], row[3])
)
else:
row = (
'<tbody class="%s results-table-row">'
'<tr style="background-color: #FEFEF9;">'
'<td class="col-result">%s</td><td>%s</td><td>%s</td>'
'<td><a href="%s">Logs</a> / <a href="%s/">Data</a>'
"</td></tr></tbody>"
"" % (row[0], row[1], row[2], row[3], log_dir, row[4])
)
table_html += row
for row in the_passed_hl:
# Passed and has logs
row = (
'<tbody class="%s results-table-row">'
'<tr style="background-color: #F8FFF8;">'
'<td class="col-result">%s</td><td>%s</td><td>%s</td>'
'<td><a href="%s">Logs</a> / <a href="%s/">Data</a>'
"</td></tr></tbody>"
"" % (row[0], row[1], row[2], row[3], log_dir, row[4])
)
table_html += row
for row in the_passed_nl:
# Passed and no logs
row = (
'<tbody class="%s results-table-row">'
'<tr style="background-color: #F8FFF8;">'
'<td class="col-result">%s</td><td>%s</td><td>%s</td>'
"<td>-</td></tr></tbody>" % (row[0], row[1], row[2], row[3])
)
table_html += row
for row in the_untested:
row = (
'<tbody class="%s results-table-row"><tr>'
'<td class="col-result">%s</td><td>%s</td><td>%s</td>'
"<td>-</td></tr></tbody>" % (row[0], row[1], row[2], row[3])
)
table_html += row
table_html += "</table>"
add_more = "<br /><b>Last updated:</b> "
timestamp, the_date, the_time = log_helper.get_master_time()
last_updated = "%s at %s" % (the_date, the_time)
add_more = add_more + "%s" % last_updated
status = "<p></p><div><b>Status:</b> Awaiting results..."
status += " (Refresh the page for updates)"
if num_untested == 0:
status = "<p></p><div><b>Status:</b> Test Run Complete:"
if num_failed == 0:
if num_passed > 0:
if num_skipped == 0:
status += " <b>Success!</b> (All tests passed)"
else:
status += " <b>Success!</b> (No failing tests)"
else:
status += " All tests were skipped!"
else:
latest_logs_dir = "latest_logs/"
log_msg = "See latest logs for details"
if num_failed == 1:
status += (
" <b>1 test failed!</b> --- "
'(<b><a href="%s">%s</a></b>)'
"" % (latest_logs_dir, log_msg)
)
else:
status += (
" <b>%s tests failed!</b> --- "
'(<b><a href="%s">%s</a></b>)'
"" % (num_failed, latest_logs_dir, log_msg)
)
status += "</div><p></p>"
add_more = add_more + status
gen_by = (
'<p><div>Generated by: <b><a href="https://seleniumbase.io/">'
"SeleniumBase</a></b></div></p><p></p>"
)
add_more = add_more + gen_by
# Have dashboard auto-refresh on updates when using an http server
refresh_line = (
'<script type="text/javascript" src="%s">'
"</script>" % constants.Dashboard.LIVE_JS
)
if num_untested == 0 and sb_config._using_html_report:
sb_config._dash_final_summary = status
add_more = add_more + refresh_line
the_html = (
'<html lang="en">'
+ head
+ self.extract_chart()
+ table_html
+ add_more
)
abs_path = os.path.abspath(".")
file_path = os.path.join(abs_path, "dashboard.html")
out_file = codecs.open(file_path, "w+", encoding="utf-8")
out_file.writelines(the_html)
out_file.close()
sb_config._dash_html = the_html
if self._multithreaded:
d_stats = (num_passed, num_failed, num_skipped, num_untested)
_results = sb_config._results
_display_id = sb_config._display_id
_rt = sb_config._duration # Run Time (RT)
_tlp = sb_config._d_t_log_path # Test Log Path (TLP)
dash_json = json.dumps((_results, _display_id, _rt, _tlp, d_stats))
dash_json_loc = constants.Dashboard.DASH_JSON
dash_jsonpath = os.path.join(abs_path, dash_json_loc)
dash_json_file = codecs.open(dash_jsonpath, "w+", encoding="utf-8")
dash_json_file.writelines(dash_json)
dash_json_file.close()
def has_exception(self):
"""(This method should ONLY be used in custom tearDown() methods.)
This method returns True if the test failed or raised an exception.
This is useful for performing additional steps in your tearDown()
method (based on whether or not the test passed or failed).
Example use cases:
* Performing cleanup steps if a test didn't complete.
* Sending test data and/or results to a dashboard service.
"""
return self.__has_exception()
def save_teardown_screenshot(self):
"""(Should ONLY be used at the start of custom tearDown() methods.)
This method takes a screenshot of the current web page for a
failing test (or when running your tests with --save-screenshot).
That way your tearDown() method can navigate away from the last
page where the test failed, and still get the correct screenshot
before performing tearDown() steps on other pages. If this method
is not included in your custom tearDown() method, a screenshot
will still be taken after the last step of your tearDown(), where
you should be calling "super(SubClassOfBaseCase, self).tearDown()"
"""
try:
self.__check_scope()
except Exception:
return
if self.__has_exception() or self.save_screenshot_after_test:
test_logpath = os.path.join(self.log_path, self.__get_test_id())
self.__create_log_path_as_needed(test_logpath)
self.__set_last_page_screenshot()
self.__set_last_page_url()
self.__set_last_page_source()
if self.is_pytest:
self.__add_pytest_html_extra()
def tearDown(self):
"""
Be careful if a subclass of BaseCase overrides setUp()
You'll need to add the following line to the subclass's tearDown():
super(SubClassOfBaseCase, self).tearDown()
"""
if not hasattr(self, "_using_sb_fixture") and self.__called_teardown:
# This test already called tearDown()
return
if self.recorder_mode:
self.__process_recorded_actions()
self.__called_teardown = True
self.__called_setup = False
try:
is_pytest = self.is_pytest # This fails if overriding setUp()
if is_pytest:
with_selenium = self.with_selenium
except Exception:
sub_class_name = (
str(self.__class__.__bases__[0]).split(".")[-1].split("'")[0]
)
sub_file_name = str(self.__class__.__bases__[0]).split(".")[-2]
sub_file_name = sub_file_name + ".py"
class_name = str(self.__class__).split(".")[-1].split("'")[0]
file_name = str(self.__class__).split(".")[-2] + ".py"
class_name_used = sub_class_name
file_name_used = sub_file_name
if sub_class_name == "BaseCase":
class_name_used = class_name
file_name_used = file_name
fix_setup = "super(%s, self).setUp()" % class_name_used
fix_teardown = "super(%s, self).tearDown()" % class_name_used
message = (
"You're overriding SeleniumBase's BaseCase setUp() "
"method with your own setUp() method, which breaks "
"SeleniumBase. You can fix this by going to your "
"%s class located in your %s file and adding the "
"following line of code AT THE BEGINNING of your "
"setUp() method:\n%s\n\nAlso make sure "
"you have added the following line of code AT THE "
"END of your tearDown() method:\n%s\n"
% (class_name_used, file_name_used, fix_setup, fix_teardown)
)
raise Exception(message)
# *** Start tearDown() officially ***
self.__slow_mode_pause_if_active()
has_exception = self.__has_exception()
if self.__overrided_default_timeouts:
# Reset default timeouts in case there are more tests
# These were changed in set_default_timeout()
if sb_config._SMALL_TIMEOUT and sb_config._LARGE_TIMEOUT:
settings.SMALL_TIMEOUT = sb_config._SMALL_TIMEOUT
settings.LARGE_TIMEOUT = sb_config._LARGE_TIMEOUT
sb_config._is_timeout_changed = False
self.__overrided_default_timeouts = False
deferred_exception = None
if self.__deferred_assert_failures:
print(
"\nWhen using self.deferred_assert_*() methods in your tests, "
"remember to call self.process_deferred_asserts() afterwards. "
"Now calling in tearDown()...\nFailures Detected:"
)
if not has_exception:
try:
self.process_deferred_asserts()
except Exception as e:
deferred_exception = e
else:
self.process_deferred_asserts(print_only=True)
if self.is_pytest:
# pytest-specific code
test_id = self.__get_test_id()
if with_selenium:
# Save a screenshot if logging is on when an exception occurs
if has_exception:
self.__add_pytest_html_extra()
sb_config._has_exception = True
if (
self.with_testing_base
and not has_exception
and self.save_screenshot_after_test
):
test_logpath = os.path.join(self.log_path, test_id)
self.__create_log_path_as_needed(test_logpath)
if not self.__last_page_screenshot_png:
self.__set_last_page_screenshot()
self.__set_last_page_url()
self.__set_last_page_source()
log_helper.log_screenshot(
test_logpath,
self.driver,
self.__last_page_screenshot_png,
)
self.__add_pytest_html_extra()
if self.with_testing_base and has_exception:
test_logpath = os.path.join(self.log_path, test_id)
self.__create_log_path_as_needed(test_logpath)
if (
not self.with_screen_shots
and not self.with_basic_test_info
and not self.with_page_source
):
# Log everything if nothing specified (if testing_base)
if not self.__last_page_screenshot_png:
self.__set_last_page_screenshot()
self.__set_last_page_url()
self.__set_last_page_source()
log_helper.log_screenshot(
test_logpath,
self.driver,
self.__last_page_screenshot_png,
)
log_helper.log_test_failure_data(
self,
test_logpath,
self.driver,
self.browser,
self.__last_page_url,
)
log_helper.log_page_source(
test_logpath, self.driver, self.__last_page_source
)
else:
if self.with_screen_shots:
if not self.__last_page_screenshot_png:
self.__set_last_page_screenshot()
self.__set_last_page_url()
self.__set_last_page_source()
log_helper.log_screenshot(
test_logpath,
self.driver,
self.__last_page_screenshot_png,
)
if self.with_basic_test_info:
log_helper.log_test_failure_data(
self,
test_logpath,
self.driver,
self.browser,
self.__last_page_url,
)
if self.with_page_source:
log_helper.log_page_source(
test_logpath,
self.driver,
self.__last_page_source,
)
if self.dashboard:
if self._multithreaded:
with self.dash_lock:
self.__process_dashboard(has_exception)
else:
self.__process_dashboard(has_exception)
# (Pytest) Finally close all open browser windows
self.__quit_all_drivers()
if self.headless or self.xvfb:
if self.headless_active:
try:
self.display.stop()
except AttributeError:
pass
except Exception:
pass
self.display = None
if self.with_db_reporting:
if has_exception:
self.__insert_test_result(constants.State.FAILED, True)
else:
test_id = self.__get_test_id_2()
if test_id in sb_config._results.keys() and (
sb_config._results[test_id] == "Skipped"
):
self.__insert_test_result(
constants.State.SKIPPED, False
)
else:
self.__insert_test_result(
constants.State.PASSED, False
)
runtime = int(time.time() * 1000) - self.execution_start_time
self.testcase_manager.update_execution_data(
self.execution_guid, runtime
)
if self.with_s3_logging and has_exception:
""" If enabled, upload logs to S3 during test exceptions. """
import uuid
from seleniumbase.core.s3_manager import S3LoggingBucket
s3_bucket = S3LoggingBucket()
guid = str(uuid.uuid4().hex)
path = "%s/%s" % (self.log_path, test_id)
uploaded_files = []
for logfile in os.listdir(path):
logfile_name = "%s/%s/%s" % (
guid,
test_id,
logfile.split(path)[-1],
)
s3_bucket.upload_file(
logfile_name, "%s/%s" % (path, logfile)
)
uploaded_files.append(logfile_name)
s3_bucket.save_uploaded_file_names(uploaded_files)
index_file = s3_bucket.upload_index_file(test_id, guid)
print("\n\n*** Log files uploaded: ***\n%s\n" % index_file)
logging.info(
"\n\n*** Log files uploaded: ***\n%s\n" % index_file
)
if self.with_db_reporting:
from seleniumbase.core.testcase_manager import (
TestcaseDataPayload,
)
from seleniumbase.core.testcase_manager import (
TestcaseManager,
)
self.testcase_manager = TestcaseManager(self.database_env)
data_payload = TestcaseDataPayload()
data_payload.guid = self.testcase_guid
data_payload.logURL = index_file
self.testcase_manager.update_testcase_log_url(data_payload)
else:
# (Nosetests)
if has_exception:
test_id = self.__get_test_id()
test_logpath = os.path.join(self.log_path, test_id)
self.__create_log_path_as_needed(test_logpath)
log_helper.log_test_failure_data(
self,
test_logpath,
self.driver,
self.browser,
self.__last_page_url,
)
if len(self._drivers_list) > 0:
if not self.__last_page_screenshot_png:
self.__set_last_page_screenshot()
self.__set_last_page_url()
self.__set_last_page_source()
log_helper.log_screenshot(
test_logpath,
self.driver,
self.__last_page_screenshot_png,
)
log_helper.log_page_source(
test_logpath, self.driver, self.__last_page_source
)
elif self.save_screenshot_after_test:
test_id = self.__get_test_id()
test_logpath = os.path.join(self.log_path, test_id)
self.__create_log_path_as_needed(test_logpath)
if not self.__last_page_screenshot_png:
self.__set_last_page_screenshot()
self.__set_last_page_url()
self.__set_last_page_source()
log_helper.log_screenshot(
test_logpath, self.driver, self.__last_page_screenshot_png
)
if self.report_on:
self._last_page_screenshot = self.__last_page_screenshot_png
try:
self._last_page_url = self.get_current_url()
except Exception:
self._last_page_url = "(Error: Unknown URL)"
# (Nosetests) Finally close all open browser windows
self.__quit_all_drivers()
# Resume tearDown() for both Pytest and Nosetests
if has_exception and self.__visual_baseline_copies:
self.__process_visual_baseline_logs()
if deferred_exception:
# User forgot to call "self.process_deferred_asserts()" in test
raise deferred_exception
| []
| []
| [
"PYTEST_CURRENT_TEST"
]
| [] | ["PYTEST_CURRENT_TEST"] | python | 1 | 0 | |
salt/modules/pip.py | # -*- coding: utf-8 -*-
r'''
Install Python packages with pip to either the system or a virtualenv
Windows Support
===============
.. versionadded:: 2014.7.4
Salt now uses a portable python. As a result the entire pip module is now
functional on the salt installation itself. You can pip install dependencies
for your custom modules. You can even upgrade salt itself using pip. For this
to work properly, you must specify the Current Working Directory (``cwd``) and
the Pip Binary (``bin_env``) salt should use. The variable ``pip_bin`` can be
either a virtualenv path or the path to the pip binary itself.
For example, the following command will list all software installed using pip
to your current salt environment:
.. code-block:: bat
salt <minion> pip.list cwd='C:\salt\bin\Scripts' bin_env='C:\salt\bin\Scripts\pip.exe'
Specifying the ``cwd`` and ``bin_env`` options ensures you're modifying the
salt environment. If these are omitted, it will default to the local
installation of python. If python is not installed locally it will fail saying
it couldn't find pip.
State File Support
------------------
This functionality works in states as well. If you need to pip install colorama
with a state, for example, the following will work:
.. code-block:: yaml
install_colorama:
pip.installed:
- name: colorama
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- upgrade: True
Upgrading Salt using Pip
------------------------
You can now update salt using pip to any version from the 2014.7 branch
forward. Previous version require recompiling some of the dependencies which is
painful in windows.
To do this you just use pip with git to update to the version you want and then
restart the service. Here is a sample state file that upgrades salt to the head
of the 2015.5 branch:
.. code-block:: yaml
install_salt:
pip.installed:
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- editable: git+https://github.com/saltstack/[email protected]#egg=salt
- upgrade: True
restart_service:
service.running:
- name: salt-minion
- enable: True
- watch:
- pip: install_salt
.. note::
If you're having problems, you might try doubling the back slashes. For
example, cwd: 'C:\\salt\\bin\\scripts'. Sometimes python thinks the single
back slash is an escape character.
'''
from __future__ import absolute_import
# Import python libs
import os
import re
import shutil
import logging
# Import salt libs
import salt.utils
import tempfile
import salt.utils.locales
import salt.utils.url
from salt.ext.six import string_types
from salt.exceptions import CommandExecutionError, CommandNotFoundError
logger = logging.getLogger(__name__) # pylint: disable=C0103
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list'
}
VALID_PROTOS = ['http', 'https', 'ftp', 'file']
rex_pip_chain_read = re.compile(r'-r\s(.*)\n?', re.MULTILINE)
def __virtual__():
'''
There is no way to verify that pip is installed without inspecting the
entire filesystem. If it's not installed in a conventional location, the
user is required to provide the location of pip each time it is used.
'''
return 'pip'
def _get_pip_bin(bin_env):
'''
Locate the pip binary, either from `bin_env` as a virtualenv, as the
executable itself, or from searching conventional filesystem locations
'''
if not bin_env:
which_result = __salt__['cmd.which_bin'](['pip2', 'pip', 'pip-python'])
if which_result is None:
raise CommandNotFoundError('Could not find a `pip` binary')
if salt.utils.is_windows():
return which_result.encode('string-escape')
return which_result
# try to get pip bin from virtualenv, bin_env
if os.path.isdir(bin_env):
if salt.utils.is_windows():
pip_bin = os.path.join(
bin_env, 'Scripts', 'pip.exe').encode('string-escape')
else:
pip_bin = os.path.join(bin_env, 'bin', 'pip')
if os.path.isfile(pip_bin):
return pip_bin
msg = 'Could not find a `pip` binary in virtualenv {0}'.format(bin_env)
raise CommandNotFoundError(msg)
# bin_env is the pip binary
elif os.access(bin_env, os.X_OK):
if os.path.isfile(bin_env) or os.path.islink(bin_env):
return bin_env
else:
raise CommandNotFoundError('Could not find a `pip` binary')
def _get_cached_requirements(requirements, saltenv):
'''
Get the location of a cached requirements file; caching if necessary.
'''
req_file, senv = salt.utils.url.parse(requirements)
if senv:
saltenv = senv
if req_file not in __salt__['cp.list_master'](saltenv):
# Requirements file does not exist in the given saltenv.
return False
cached_requirements = __salt__['cp.is_cached'](
requirements, saltenv
)
if not cached_requirements:
# It's not cached, let's cache it.
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
# Check if the master version has changed.
if __salt__['cp.hash_file'](requirements, saltenv) != \
__salt__['cp.hash_file'](cached_requirements, saltenv):
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
return cached_requirements
def _get_env_activate(bin_env):
'''
Return the path to the activate binary
'''
if not bin_env:
raise CommandNotFoundError('Could not find a `activate` binary')
if os.path.isdir(bin_env):
if salt.utils.is_windows():
activate_bin = os.path.join(bin_env, 'Scripts', 'activate.bat')
else:
activate_bin = os.path.join(bin_env, 'bin', 'activate')
if os.path.isfile(activate_bin):
return activate_bin
raise CommandNotFoundError('Could not find a `activate` binary')
def _find_req(link):
logger.info('_find_req -- link = %s', str(link))
with salt.utils.fopen(link) as fh_link:
child_links = rex_pip_chain_read.findall(fh_link.read())
base_path = os.path.dirname(link)
child_links = [os.path.join(base_path, d) for d in child_links]
return child_links
def _resolve_requirements_chain(requirements):
'''
Return an array of requirements file paths that can be used to complete
the no_chown==False && user != None conundrum
'''
chain = []
if isinstance(requirements, string_types):
requirements = [requirements]
for req_file in requirements:
chain.append(req_file)
chain.extend(_resolve_requirements_chain(_find_req(req_file)))
return chain
def _process_requirements(requirements, cmd, cwd, saltenv, user):
'''
Process the requirements argument
'''
cleanup_requirements = []
if requirements is not None:
if isinstance(requirements, string_types):
requirements = [r.strip() for r in requirements.split(',')]
elif not isinstance(requirements, list):
raise TypeError('requirements must be a string or list')
treq = None
for requirement in requirements:
logger.debug('TREQ IS: %s', str(treq))
if requirement.startswith('salt://'):
cached_requirements = _get_cached_requirements(
requirement, saltenv
)
if not cached_requirements:
ret = {'result': False,
'comment': 'pip requirements file \'{0}\' not found'
.format(requirement)}
return None, ret
requirement = cached_requirements
if user:
# Need to make a temporary copy since the user will, most
# likely, not have the right permissions to read the file
if not treq:
treq = tempfile.mkdtemp()
__salt__['file.chown'](treq, user, None)
current_directory = None
if not current_directory:
current_directory = os.path.abspath(os.curdir)
logger.info('_process_requirements from directory,' +
'%s -- requirement: %s', cwd, requirement
)
if cwd is None:
r = requirement
c = cwd
requirement_abspath = os.path.abspath(requirement)
cwd = os.path.dirname(requirement_abspath)
requirement = os.path.basename(requirement)
logger.debug('\n\tcwd: %s -> %s\n\trequirement: %s -> %s\n',
c, cwd, r, requirement
)
os.chdir(cwd)
reqs = _resolve_requirements_chain(requirement)
os.chdir(current_directory)
logger.info('request files: {0}'.format(str(reqs)))
for req_file in reqs:
req_filename = os.path.basename(req_file)
logger.debug('TREQ N CWD: %s -- %s -- for %s', str(treq), str(cwd), str(req_filename))
source_path = os.path.join(cwd, req_filename)
target_path = os.path.join(treq, req_filename)
logger.debug('S: %s', source_path)
logger.debug('T: %s', target_path)
target_base = os.path.dirname(target_path)
if not os.path.exists(target_base):
os.makedirs(target_base, mode=0o755)
__salt__['file.chown'](target_base, user, None)
if not os.path.exists(target_path):
logger.debug(
'Copying %s to %s', source_path, target_path
)
__salt__['file.copy'](source_path, target_path)
logger.debug(
'Changing ownership of requirements file \'{0}\' to '
'user \'{1}\''.format(target_path, user)
)
__salt__['file.chown'](target_path, user, None)
req_args = os.path.join(treq, requirement) if treq else requirement
cmd.extend(['--requirement', req_args])
cleanup_requirements.append(treq)
logger.debug('CLEANUP_REQUIREMENTS: %s', str(cleanup_requirements))
return cleanup_requirements, None
def install(pkgs=None, # pylint: disable=R0912,R0913,R0914
requirements=None,
env=None,
bin_env=None,
use_wheel=False,
no_use_wheel=False,
log=None,
proxy=None,
timeout=None,
editable=None,
find_links=None,
index_url=None,
extra_index_url=None,
no_index=False,
mirrors=None,
build=None,
target=None,
download=None,
download_cache=None,
source=None,
upgrade=False,
force_reinstall=False,
ignore_installed=False,
exists_action=None,
no_deps=False,
no_install=False,
no_download=False,
global_options=None,
install_options=None,
user=None,
no_chown=False,
cwd=None,
activate=False,
pre_releases=False,
cert=None,
allow_all_external=False,
allow_external=None,
allow_unverified=None,
process_dependency_links=False,
__env__=None,
saltenv='base',
env_vars=None,
use_vt=False,
trusted_host=None,
no_cache_dir=False):
'''
Install packages with pip
Install packages individually or from a pip requirements file. Install
packages globally or to a virtualenv.
pkgs
Comma separated list of packages to install
requirements
Path to requirements
bin_env
Path to pip bin or path to virtualenv. If doing a system install,
and want to use a specific pip bin (pip-2.7, pip-2.6, etc..) just
specify the pip bin you want.
.. note::
If installing into a virtualenv, just use the path to the
virtualenv (e.g. ``/home/code/path/to/virtualenv/``)
env
Deprecated, use bin_env now
use_wheel
Prefer wheel archives (requires pip>=1.4)
no_use_wheel
Force to not use wheel archives (requires pip>=1.4)
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the form ``user:[email protected]:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``[email protected]:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
editable
install something editable (e.g.
``git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed``)
find_links
URL to search for packages
index_url
Base URL of Python Package Index
extra_index_url
Extra URLs of package indexes to use in addition to ``index_url``
no_index
Ignore package index
mirrors
Specific mirror URL(s) to query (automatically adds --use-mirrors)
build
Unpack packages into ``build`` dir
target
Install packages into ``target`` dir
download
Download packages into ``download`` instead of installing them
download_cache
Cache downloaded packages in ``download_cache`` dir
source
Check out ``editable`` packages into ``source`` dir
upgrade
Upgrade all packages to the newest available version
force_reinstall
When upgrading, reinstall all packages even if they are already
up-to-date.
ignore_installed
Ignore the installed packages (reinstalling instead)
exists_action
Default action when a path already exists: (s)witch, (i)gnore, (w)ipe,
(b)ackup
no_deps
Ignore package dependencies
no_install
Download and unpack all packages, but don't actually install them
no_download
Don't download any packages, just install the ones already downloaded
(completes an install run with ``--no-install``)
install_options
Extra arguments to be supplied to the setup.py install command (e.g.
like ``--install-option='--install-scripts=/usr/local/bin'``). Use
multiple --install-option options to pass multiple options to setup.py
install. If you are using an option with a directory path, be sure to
use absolute path.
global_options
Extra global options to be supplied to the setup.py call before the
install command.
user
The user under which to run pip
no_chown
When user is given, do not attempt to copy and chown a requirements
file
cwd
Current working directory to run pip from
activate
Activates the virtual environment, if given via bin_env, before running
install.
.. deprecated:: 2014.7.2
If `bin_env` is given, pip will already be sourced from that
virtualenv, making `activate` effectively a noop.
pre_releases
Include pre-releases in the available versions
cert
Provide a path to an alternate CA bundle
allow_all_external
Allow the installation of all externally hosted files
allow_external
Allow the installation of externally hosted files (comma separated
list)
allow_unverified
Allow the installation of insecure and unverifiable files (comma
separated list)
process_dependency_links
Enable the processing of dependency links
env_vars
Set environment variables that some builds will depend on. For example,
a Python C-module may have a Makefile that needs INCLUDE_PATH set to
pick up a header file while compiling. This must be in the form of a
dictionary or a mapping.
Example:
.. code-block:: bash
salt '*' pip.install django_app env_vars="{'CUSTOM_PATH': '/opt/django_app'}"
trusted_host
Mark this host as trusted, even though it does not have valid or any
HTTPS.
use_vt
Use VT terminal emulation (see output while installing)
no_cache_dir
Disable the cache.
CLI Example:
.. code-block:: bash
salt '*' pip.install <package name>,<package2 name>
salt '*' pip.install requirements=/path/to/requirements.txt
salt '*' pip.install <package name> bin_env=/path/to/virtualenv
salt '*' pip.install <package name> bin_env=/path/to/pip_bin
Complicated CLI example::
salt '*' pip.install markdown,django \
editable=git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed upgrade=True no_deps=True
'''
# Switching from using `pip_bin` and `env` to just `bin_env`
# cause using an env and a pip bin that's not in the env could
# be problematic.
# Still using the `env` variable, for backwards compatibility's sake
# but going fwd you should specify either a pip bin or an env with
# the `bin_env` argument and we'll take care of the rest.
if env and not bin_env:
salt.utils.warn_until(
'Boron',
'Passing \'env\' to the pip module is deprecated. Use bin_env instead. '
'This functionality will be removed in Salt Boron.'
)
bin_env = env
if activate:
salt.utils.warn_until(
'Boron',
'Passing \'activate\' to the pip module is deprecated. If '
'bin_env refers to a virtualenv, there is no need to activate '
'that virtualenv before using pip to install packages in it.'
)
if isinstance(__env__, string_types):
salt.utils.warn_until(
'Boron',
'Passing a salt environment should be done using \'saltenv\' '
'not \'__env__\'. This functionality will be removed in Salt '
'Boron.'
)
# Backwards compatibility
saltenv = __env__
pip_bin = _get_pip_bin(bin_env)
cmd = [pip_bin, 'install']
cleanup_requirements, error = _process_requirements(
requirements=requirements,
cmd=cmd,
cwd=cwd,
saltenv=saltenv,
user=user
)
if error:
return error
if use_wheel:
min_version = '1.4'
cur_version = __salt__['pip.version'](bin_env)
if not salt.utils.compare_versions(ver1=cur_version, oper='>=',
ver2=min_version):
log.error(
('The --use-wheel option is only supported in pip {0} and '
'newer. The version of pip detected is {1}. This option '
'will be ignored.'.format(min_version, cur_version))
)
else:
cmd.append('--use-wheel')
if no_use_wheel:
min_version = '1.4'
cur_version = __salt__['pip.version'](bin_env)
if not salt.utils.compare_versions(ver1=cur_version, oper='>=',
ver2=min_version):
log.error(
('The --no-use-wheel option is only supported in pip {0} and '
'newer. The version of pip detected is {1}. This option '
'will be ignored.'.format(min_version, cur_version))
)
else:
cmd.append('--no-use-wheel')
if log:
if os.path.isdir(log):
raise IOError(
'\'{0}\' is a directory. Use --log path_to_file'.format(log))
elif not os.access(log, os.W_OK):
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if find_links:
if isinstance(find_links, string_types):
find_links = [l.strip() for l in find_links.split(',')]
for link in find_links:
if not (salt.utils.url.validate(link, VALID_PROTOS) or os.path.exists(link)):
raise CommandExecutionError(
'\'{0}\' is not a valid URL or path'.format(link)
)
cmd.extend(['--find-links', link])
if no_index and (index_url or extra_index_url):
raise CommandExecutionError(
'\'no_index\' and (\'index_url\' or \'extra_index_url\') are '
'mutually exclusive.'
)
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
if no_index:
cmd.append('--no-index')
if mirrors:
if isinstance(mirrors, string_types):
mirrors = [m.strip() for m in mirrors.split(',')]
cmd.append('--use-mirrors')
for mirror in mirrors:
if not mirror.startswith('http://'):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(mirror)
)
cmd.extend(['--mirrors', mirror])
if build:
cmd.extend(['--build', build])
if target:
cmd.extend(['--target', target])
if download:
cmd.extend(['--download', download])
if download_cache:
cmd.extend(['--download-cache', download_cache])
if source:
cmd.extend(['--source', source])
if upgrade:
cmd.append('--upgrade')
if force_reinstall:
cmd.append('--force-reinstall')
if ignore_installed:
cmd.append('--ignore-installed')
if exists_action:
if exists_action.lower() not in ('s', 'i', 'w', 'b'):
raise CommandExecutionError(
'The exists_action pip option only supports the values '
's, i, w, and b. \'{0}\' is not valid.'.format(exists_action)
)
cmd.extend(['--exists-action', exists_action])
if no_deps:
cmd.append('--no-deps')
if no_install:
cmd.append('--no-install')
if no_download:
cmd.append('--no-download')
if no_cache_dir:
cmd.append('--no-cache-dir')
if pre_releases:
# Check the locally installed pip version
pip_version = version(pip_bin)
# From pip v1.4 the --pre flag is available
if salt.utils.compare_versions(ver1=pip_version, oper='>=', ver2='1.4'):
cmd.append('--pre')
if cert:
cmd.extend(['--cert', cert])
if global_options:
if isinstance(global_options, string_types):
global_options = [go.strip() for go in global_options.split(',')]
for opt in global_options:
cmd.extend(['--global-option', opt])
if install_options:
if isinstance(install_options, string_types):
install_options = [io.strip() for io in install_options.split(',')]
for opt in install_options:
cmd.extend(['--install-option', opt])
if pkgs:
if isinstance(pkgs, string_types):
pkgs = [p.strip() for p in pkgs.split(',')]
# It's possible we replaced version-range commas with semicolons so
# they would survive the previous line (in the pip.installed state).
# Put the commas back in while making sure the names are contained in
# quotes, this allows for proper version spec passing salt>=0.17.0
cmd.extend(['{0}'.format(p.replace(';', ',')) for p in pkgs])
if editable:
egg_match = re.compile(r'(?:#|#.*?&)egg=([^&]*)')
if isinstance(editable, string_types):
editable = [e.strip() for e in editable.split(',')]
for entry in editable:
# Is the editable local?
if not (entry == '.' or entry.startswith(('file://', '/'))):
match = egg_match.search(entry)
if not match or not match.group(1):
# Missing #egg=theEggName
raise CommandExecutionError(
'You must specify an egg for this editable'
)
cmd.extend(['--editable', entry])
if allow_all_external:
cmd.append('--allow-all-external')
if allow_external:
if isinstance(allow_external, string_types):
allow_external = [p.strip() for p in allow_external.split(',')]
for pkg in allow_external:
cmd.extend(['--allow-external', pkg])
if allow_unverified:
if isinstance(allow_unverified, string_types):
allow_unverified = \
[p.strip() for p in allow_unverified.split(',')]
for pkg in allow_unverified:
cmd.extend(['--allow-unverified', pkg])
if process_dependency_links:
cmd.append('--process-dependency-links')
if env_vars:
if isinstance(env_vars, dict):
os.environ.update(env_vars)
else:
raise CommandExecutionError(
'env_vars {0} is not a dictionary'.format(env_vars))
if trusted_host:
cmd.extend(['--trusted-host', trusted_host])
try:
cmd_kwargs = dict(saltenv=saltenv, use_vt=use_vt, runas=user)
if cwd:
cmd_kwargs['cwd'] = cwd
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
logger.debug(
'TRY BLOCK: end of pip.install -- cmd: %s, cmd_kwargs: %s',
str(cmd), str(cmd_kwargs)
)
return __salt__['cmd.run_all'](cmd,
python_shell=False,
**cmd_kwargs)
finally:
for tempdir in [cr for cr in cleanup_requirements if cr is not None]:
if os.path.isdir(tempdir):
shutil.rmtree(tempdir)
def uninstall(pkgs=None,
requirements=None,
bin_env=None,
log=None,
proxy=None,
timeout=None,
user=None,
no_chown=False,
cwd=None,
__env__=None,
saltenv='base',
use_vt=False):
'''
Uninstall packages with pip
Uninstall packages individually or from a pip requirements file. Uninstall
packages globally or from a virtualenv.
pkgs
comma separated list of packages to install
requirements
path to requirements.
bin_env
path to pip bin or path to virtualenv. If doing an uninstall from
the system python and want to use a specific pip bin (pip-2.7,
pip-2.6, etc..) just specify the pip bin you want.
If uninstalling from a virtualenv, just use the path to the virtualenv
(/home/code/path/to/virtualenv/)
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the form
user:[email protected]:port. Note that the
user:password@ is optional and required only if you
are behind an authenticated proxy. If you provide
[email protected]:port then you will be prompted for a
password.
timeout
Set the socket timeout (default 15 seconds)
user
The user under which to run pip
no_chown
When user is given, do not attempt to copy and chown
a requirements file (needed if the requirements file refers to other
files via relative paths, as the copy-and-chown procedure does not
account for such files)
cwd
Current working directory to run pip from
use_vt
Use VT terminal emulation (see output while installing)
CLI Example:
.. code-block:: bash
salt '*' pip.uninstall <package name>,<package2 name>
salt '*' pip.uninstall requirements=/path/to/requirements.txt
salt '*' pip.uninstall <package name> bin_env=/path/to/virtualenv
salt '*' pip.uninstall <package name> bin_env=/path/to/pip_bin
'''
pip_bin = _get_pip_bin(bin_env)
cmd = [pip_bin, 'uninstall', '-y']
if isinstance(__env__, string_types):
salt.utils.warn_until(
'Boron',
'Passing a salt environment should be done using \'saltenv\' '
'not \'__env__\'. This functionality will be removed in Salt '
'Boron.'
)
# Backwards compatibility
saltenv = __env__
cleanup_requirements, error = _process_requirements(
requirements=requirements, cmd=cmd, saltenv=saltenv, user=user,
cwd=cwd
)
if error:
return error
if log:
try:
# TODO make this check if writeable
os.path.exists(log)
except IOError:
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if pkgs:
if isinstance(pkgs, string_types):
pkgs = [p.strip() for p in pkgs.split(',')]
if requirements:
for requirement in requirements:
with salt.utils.fopen(requirement) as rq_:
for req in rq_:
try:
req_pkg, _ = req.split('==')
if req_pkg in pkgs:
pkgs.remove(req_pkg)
except ValueError:
pass
cmd.extend(pkgs)
cmd_kwargs = dict(python_shell=False, runas=user,
cwd=cwd, saltenv=saltenv, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
try:
return __salt__['cmd.run_all'](cmd, **cmd_kwargs)
finally:
for requirement in cleanup_requirements:
if requirement:
try:
os.remove(requirement)
except OSError:
pass
def freeze(bin_env=None,
user=None,
cwd=None,
use_vt=False):
'''
Return a list of installed packages either globally or in the specified
virtualenv
bin_env
path to pip bin or path to virtualenv. If doing an uninstall from
the system python and want to use a specific pip bin (pip-2.7,
pip-2.6, etc..) just specify the pip bin you want.
If uninstalling from a virtualenv, just use the path to the virtualenv
(/home/code/path/to/virtualenv/)
user
The user under which to run pip
cwd
Current working directory to run pip from
CLI Example:
.. code-block:: bash
salt '*' pip.freeze /home/code/path/to/virtualenv/
'''
pip_bin = _get_pip_bin(bin_env)
cmd = [pip_bin, 'freeze']
cmd_kwargs = dict(runas=user, cwd=cwd, use_vt=use_vt, python_shell=False)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode'] > 0:
raise CommandExecutionError(result['stderr'])
return result['stdout'].splitlines()
def list_(prefix=None,
bin_env=None,
user=None,
cwd=None):
'''
Filter list of installed apps from ``freeze`` and check to see if
``prefix`` exists in the list of packages installed.
CLI Example:
.. code-block:: bash
salt '*' pip.list salt
'''
packages = {}
pip_bin = _get_pip_bin(bin_env)
cmd = [pip_bin, 'freeze']
cmd_kwargs = dict(runas=user, cwd=cwd, python_shell=False)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
if not prefix or prefix in ('p', 'pi', 'pip'):
packages['pip'] = version(bin_env)
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode'] > 0:
raise CommandExecutionError(result['stderr'])
for line in result['stdout'].splitlines():
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
version_, name = line.split('#egg=')
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'{0}\''.format(line))
continue
if prefix:
if name.lower().startswith(prefix.lower()):
packages[name] = version_
else:
packages[name] = version_
return packages
def version(bin_env=None):
'''
.. versionadded:: 0.17.0
Returns the version of pip. Use ``bin_env`` to specify the path to a
virtualenv and get the version of pip in that virtualenv.
If unable to detect the pip version, returns ``None``.
CLI Example:
.. code-block:: bash
salt '*' pip.version
'''
pip_bin = _get_pip_bin(bin_env)
output = __salt__['cmd.run'](
'{0} --version'.format(pip_bin), python_shell=False)
try:
return re.match(r'^pip (\S+)', output).group(1)
except AttributeError:
return None
def list_upgrades(bin_env=None,
user=None,
cwd=None):
'''
Check whether or not an upgrade is available for all packages
CLI Example:
.. code-block:: bash
salt '*' pip.list_upgrades
'''
pip_bin = _get_pip_bin(bin_env)
cmd = [pip_bin, 'list', '--outdated']
cmd_kwargs = dict(cwd=cwd, runas=user)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode'] > 0:
logger.error(result['stderr'])
raise CommandExecutionError(result['stderr'])
packages = {}
for line in result['stdout'].splitlines():
match = re.search(r'(\S*)\s+\(.*Latest:\s+(.*)\)', line)
if match:
name, version_ = match.groups()
else:
logger.error('Can\'t parse line \'{0}\''.format(line))
continue
packages[name] = version_
return packages
def upgrade_available(pkg,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2015.5.0
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade_available <package name>
'''
return pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd)
def upgrade(bin_env=None,
user=None,
cwd=None,
use_vt=False):
'''
.. versionadded:: 2015.5.0
Upgrades outdated pip packages
Returns a dict containing the changes.
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
pip_bin = _get_pip_bin(bin_env)
old = list_(bin_env=bin_env, user=user, cwd=cwd)
cmd = [pip_bin, 'install', '-U']
cmd_kwargs = dict(cwd=cwd, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
errors = False
for pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd):
result = __salt__['cmd.run_all'](cmd + [pkg], **cmd_kwargs)
if result['retcode'] != 0:
errors = True
if 'stderr' in result:
ret['comment'] += result['stderr']
if errors:
ret['result'] = False
new = list_(bin_env=bin_env, user=user, cwd=cwd)
ret['changes'] = salt.utils.compare_dicts(old, new)
return ret
| []
| []
| []
| [] | [] | python | 0 | 0 | |
algo/thread/thread_return_value.py | # https://stackoverflow.com/questions/6893968/how-to-get-the-return-value-from-a-thread-in-python
from threading import Thread
def foo(bar):
print ('hello {0}'.format(bar))
return "foo"
class ThreadWithReturnValue(Thread):
def __init__(self, group=None, target=None, name=None,
args=(), kwargs={}):
Thread.__init__(self, group, target, name, args, kwargs)
self._return = None
def run(self):
self._return = "foo from thread when it runs!"
def join(self):
Thread.join(self)
return self._return
twrv = ThreadWithReturnValue(target=foo, args=('world!',))
twrv.start()
print (twrv.join()) # prints foo | []
| []
| []
| [] | [] | python | null | null | null |
tests/aws/test_redshift.py | # Dmitry Kisler © 2020-present
# www.dkisler.com
# pylint: disable=missing-function-docstring
import os
import sys
import inspect
import warnings
import logging
from cloud_connectors.aws import redshift as module
logging.basicConfig(level=logging.ERROR, format="[line: %(lineno)s] %(message)s")
LOGGER = logging.getLogger(__name__)
warnings.simplefilter(action="ignore", category=FutureWarning)
CLASSES = {"Client"}
CLASS_METHODS = {
"SCHEMA",
"CONF_DEFAULT",
"RESULT_TUPLE",
"query_fetch",
"query_cud",
"commit",
"rollback",
"close",
}
def test_module_miss_classes() -> None:
missing = CLASSES.difference(set(module.__dir__()))
if missing:
LOGGER.error(f"""Class(es) '{"', '".join(missing)}' is(are) missing.""")
sys.exit(1)
def test_class_client_miss_methods() -> None:
model_members = inspect.getmembers(module.Client)
missing = CLASS_METHODS.difference({i[0] for i in model_members})
if missing:
LOGGER.error(f"""Class 'Client' Method(s) '{"', '".join(missing)}' is(are) missing.""")
sys.exit(1)
def test_validator() -> None:
tests = [
{
"type": "faulty_validation",
"config": {
"host": "localhost",
"dbname": "postgres",
"port": 5432,
"password": "postgres",
},
},
{
"type": "faulty_connection",
"config": {
"host": "localhost",
"dbname": "postgres",
"port": 1,
"user": "postgres",
"password": "postgres",
},
},
]
for test in tests:
try:
_ = module.Client(test["config"])
except Exception as ex:
if test["type"] == "faulty_validation":
if type(ex).__name__ != "ConfigurationError":
LOGGER.error("Wrong error type to handle config error")
sys.exit(1)
if "['dbname', 'user', 'password']" not in str(ex):
LOGGER.error(f"Configuration validator error - user: {ex}")
sys.exit(1)
elif test["type"] == "faulty_connection":
if type(ex).__name__ != "DatabaseConnectionError":
LOGGER.error("Wrong error type to handle connection error")
sys.exit(1)
# db instance required
config = {
"host": "localhost",
"dbname": "postgres",
"port": int(os.getenv("DB_PORT_TEST", "11111")),
"user": "postgres",
"password": "postgres",
}
skip = False
try:
client = module.Client(config)
except Exception as ex:
if type(ex).__name__ == "DatabaseConnectionError":
skip = True
def test_select() -> None:
if not skip:
client = module.Client(config, autocommit=False)
result = client.query_fetch("SELECT 100 AS a;")
client.commit()
if (result.col_names, result.values) != (["a"], [(100,)]):
LOGGER.error("Faulty select query runner")
sys.exit(1)
try:
_ = client.query_fetch("SELECT * FROM foo_bar;")
except Exception as ex:
if type(ex).__name__ != "DatabaseError":
LOGGER.error("Wrong error type to handle database error")
sys.exit(1)
client.close()
def test_create() -> None:
if not skip:
client = module.Client(config)
client.query_cud("CREATE TABLE IF NOT EXISTS test (a int);")
client.query_cud("INSERT INTO test VALUES (100);")
result = client.query_fetch("SELECT * FROM test;")
if (result.col_names, result.values) != (["a"], [(100,)]):
LOGGER.error("Faulty select query runner")
sys.exit(1)
client.query_cud("DROP TABLE test;")
try:
client.query_cud("DROP TABLE test;")
except Exception as ex:
if type(ex).__name__ != "DatabaseError":
LOGGER.error("Wrong error type to handle database error")
sys.exit(1)
client = module.Client(config, autocommit=False)
client.query_cud("CREATE TABLE IF NOT EXISTS test (a int);")
client.query_cud("INSERT INTO test VALUES (100);")
client.rollback()
try:
result = client.query_fetch("SELECT * FROM test;")
except Exception as ex:
if type(ex).__name__ != "DatabaseError":
LOGGER.error("Rollback error")
sys.exit(1) | []
| []
| [
"DB_PORT_TEST"
]
| [] | ["DB_PORT_TEST"] | python | 1 | 0 | |
microservices/ga/datamgr/templateApp.go | {{define "templateApp.go"}}
{{.PavedroadInfo}}
// User project / copyright / usage information
// {{.ProjectInfo}}
package main
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"github.com/gorilla/mux"
_ "github.com/lib/pq"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"time"
)
// Initialize setups database connection object and the http server
//
func (a *{{.NameExported}}App) Initialize() {
// Override defaults
a.initializeEnvironment()
// Build connection strings
connectionString := fmt.Sprintf("user=%s password=%s dbname=%s sslmode=%s host=%s port=%s",
dbconf.username,
dbconf.password,
dbconf.database,
dbconf.sslMode,
dbconf.ip,
dbconf.port)
httpconf.listenString = fmt.Sprintf("%s:%s", httpconf.ip, httpconf.port)
var err error
a.DB, err = sql.Open(dbconf.dbDriver, connectionString)
if err != nil {
log.Fatal(err)
}
a.Router = mux.NewRouter()
a.initializeRoutes()
}
// Start the server
func (a *{{.NameExported}}App) Run(addr string) {
log.Println("Listing at: " + addr)
srv := &http.Server{
Handler: a.Router,
Addr: addr,
WriteTimeout: httpconf.writeTimeout * time.Second,
ReadTimeout: httpconf.readTimeout * time.Second,
}
go func() {
if err := srv.ListenAndServe(); err != nil {
log.Println(err)
}
}()
// Listen for SIGHUP
c := make(chan os.Signal, 1)
<-c
// Create a deadline to wait for.
ctx, cancel := context.WithTimeout(context.Background(), httpconf.shutdownTimeout)
defer cancel()
// Doesn't block if no connections, but will otherwise wait
// until the timeout deadline.
srv.Shutdown(ctx)
log.Println("shutting down")
os.Exit(0)
}
// Get for ennvironment variable overrides
func (a *{{.NameExported}}App) initializeEnvironment() {
var envVar = ""
//look for environment variables overrides
envVar = os.Getenv("APP_DB_USERNAME")
if envVar != "" {
dbconf.username = envVar
}
envVar = os.Getenv("APP_DB_PASSWORD")
if envVar != "" {
dbconf.password = envVar
}
envVar = os.Getenv("APP_DB_NAME")
if envVar != "" {
dbconf.database = envVar
}
envVar = os.Getenv("APP_DB_SSL_MODE")
if envVar != "" {
dbconf.sslMode = envVar
}
envVar = os.Getenv("APP_DB_SQL_DRIVER")
if envVar != "" {
dbconf.dbDriver = envVar
}
envVar = os.Getenv("APP_DB_IP")
if envVar != "" {
dbconf.ip = envVar
}
envVar = os.Getenv("APP_DB_PORT")
if envVar != "" {
dbconf.port = envVar
}
envVar = os.Getenv("HTTP_IP_ADDR")
if envVar != "" {
httpconf.ip = envVar
}
envVar = os.Getenv("HTTP_IP_PORT")
if envVar != "" {
httpconf.port = envVar
}
envVar = os.Getenv("HTTP_READ_TIMEOUT")
if envVar != "" {
to, err := strconv.Atoi(envVar)
if err == nil {
log.Printf("failed to convert HTTP_READ_TIMEOUT: %s to int", envVar)
} else {
httpconf.readTimeout = time.Duration(to) * time.Second
}
log.Printf("Read timeout: %d", httpconf.readTimeout)
}
envVar = os.Getenv("HTTP_WRITE_TIMEOUT")
if envVar != "" {
to, err := strconv.Atoi(envVar)
if err == nil {
log.Printf("failed to convert HTTP_READ_TIMEOUT: %s to int", envVar)
} else {
httpconf.writeTimeout = time.Duration(to) * time.Second
}
log.Printf("Write timeout: %d", httpconf.writeTimeout)
}
envVar = os.Getenv("HTTP_SHUTDOWN_TIMEOUT")
if envVar != "" {
if envVar != "" {
to, err := strconv.Atoi(envVar)
if err != nil {
httpconf.shutdownTimeout = time.Second * time.Duration(to)
} else {
httpconf.shutdownTimeout = time.Second * httpconf.shutdownTimeout
}
log.Println("Shutdown timeout", httpconf.shutdownTimeout)
}
}
envVar = os.Getenv("HTTP_LOG")
if envVar != "" {
httpconf.logPath = envVar
}
}
{{.AllRoutesSwaggerDoc}}
func (a *{{.NameExported}}App) initializeRoutes() {
uri := {{.NameExported}}APIVersion + "/" + {{.NameExported}}NamespaceID + "/{namespace}/" +
{{.NameExported}}ResourceType + "LIST"
a.Router.HandleFunc(uri, a.list{{.NameExported}}).Methods("GET")
uri = {{.NameExported}}APIVersion + "/" + {{.NameExported}}NamespaceID + "/{namespace}/" +
{{.NameExported}}ResourceType + "/{key}"
a.Router.HandleFunc(uri, a.get{{.NameExported}}).Methods("GET")
uri = {{.NameExported}}APIVersion + "/" + {{.NameExported}}NamespaceID + "/{namespace}/" + {{.NameExported}}ResourceType
a.Router.HandleFunc(uri, a.create{{.NameExported}}).Methods("POST")
uri = {{.NameExported}}APIVersion + "/" + {{.NameExported}}NamespaceID + "/{namespace}/" +
{{.NameExported}}ResourceType + {{.NameExported}}Key
a.Router.HandleFunc(uri, a.update{{.NameExported}}).Methods("PUT")
uri = {{.NameExported}}APIVersion + "/" + {{.NameExported}}NamespaceID + "/{namespace}/" +
{{.NameExported}}ResourceType + {{.NameExported}}Key
a.Router.HandleFunc(uri, a.delete{{.NameExported}}).Methods("DELETE")
}
{{.GetAllSwaggerDoc}}
// list{{.NameExported}} swagger:route GET /api/v1/namespace/pavedroad.io/{{.Name}}LIST {{.Name}} list{{.Name}}
//
// Returns a list of {{.Name}}
//
// Responses:
// default: genericError
// 200: {{.Name}}List
func (a *{{.NameExported}}App) list{{.NameExported}}(w http.ResponseWriter, r *http.Request) {
{{.Name}} := {{.Name}}{}
count, _ := strconv.Atoi(r.FormValue("count"))
start, _ := strconv.Atoi(r.FormValue("start"))
if count > 10 || count < 1 {
count = 10
}
if start < 0 {
start = 0
}
mappings, err := {{.Name}}.list{{.NameExported}}(a.DB, start, count)
if err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
respondWithJSON(w, http.StatusOK, mappings)
}
{{.GetSwaggerDoc}}
// get{{.NameExported}} swagger:route GET /api/v1/namespace/pavedroad.io/{{.Name}}/{uuid} {{.Name}} get{{.Name}}
//
// Returns a {{.Name}} given a key, where key is a UUID
//
// Responses:
// default: genericError
// 200: {{.Name}}Response
func (a *{{.NameExported}}App) get{{.NameExported}}(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
{{.Name}} := {{.Name}}{}
//TODO: allows them to specify the column used to retrieve user
err := {{.Name}}.get{{.NameExported}}(a.DB, vars["key"], UUID)
if err != nil {
errmsg := err.Error()
errno := errmsg[0:3]
if errno == "400" {
respondWithError(w, http.StatusBadRequest, err.Error())
} else {
respondWithError(w, http.StatusNotFound, err.Error())
}
return
}
respondWithJSON(w, http.StatusOK, {{.Name}})
}
{{.PostSwaggerDoc}}
// create{{.NameExported}} swagger:route POST /api/v1/namespace/pavedroad.io/{{.Name}} {{.Name}} create{{.Name}}
//
// Create a new {{.Name}}
//
// Responses:
// default: genericError
// 201: {{.Name}}Response
// 400: genericError
func (a *{{.NameExported}}App) create{{.NameExported}}(w http.ResponseWriter, r *http.Request) {
// New map structure
{{.Name}} := {{.Name}}{}
htmlData, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Println(err)
os.Exit(1)
}
err = json.Unmarshal(htmlData, &{{.Name}})
if err != nil {
log.Println(err)
os.Exit(1)
}
ct := time.Now().UTC()
{{.Name}}.Created = ct
{{.Name}}.Updated = ct
// Save into backend storage
// returns the UUID if needed
if _, err := {{.Name}}.create{{.NameExported}}(a.DB); err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid request payload")
return
}
respondWithJSON(w, http.StatusCreated, {{.Name}})
}
{{.PutSwaggerDoc}}
// update{{.NameExported}} swagger:route PUT /api/v1/namespace/pavedroad.io/{{.Name}}/{key} {{.Name}} update{{.Name}}
//
// Update a {{.Name}} specified by key, where key is a uuid
//
// Responses:
// default: genericError
// 201: {{.Name}}Response
// 400: genericError
func (a *{{.NameExported}}App) update{{.NameExported}}(w http.ResponseWriter, r *http.Request) {
{{.Name}} := {{.Name}}{}
// Read URI variables
// vars := mux.Vars(r)
htmlData, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Println(err)
return
}
err = json.Unmarshal(htmlData, &{{.Name}})
if err != nil {
log.Println(err)
return
}
ct := time.Now().UTC()
{{.Name}}.Updated = ct
if err := {{.Name}}.update{{.NameExported}}(a.DB, {{.Name}}.{{.NameExported}}UUID); err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid request payload")
return
}
respondWithJSON(w, http.StatusOK, {{.Name}})
}
{{.DeleteSwaggerDoc}}
// delete{{.NameExported}} swagger:route DELETE /api/v1/namespace/pavedroad.io/{{.Name}}/{key} {{.Name}} delete{{.Name}}
//
// Update a {{.Name}} specified by key, which is a uuid
//
// Responses:
// default: genericError
// 200: {{.Name}}Response
// 400: genericError
func (a *{{.NameExported}}App) delete{{.NameExported}}(w http.ResponseWriter, r *http.Request) {
{{.Name}} := {{.Name}}{}
vars := mux.Vars(r)
err := {{.Name}}.delete{{.NameExported}}(a.DB, vars["key"])
if err != nil {
respondWithError(w, http.StatusNotFound, err.Error())
return
}
respondWithJSON(w, http.StatusOK, map[string]string{"result": "success"})
}
func respondWithError(w http.ResponseWriter, code int, message string) {
respondWithJSON(w, code, map[string]string{"error": message})
}
func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
response, _ := json.Marshal(payload)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(response)
}
func logRequest(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s %s\n", r.RemoteAddr, r.Method, r.URL)
handler.ServeHTTP(w, r)
})
}
func openLogFile(logfile string) {
if logfile != "" {
lf, err := os.OpenFile(logfile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0640)
if err != nil {
log.Fatal("OpenLogfile: os.OpenFile:", err)
}
log.SetOutput(lf)
}
}
/*
func dump{{.NameExported}}(m {{.NameExported}}) {
fmt.Println("Dump {{.Name}}")
{{.DumpStructs}}
}
*/
{{end}}
| [
"\"APP_DB_USERNAME\"",
"\"APP_DB_PASSWORD\"",
"\"APP_DB_NAME\"",
"\"APP_DB_SSL_MODE\"",
"\"APP_DB_SQL_DRIVER\"",
"\"APP_DB_IP\"",
"\"APP_DB_PORT\"",
"\"HTTP_IP_ADDR\"",
"\"HTTP_IP_PORT\"",
"\"HTTP_READ_TIMEOUT\"",
"\"HTTP_WRITE_TIMEOUT\"",
"\"HTTP_SHUTDOWN_TIMEOUT\"",
"\"HTTP_LOG\""
]
| []
| [
"APP_DB_PORT",
"APP_DB_NAME",
"APP_DB_SSL_MODE",
"APP_DB_IP",
"APP_DB_PASSWORD",
"HTTP_IP_ADDR",
"HTTP_READ_TIMEOUT",
"HTTP_WRITE_TIMEOUT",
"HTTP_IP_PORT",
"HTTP_SHUTDOWN_TIMEOUT",
"HTTP_LOG",
"APP_DB_USERNAME",
"APP_DB_SQL_DRIVER"
]
| [] | ["APP_DB_PORT", "APP_DB_NAME", "APP_DB_SSL_MODE", "APP_DB_IP", "APP_DB_PASSWORD", "HTTP_IP_ADDR", "HTTP_READ_TIMEOUT", "HTTP_WRITE_TIMEOUT", "HTTP_IP_PORT", "HTTP_SHUTDOWN_TIMEOUT", "HTTP_LOG", "APP_DB_USERNAME", "APP_DB_SQL_DRIVER"] | go | 13 | 0 | |
repl/repl.go | // Copyright 2018 The go-python Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Read Eval Print Loop
package repl
import (
"fmt"
"io"
"os"
"os/user"
"path/filepath"
"sort"
"strings"
"github.com/go-python/gpython/compile"
"github.com/go-python/gpython/py"
"github.com/go-python/gpython/vm"
"github.com/peterh/liner"
)
const HistoryFileName = ".gpyhistory"
// homeDirectory finds the home directory or returns ""
func homeDirectory() string {
usr, err := user.Current()
if err == nil {
return usr.HomeDir
}
// Fall back to reading $HOME - work around user.Current() not
// working for cross compiled binaries on OSX.
// https://github.com/golang/go/issues/6376
return os.Getenv("HOME")
}
// Holds state for readline services
type readline struct {
*liner.State
historyFile string
module *py.Module
}
// newReadline creates a new instance of readline
func newReadline(module *py.Module) *readline {
rl := &readline{
State: liner.NewLiner(),
module: module,
}
home := homeDirectory()
if home != "" {
rl.historyFile = filepath.Join(home, HistoryFileName)
}
rl.SetTabCompletionStyle(liner.TabPrints)
rl.SetWordCompleter(rl.Completer)
return rl
}
// readHistory reads the history into the term
func (rl *readline) ReadHistory() error {
f, err := os.Open(rl.historyFile)
if err != nil {
return err
}
defer f.Close()
_, err = rl.State.ReadHistory(f)
if err != nil {
return err
}
return nil
}
// writeHistory writes the history from the term
func (rl *readline) WriteHistory() error {
f, err := os.OpenFile(rl.historyFile, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)
if err != nil {
return err
}
defer f.Close()
_, err = rl.State.WriteHistory(f)
if err != nil {
return err
}
return nil
}
// Close the readline and write history
func (rl *readline) Close() error {
err := rl.State.Close()
if err != nil {
return err
}
if rl.historyFile != "" {
err := rl.WriteHistory()
if err != nil {
return err
}
}
return nil
}
// WordCompleter takes the currently edited line with the cursor
// position and returns the completion candidates for the partial word
// to be completed. If the line is "Hello, wo!!!" and the cursor is
// before the first '!', ("Hello, wo!!!", 9) is passed to the
// completer which may returns ("Hello, ", {"world", "Word"}, "!!!")
// to have "Hello, world!!!".
func (rl *readline) Completer(line string, pos int) (head string, completions []string, tail string) {
head = line[:pos]
tail = line[pos:]
lastSpace := strings.LastIndex(head, " ")
head, partial := line[:lastSpace+1], line[lastSpace+1:]
// log.Printf("head = %q, partial = %q, tail = %q", head, partial, tail)
found := make(map[string]struct{})
match := func(d py.StringDict) {
for k := range d {
if strings.HasPrefix(k, partial) {
if _, ok := found[k]; !ok {
completions = append(completions, k)
found[k] = struct{}{}
}
}
}
}
match(rl.module.Globals)
match(py.Builtins.Globals)
sort.Strings(completions)
return head, completions, tail
}
func Run() {
module := py.NewModule("__main__", "", nil, nil)
rl := newReadline(module)
defer rl.Close()
err := rl.ReadHistory()
if err != nil {
fmt.Printf("Failed to open history: %v\n", err)
}
fmt.Printf("Gpython 3.4.0\n")
prog := "<stdin>"
module.Globals["__file__"] = py.String(prog)
continuation := false
previous := ""
for {
prompt := ">>> "
if continuation {
prompt = "... "
}
line, err := rl.Prompt(prompt)
if err != nil {
if err == io.EOF {
fmt.Printf("\n")
break
}
fmt.Printf("Problem reading line: %v\n", err)
continue
}
if line != "" {
rl.AppendHistory(line)
}
if continuation {
if line != "" {
previous += string(line) + "\n"
continue
}
}
// need +"\n" because "single" expects \n terminated input
toCompile := previous + string(line)
if toCompile == "" {
continue
}
obj, err := compile.Compile(toCompile+"\n", prog, "single", 0, true)
if err != nil {
// Detect that we should start a continuation line
// FIXME detect EOF properly!
errText := err.Error()
if strings.Contains(errText, "unexpected EOF while parsing") || strings.Contains(errText, "EOF while scanning triple-quoted string literal") {
continuation = true
previous += string(line) + "\n"
continue
}
}
continuation = false
previous = ""
if err != nil {
fmt.Printf("Compile error: %v\n", err)
continue
}
code := obj.(*py.Code)
_, err = vm.Run(module.Globals, module.Globals, code, nil)
if err != nil {
py.TracebackDump(err)
}
}
}
| [
"\"HOME\""
]
| []
| [
"HOME"
]
| [] | ["HOME"] | go | 1 | 0 | |
recipe/setup.py | from setuptools import setup, Extension
import os
snack = Extension('_snack',
libraries = ['newt', 'slang'],
sources = ['snack.c'])
setup (name = os.environ['PKG_NAME'],
version = os.environ['PKG_VERSION'],
description = 'Newt is a library for color text mode, widget based user interfaces',
py_modules=['snack'],
url = 'https://github.com/conda-forge/newt-feedstock',
ext_modules = [snack])
| []
| []
| [
"PKG_VERSION",
"PKG_NAME"
]
| [] | ["PKG_VERSION", "PKG_NAME"] | python | 2 | 0 | |
domino-jna-indexer-cqengine/src/test/java/com/mindoo/domino/jna/indexing/cqengine/test/BaseJNATestClass.java | package com.mindoo.domino.jna.indexing.cqengine.test;
import java.util.concurrent.Callable;
import com.mindoo.domino.jna.NotesDatabase;
import com.mindoo.domino.jna.gc.NotesGC;
import com.mindoo.domino.jna.internal.NotesNativeAPI;
import com.mindoo.domino.jna.utils.NotesInitUtils;
import com.sun.jna.Native;
import lotus.domino.Database;
import lotus.domino.NotesException;
import lotus.domino.NotesFactory;
import lotus.domino.NotesThread;
import lotus.domino.Session;
import org.junit.BeforeClass;
import org.junit.AfterClass;
public class BaseJNATestClass {
public static final String DBPATH_FAKENAMES_VIEWS_NSF = "fakenames-views.nsf";
public static final String DBPATH_FAKENAMES_NSF = "fakenames.nsf";
private ThreadLocal<Session> m_threadSession = new ThreadLocal<Session>();
private static boolean m_notesInitExtendedCalled = false;
@BeforeClass
public static void initNotes() {
NotesNativeAPI.initialize();
String notesProgramDir = System.getenv("Notes_ExecDirectory");
String notesIniPath = System.getenv("NotesINI");
if (notesProgramDir!=null && notesProgramDir.length()>0 && notesIniPath!=null && notesIniPath.length()>0) {
NotesInitUtils.notesInitExtended(new String[] {
notesProgramDir,
"="+notesIniPath
});
m_notesInitExtendedCalled = true;
}
NotesThread.sinitThread();
Native.setProtected(true);
}
@AfterClass
public static void termNotes() {
if (m_notesInitExtendedCalled) {
NotesInitUtils.notesTerm();
}
NotesThread.stermThread();
}
public NotesDatabase getFakeNamesDb() throws NotesException {
NotesDatabase db = new NotesDatabase(getSession(), "", DBPATH_FAKENAMES_NSF);
return db;
}
public NotesDatabase getFakeNamesViewsDb() throws NotesException {
NotesDatabase db = new NotesDatabase(getSession(), "", DBPATH_FAKENAMES_VIEWS_NSF);
return db;
}
public Database getFakeNamesDbLegacy() throws NotesException {
Database db = getSession().getDatabase("", DBPATH_FAKENAMES_NSF);
return db;
}
public Database getFakeNamesViewsDbLegacy() throws NotesException {
Database db = getSession().getDatabase("", DBPATH_FAKENAMES_VIEWS_NSF);
return db;
}
public Session getSession() {
return m_threadSession.get();
}
public <T> T runWithSession(final IDominoCallable<T> callable) {
final Session[] session = new Session[1];
try {
session[0] = NotesFactory.createSession();
session[0].setTrackMillisecInJavaDates(true);
m_threadSession.set(session[0]);
T result = NotesGC.runWithAutoGC(new Callable<T>() {
@Override
public T call() throws Exception {
NotesGC.setDebugLoggingEnabled(true);
T result = callable.call(session[0]);
return result;
}
});
return result;
} catch (Throwable e) {
throw new RuntimeException(e);
}
finally {
if (session[0]!=null) {
try {
session[0].recycle();
} catch (NotesException e) {
e.printStackTrace();
}
}
m_threadSession.set(null);
}
}
public static interface IDominoCallable<T> {
public T call(Session session) throws Exception;
}
}
| [
"\"Notes_ExecDirectory\"",
"\"NotesINI\""
]
| []
| [
"NotesINI",
"Notes_ExecDirectory"
]
| [] | ["NotesINI", "Notes_ExecDirectory"] | java | 2 | 0 | |
backend/api/__init__.py | import os, sys
from flask import Flask
from flask import jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_migrate import Migrate
from flask_jwt_extended import JWTManager
import docker
from config import config as Config
basedir = os.path.abspath(os.path.dirname(__file__))
db = SQLAlchemy()
ma = Marshmallow()
migrate = Migrate()
jwt = JWTManager()
def create_app(config):
app = Flask(__name__)
config_name = config
if not isinstance(config, str):
config_name = os.getenv('FLASK_CONFIG', 'default')
app.config.from_object(Config[config_name])
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# not using sqlalchemy event system, hence disabling it
Config[config_name].init_app(app)
# Set up extensions
db.init_app(app)
ma.init_app(app)
migrate.init_app(app, db)
jwt.init_app(app)
# Configure SSL if platform supports it
if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
from flask_sslify import SSLify
SSLify(app)
from .main import main as main_blueprint
from .auth import auth as auth_blueprint
from .templates import templates as templates_blueprint
from .apps import apps as apps_blueprint
app.register_blueprint(main_blueprint, url_prefix='/api')
app.register_blueprint(auth_blueprint, url_prefix='/api/auth')
app.register_blueprint(templates_blueprint, url_prefix='/api/templates')
app.register_blueprint(apps_blueprint, url_prefix="/api/apps")
return app
def register_endpoints(app):
@app.route('/')
def index():
return '<center><a href="http://127.0.0.1:8080/">Vue-Yacht</a></center><iframe src="http://127.0.0.1:8080/" style="display: block; background: #000; border: none; height: 100vh; width: 100vw;"></iframe>' | []
| []
| [
"FLASK_CONFIG"
]
| [] | ["FLASK_CONFIG"] | python | 1 | 0 | |
pkg/filesystem/device_test.go | package filesystem
import (
"os"
"path/filepath"
"runtime"
"testing"
)
func TestDeviceIDsDifferent(t *testing.T) {
// If we're on Windows, the device ID is always 0, so skip this test in that
// case.
if runtime.GOOS == "windows" {
t.Skip()
}
// If we don't have the separate FAT32 partition, skip this test.
fat32Root := os.Getenv("MUTAGEN_TEST_FAT32_ROOT")
if fat32Root == "" {
t.Skip()
}
// Grab the device ID for the current path.
info, err := os.Lstat(".")
if err != nil {
t.Fatal("lstat failed for current path:", err)
}
deviceID, err := DeviceID(info)
if err != nil {
t.Fatal("device ID probe failed for current path:", err)
}
// Grab the device ID for the FAT32 partition.
fat32Info, err := os.Lstat(fat32Root)
if err != nil {
t.Fatal("lstat failed for FAT32 partition:", err)
}
fat32DeviceID, err := DeviceID(fat32Info)
if err != nil {
t.Fatal("device ID probe failed for FAT32 partition:", err)
}
// Ensure they differ.
if deviceID == fat32DeviceID {
t.Error("different partitions show same device ID")
}
}
func TestDeviceIDSubrootDifferent(t *testing.T) {
// If we're on Windows, the device ID is always 0, so skip this test in that
// case.
if runtime.GOOS == "windows" {
t.Skip()
}
// If we don't have the separate FAT32 partition mounted at a subdirectory,
// skip this test.
fat32Subroot := os.Getenv("MUTAGEN_TEST_FAT32_SUBROOT")
if fat32Subroot == "" {
t.Skip()
}
// Compute its parent path.
parent := filepath.Dir(fat32Subroot)
// Grab the device ID for the parent path.
parentInfo, err := os.Lstat(parent)
if err != nil {
t.Fatal("lstat failed for parent path:", err)
}
parentDeviceID, err := DeviceID(parentInfo)
if err != nil {
t.Fatal("device ID probe failed for parent path:", err)
}
// Grab the device ID for the FAT32 partition.
fat32SubrootInfo, err := os.Lstat(fat32Subroot)
if err != nil {
t.Fatal("lstat failed for FAT32 subpath:", err)
}
fat32SubrootDeviceID, err := DeviceID(fat32SubrootInfo)
if err != nil {
t.Fatal("device ID probe failed for FAT32 subpath:", err)
}
// Ensure they differ.
if fat32SubrootDeviceID == parentDeviceID {
t.Error("separate partition has same device ID as parent path")
}
}
| [
"\"MUTAGEN_TEST_FAT32_ROOT\"",
"\"MUTAGEN_TEST_FAT32_SUBROOT\""
]
| []
| [
"MUTAGEN_TEST_FAT32_SUBROOT",
"MUTAGEN_TEST_FAT32_ROOT"
]
| [] | ["MUTAGEN_TEST_FAT32_SUBROOT", "MUTAGEN_TEST_FAT32_ROOT"] | go | 2 | 0 | |
BeaverStacks/BeaverStacks/wsgi.py | """
WSGI config for BeaverStacks project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'BeaverStacks.settings')
application = get_wsgi_application()
| []
| []
| []
| [] | [] | python | 0 | 0 | |
tools/shared.py | # Copyright 2011 The Emscripten Authors. All rights reserved.
# Emscripten is available under two separate licenses, the MIT license and the
# University of Illinois/NCSA Open Source License. Both these licenses can be
# found in the LICENSE file.
from .toolchain_profiler import ToolchainProfiler
from subprocess import PIPE
import atexit
import binascii
import json
import logging
import os
import re
import shutil
import subprocess
import signal
import stat
import sys
import tempfile
# We depend on python 3.6 for fstring support
if sys.version_info < (3, 6):
print('error: emscripten requires python 3.6 or above', file=sys.stderr)
sys.exit(1)
from . import colored_logger
# Configure logging before importing any other local modules so even
# log message during import are shown as expected.
DEBUG = int(os.environ.get('EMCC_DEBUG', '0'))
# can add %(asctime)s to see timestamps
logging.basicConfig(format='%(name)s:%(levelname)s: %(message)s',
level=logging.DEBUG if DEBUG else logging.INFO)
colored_logger.enable()
from .tempfiles import try_delete
from .utils import path_from_root, exit_with_error, safe_ensure_dirs, WINDOWS
from . import cache, tempfiles
from . import diagnostics
from . import config
from . import filelock
from . import utils
from .settings import settings
DEBUG_SAVE = DEBUG or int(os.environ.get('EMCC_DEBUG_SAVE', '0'))
MINIMUM_NODE_VERSION = (4, 1, 1)
EXPECTED_LLVM_VERSION = "15.0"
# Used only when EM_PYTHON_MULTIPROCESSING=1 env. var is set.
multiprocessing_pool = None
logger = logging.getLogger('shared')
# warning about absolute-paths is disabled by default, and not enabled by -Wall
diagnostics.add_warning('absolute-paths', enabled=False, part_of_all=False)
# unused diagnostic flags. TODO(sbc): remove at some point
diagnostics.add_warning('almost-asm')
diagnostics.add_warning('experimental')
diagnostics.add_warning('invalid-input')
# Don't show legacy settings warnings by default
diagnostics.add_warning('legacy-settings', enabled=False, part_of_all=False)
# Catch-all for other emcc warnings
diagnostics.add_warning('linkflags')
diagnostics.add_warning('emcc')
diagnostics.add_warning('undefined', error=True)
diagnostics.add_warning('deprecated', shared=True)
diagnostics.add_warning('version-check')
diagnostics.add_warning('export-main')
diagnostics.add_warning('map-unrecognized-libraries')
diagnostics.add_warning('unused-command-line-argument', shared=True)
diagnostics.add_warning('pthreads-mem-growth')
diagnostics.add_warning('transpile')
diagnostics.add_warning('limited-postlink-optimizations')
diagnostics.add_warning('em-js-i64')
# TODO(sbc): Investigate switching to shlex.quote
def shlex_quote(arg):
arg = os.fspath(arg)
if ' ' in arg and (not (arg.startswith('"') and arg.endswith('"'))) and (not (arg.startswith("'") and arg.endswith("'"))):
return '"' + arg.replace('"', '\\"') + '"'
return arg
# Switch to shlex.join once we can depend on python 3.8:
# https://docs.python.org/3/library/shlex.html#shlex.join
def shlex_join(cmd):
return ' '.join(shlex_quote(x) for x in cmd)
def run_process(cmd, check=True, input=None, *args, **kw):
"""Runs a subprocess returning the exit code.
By default this function will raise an exception on failure. Therefor this should only be
used if you want to handle such failures. For most subprocesses, failures are not recoverable
and should be fatal. In those cases the `check_call` wrapper should be preferred.
"""
# Flush standard streams otherwise the output of the subprocess may appear in the
# output before messages that we have already written.
sys.stdout.flush()
sys.stderr.flush()
kw.setdefault('universal_newlines', True)
kw.setdefault('encoding', 'utf-8')
ret = subprocess.run(cmd, check=check, input=input, *args, **kw)
debug_text = '%sexecuted %s' % ('successfully ' if check else '', shlex_join(cmd))
logger.debug(debug_text)
return ret
def get_num_cores():
return int(os.environ.get('EMCC_CORES', os.cpu_count()))
def mp_run_process(command_tuple):
temp_files = get_temp_files()
cmd, env, route_stdout_to_temp_files_suffix, pipe_stdout, check, cwd = command_tuple
std_out = temp_files.get(route_stdout_to_temp_files_suffix) if route_stdout_to_temp_files_suffix else (subprocess.PIPE if pipe_stdout else None)
ret = std_out.name if route_stdout_to_temp_files_suffix else None
proc = subprocess.Popen(cmd, stdout=std_out, stderr=subprocess.PIPE if pipe_stdout else None, env=env, cwd=cwd)
out, _ = proc.communicate()
if pipe_stdout:
ret = out.decode('UTF-8')
return ret
def returncode_to_str(code):
assert code != 0
if code < 0:
signal_name = signal.Signals(-code).name
return f'received {signal_name} ({code})'
return f'returned {code}'
# Runs multiple subprocess commands.
# bool 'check': If True (default), raises an exception if any of the subprocesses failed with a nonzero exit code.
# string 'route_stdout_to_temp_files_suffix': if not None, all stdouts are instead written to files, and an array of filenames is returned.
# bool 'pipe_stdout': If True, an array of stdouts is returned, for each subprocess.
def run_multiple_processes(commands,
env=None,
route_stdout_to_temp_files_suffix=None,
pipe_stdout=False,
check=True,
cwd=None):
if env is None:
env = os.environ.copy()
# By default, avoid using Python multiprocessing library due to a large amount of bugs it has on Windows (#8013, #718, #13785, etc.)
# Use EM_PYTHON_MULTIPROCESSING=1 environment variable to enable it. It can be faster, but may not work on Windows.
if int(os.getenv('EM_PYTHON_MULTIPROCESSING', '0')):
import multiprocessing
global multiprocessing_pool
if not multiprocessing_pool:
multiprocessing_pool = multiprocessing.Pool(processes=get_num_cores())
return multiprocessing_pool.map(mp_run_process, [(cmd, env, route_stdout_to_temp_files_suffix, pipe_stdout, check, cwd) for cmd in commands], chunksize=1)
std_outs = []
if route_stdout_to_temp_files_suffix and pipe_stdout:
raise Exception('Cannot simultaneously pipe stdout to file and a string! Choose one or the other.')
# TODO: Experiment with registering a signal handler here to see if that helps with Ctrl-C locking up the command prompt
# when multiple child processes have been spawned.
# import signal
# def signal_handler(sig, frame):
# sys.exit(1)
# signal.signal(signal.SIGINT, signal_handler)
with ToolchainProfiler.profile_block('run_multiple_processes'):
processes = []
num_parallel_processes = get_num_cores()
temp_files = get_temp_files()
i = 0
num_completed = 0
while num_completed < len(commands):
if i < len(commands) and len(processes) < num_parallel_processes:
# Not enough parallel processes running, spawn a new one.
std_out = temp_files.get(route_stdout_to_temp_files_suffix) if route_stdout_to_temp_files_suffix else (subprocess.PIPE if pipe_stdout else None)
if DEBUG:
logger.debug('Running subprocess %d/%d: %s' % (i + 1, len(commands), ' '.join(commands[i])))
print_compiler_stage(commands[i])
processes += [(i, subprocess.Popen(commands[i], stdout=std_out, stderr=subprocess.PIPE if pipe_stdout else None, env=env, cwd=cwd))]
if route_stdout_to_temp_files_suffix:
std_outs += [(i, std_out.name)]
i += 1
else:
# Not spawning a new process (Too many commands running in parallel, or no commands left): find if a process has finished.
def get_finished_process():
while True:
j = 0
while j < len(processes):
if processes[j][1].poll() is not None:
out, err = processes[j][1].communicate()
return (j, out.decode('UTF-8') if out else '', err.decode('UTF-8') if err else '')
j += 1
# All processes still running; wait a short while for the first (oldest) process to finish,
# then look again if any process has completed.
try:
out, err = processes[0][1].communicate(0.2)
return (0, out.decode('UTF-8') if out else '', err.decode('UTF-8') if err else '')
except subprocess.TimeoutExpired:
pass
j, out, err = get_finished_process()
idx, finished_process = processes[j]
del processes[j]
if pipe_stdout:
std_outs += [(idx, out)]
if check and finished_process.returncode != 0:
if out:
logger.info(out)
if err:
logger.error(err)
raise Exception('Subprocess %d/%d failed (%s)! (cmdline: %s)' % (idx + 1, len(commands), returncode_to_str(finished_process.returncode), shlex_join(commands[idx])))
num_completed += 1
# If processes finished out of order, sort the results to the order of the input.
std_outs.sort(key=lambda x: x[0])
return [x[1] for x in std_outs]
def check_call(cmd, *args, **kw):
"""Like `run_process` above but treat failures as fatal and exit_with_error."""
print_compiler_stage(cmd)
try:
return run_process(cmd, *args, **kw)
except subprocess.CalledProcessError as e:
exit_with_error("'%s' failed (%s)", shlex_join(cmd), returncode_to_str(e.returncode))
except OSError as e:
exit_with_error("'%s' failed: %s", shlex_join(cmd), str(e))
def run_js_tool(filename, jsargs=[], node_args=[], **kw): # noqa: mutable default args
"""Execute a javascript tool.
This is used by emcc to run parts of the build process that are written
implemented in javascript.
"""
command = config.NODE_JS + node_args + [filename] + jsargs
return check_call(command, **kw).stdout
def get_npm_cmd(name):
if WINDOWS:
cmd = [path_from_root('node_modules/.bin', name + '.cmd')]
else:
cmd = config.NODE_JS + [path_from_root('node_modules/.bin', name)]
if not os.path.exists(cmd[-1]):
exit_with_error(f'{name} was not found! Please run "npm install" in Emscripten root directory to set up npm dependencies')
return cmd
def get_clang_version():
if not hasattr(get_clang_version, 'found_version'):
if not os.path.exists(CLANG_CC):
exit_with_error('clang executable not found at `%s`' % CLANG_CC)
proc = check_call([CLANG_CC, '--version'], stdout=PIPE)
m = re.search(r'[Vv]ersion\s+(\d+\.\d+)', proc.stdout)
get_clang_version.found_version = m and m.group(1)
return get_clang_version.found_version
def check_llvm_version():
actual = get_clang_version()
if EXPECTED_LLVM_VERSION in actual:
return True
diagnostics.warning('version-check', 'LLVM version for clang executable "%s" appears incorrect (seeing "%s", expected "%s")', CLANG_CC, actual, EXPECTED_LLVM_VERSION)
return False
def get_llc_targets():
if not os.path.exists(LLVM_COMPILER):
exit_with_error('llc executable not found at `%s`' % LLVM_COMPILER)
try:
llc_version_info = run_process([LLVM_COMPILER, '--version'], stdout=PIPE).stdout
except subprocess.CalledProcessError:
exit_with_error('error running `llc --version`. Check your llvm installation (%s)' % LLVM_COMPILER)
if 'Registered Targets:' not in llc_version_info:
exit_with_error('error parsing output of `llc --version`. Check your llvm installation (%s)' % LLVM_COMPILER)
pre, targets = llc_version_info.split('Registered Targets:')
return targets
def check_llvm():
targets = get_llc_targets()
if 'wasm32' not in targets and 'WebAssembly 32-bit' not in targets:
logger.critical('LLVM has not been built with the WebAssembly backend, llc reports:')
print('===========================================================================', file=sys.stderr)
print(targets, file=sys.stderr)
print('===========================================================================', file=sys.stderr)
return False
return True
def get_node_directory():
return os.path.dirname(config.NODE_JS[0] if type(config.NODE_JS) is list else config.NODE_JS)
# When we run some tools from npm (closure, html-minifier-terser), those
# expect that the tools have node.js accessible in PATH. Place our node
# there when invoking those tools.
def env_with_node_in_path():
env = os.environ.copy()
env['PATH'] = get_node_directory() + os.pathsep + env['PATH']
return env
def check_node_version():
try:
actual = run_process(config.NODE_JS + ['--version'], stdout=PIPE).stdout.strip()
version = actual.replace('v', '')
version = version.split('-')[0].split('.')
version = tuple(int(v) for v in version)
except Exception as e:
diagnostics.warning('version-check', 'cannot check node version: %s', e)
return False
if version < MINIMUM_NODE_VERSION:
expected = '.'.join(str(v) for v in MINIMUM_NODE_VERSION)
diagnostics.warning('version-check', f'node version appears too old (seeing "{actual}", expected "v{expected}")')
return False
return True
def set_version_globals():
global EMSCRIPTEN_VERSION, EMSCRIPTEN_VERSION_MAJOR, EMSCRIPTEN_VERSION_MINOR, EMSCRIPTEN_VERSION_TINY
filename = path_from_root('emscripten-version.txt')
EMSCRIPTEN_VERSION = utils.read_file(filename).strip().strip('"')
parts = [int(x) for x in EMSCRIPTEN_VERSION.split('-')[0].split('.')]
EMSCRIPTEN_VERSION_MAJOR, EMSCRIPTEN_VERSION_MINOR, EMSCRIPTEN_VERSION_TINY = parts
def generate_sanity():
sanity_file_content = f'{EMSCRIPTEN_VERSION}|{config.LLVM_ROOT}|{get_clang_version()}'
config_data = utils.read_file(config.EM_CONFIG)
checksum = binascii.crc32(config_data.encode())
sanity_file_content += '|%#x\n' % checksum
return sanity_file_content
def perform_sanity_checks():
# some warning, mostly not fatal checks - do them even if EM_IGNORE_SANITY is on
check_node_version()
check_llvm_version()
llvm_ok = check_llvm()
if os.environ.get('EM_IGNORE_SANITY'):
logger.info('EM_IGNORE_SANITY set, ignoring sanity checks')
return
logger.info('(Emscripten: Running sanity checks)')
if not llvm_ok:
exit_with_error('failing sanity checks due to previous llvm failure')
with ToolchainProfiler.profile_block('sanity compiler_engine'):
try:
run_process(config.NODE_JS + ['-e', 'console.log("hello")'], stdout=PIPE)
except Exception as e:
exit_with_error('The configured node executable (%s) does not seem to work, check the paths in %s (%s)', config.NODE_JS, config.EM_CONFIG, str(e))
with ToolchainProfiler.profile_block('sanity LLVM'):
for cmd in [CLANG_CC, LLVM_AR, LLVM_NM]:
if not os.path.exists(cmd) and not os.path.exists(cmd + '.exe'): # .exe extension required for Windows
exit_with_error('Cannot find %s, check the paths in %s', cmd, config.EM_CONFIG)
@ToolchainProfiler.profile()
def check_sanity(force=False):
"""Check that basic stuff we need (a JS engine to compile, Node.js, and Clang
and LLVM) exists.
The test runner always does this check (through |force|). emcc does this less
frequently, only when ${EM_CONFIG}_sanity does not exist or is older than
EM_CONFIG (so, we re-check sanity when the settings are changed). We also
re-check sanity and clear the cache when the version changes.
"""
if not force and os.environ.get('EMCC_SKIP_SANITY_CHECK') == '1':
return
# We set EMCC_SKIP_SANITY_CHECK so that any subprocesses that we launch will
# not re-run the tests.
os.environ['EMCC_SKIP_SANITY_CHECK'] = '1'
if DEBUG:
force = True
if config.FROZEN_CACHE:
if force:
perform_sanity_checks()
return
if os.environ.get('EM_IGNORE_SANITY'):
perform_sanity_checks()
return
expected = generate_sanity()
sanity_file = Cache.get_path('sanity.txt')
with Cache.lock():
if os.path.exists(sanity_file):
sanity_data = utils.read_file(sanity_file)
if sanity_data != expected:
logger.debug('old sanity: %s' % sanity_data)
logger.debug('new sanity: %s' % expected)
logger.info('(Emscripten: config changed, clearing cache)')
Cache.erase()
# the check actually failed, so definitely write out the sanity file, to
# avoid others later seeing failures too
force = False
else:
if force:
logger.debug(f'sanity file up-to-date but check forced: {sanity_file}')
else:
logger.debug(f'sanity file up-to-date: {sanity_file}')
return # all is well
else:
logger.debug(f'sanity file not found: {sanity_file}')
perform_sanity_checks()
if not force:
# Only create/update this file if the sanity check succeeded, i.e., we got here
utils.write_file(sanity_file, expected)
# Some distributions ship with multiple llvm versions so they add
# the version to the binaries, cope with that
def build_llvm_tool_path(tool):
if config.LLVM_ADD_VERSION:
return os.path.join(config.LLVM_ROOT, tool + "-" + config.LLVM_ADD_VERSION)
else:
return os.path.join(config.LLVM_ROOT, tool)
# Some distributions ship with multiple clang versions so they add
# the version to the binaries, cope with that
def build_clang_tool_path(tool):
if config.CLANG_ADD_VERSION:
return os.path.join(config.LLVM_ROOT, tool + "-" + config.CLANG_ADD_VERSION)
else:
return os.path.join(config.LLVM_ROOT, tool)
def exe_suffix(cmd):
return cmd + '.exe' if WINDOWS else cmd
def bat_suffix(cmd):
return cmd + '.bat' if WINDOWS else cmd
def replace_suffix(filename, new_suffix):
assert new_suffix[0] == '.'
return os.path.splitext(filename)[0] + new_suffix
# In MINIMAL_RUNTIME mode, keep suffixes of generated files simple
# ('.mem' instead of '.js.mem'; .'symbols' instead of '.js.symbols' etc)
# Retain the original naming scheme in traditional runtime.
def replace_or_append_suffix(filename, new_suffix):
assert new_suffix[0] == '.'
return replace_suffix(filename, new_suffix) if settings.MINIMAL_RUNTIME else filename + new_suffix
# Temp dir. Create a random one, unless EMCC_DEBUG is set, in which case use the canonical
# temp directory (TEMP_DIR/emscripten_temp).
def get_emscripten_temp_dir():
"""Returns a path to EMSCRIPTEN_TEMP_DIR, creating one if it didn't exist."""
global EMSCRIPTEN_TEMP_DIR
if not EMSCRIPTEN_TEMP_DIR:
EMSCRIPTEN_TEMP_DIR = tempfile.mkdtemp(prefix='emscripten_temp_', dir=TEMP_DIR)
if not DEBUG_SAVE:
def prepare_to_clean_temp(d):
def clean_temp():
try_delete(d)
atexit.register(clean_temp)
# this global var might change later
prepare_to_clean_temp(EMSCRIPTEN_TEMP_DIR)
return EMSCRIPTEN_TEMP_DIR
def get_canonical_temp_dir(temp_dir):
return os.path.join(temp_dir, 'emscripten_temp')
def setup_temp_dirs():
global EMSCRIPTEN_TEMP_DIR, CANONICAL_TEMP_DIR, TEMP_DIR
EMSCRIPTEN_TEMP_DIR = None
TEMP_DIR = os.environ.get("EMCC_TEMP_DIR", tempfile.gettempdir())
if not os.path.isdir(TEMP_DIR):
exit_with_error(f'The temporary directory `{TEMP_DIR}` does not exist! Please make sure that the path is correct.')
CANONICAL_TEMP_DIR = get_canonical_temp_dir(TEMP_DIR)
if DEBUG:
EMSCRIPTEN_TEMP_DIR = CANONICAL_TEMP_DIR
try:
safe_ensure_dirs(EMSCRIPTEN_TEMP_DIR)
except Exception as e:
exit_with_error(str(e) + f'Could not create canonical temp dir. Check definition of TEMP_DIR in {config.EM_CONFIG}')
# Since the canonical temp directory is, by definition, the same
# between all processes that run in DEBUG mode we need to use a multi
# process lock to prevent more than one process from writing to it.
# This is because emcc assumes that it can use non-unique names inside
# the temp directory.
# Sadly we need to allow child processes to access this directory
# though, since emcc can recursively call itself when building
# libraries and ports.
if 'EM_HAVE_TEMP_DIR_LOCK' not in os.environ:
filelock_name = os.path.join(EMSCRIPTEN_TEMP_DIR, 'emscripten.lock')
lock = filelock.FileLock(filelock_name)
os.environ['EM_HAVE_TEMP_DIR_LOCK'] = '1'
lock.acquire()
atexit.register(lock.release)
def get_temp_files():
if DEBUG_SAVE:
# In debug mode store all temp files in the emscripten-specific temp dir
# and don't worry about cleaning them up.
return tempfiles.TempFiles(get_emscripten_temp_dir(), save_debug_files=True)
else:
# Otherwise use the system tempdir and try to clean up after ourselves.
return tempfiles.TempFiles(TEMP_DIR, save_debug_files=False)
def target_environment_may_be(environment):
return not settings.ENVIRONMENT or environment in settings.ENVIRONMENT.split(',')
def print_compiler_stage(cmd):
"""Emulate the '-v' of clang/gcc by printing the name of the sub-command
before executing it."""
if PRINT_STAGES:
print(' "%s" %s' % (cmd[0], shlex_join(cmd[1:])), file=sys.stderr)
sys.stderr.flush()
def mangle_c_symbol_name(name):
return '_' + name if not name.startswith('$') else name[1:]
def demangle_c_symbol_name(name):
return name[1:] if name.startswith('_') else '$' + name
def is_c_symbol(name):
return name.startswith('_')
def treat_as_user_function(name):
if name.startswith('dynCall_'):
return False
if name in settings.WASM_SYSTEM_EXPORTS:
return False
return True
def asmjs_mangle(name):
"""Mangle a name the way asm.js/JSBackend globals are mangled.
Prepends '_' and replaces non-alphanumerics with '_'.
Used by wasm backend for JS library consistency with asm.js.
"""
# We also use this function to convert the clang-mangled `__main_argc_argv`
# to simply `main` which is expected by the emscripten JS glue code.
if name == '__main_argc_argv':
name = 'main'
if treat_as_user_function(name):
return '_' + name
return name
def reconfigure_cache():
global Cache
Cache = cache.Cache(config.CACHE)
def suffix(name):
"""Return the file extension"""
return os.path.splitext(name)[1]
def unsuffixed(name):
"""Return the filename without the extension.
If there are multiple extensions this strips only the final one.
"""
return os.path.splitext(name)[0]
def unsuffixed_basename(name):
return os.path.basename(unsuffixed(name))
def strip_prefix(string, prefix):
assert string.startswith(prefix)
return string[len(prefix):]
def make_writable(filename):
assert(os.path.isfile(filename))
old_mode = stat.S_IMODE(os.stat(filename).st_mode)
os.chmod(filename, old_mode | stat.S_IWUSR)
def safe_copy(src, dst):
logging.debug('copy: %s -> %s', src, dst)
src = os.path.abspath(src)
dst = os.path.abspath(dst)
if os.path.isdir(dst):
dst = os.path.join(dst, os.path.basename(src))
if src == dst:
return
if dst == os.devnull:
return
# Copies data and permission bits, but not other metadata such as timestamp
shutil.copy(src, dst)
# We always want the target file to be writable even when copying from
# read-only source. (e.g. a read-only install of emscripten).
make_writable(dst)
def read_and_preprocess(filename, expand_macros=False):
temp_dir = get_emscripten_temp_dir()
# Create a settings file with the current settings to pass to the JS preprocessor
settings_str = ''
for key, value in settings.dict().items():
assert key == key.upper() # should only ever be uppercase keys in settings
jsoned = json.dumps(value, sort_keys=True)
settings_str += f'var {key} = {jsoned};\n'
settings_file = os.path.join(temp_dir, 'settings.js')
utils.write_file(settings_file, settings_str)
# Run the JS preprocessor
# N.B. We can't use the default stdout=PIPE here as it only allows 64K of output before it hangs
# and shell.html is bigger than that!
# See https://thraxil.org/users/anders/posts/2008/03/13/Subprocess-Hanging-PIPE-is-your-enemy/
dirname, filename = os.path.split(filename)
if not dirname:
dirname = None
stdout = os.path.join(temp_dir, 'stdout')
args = [settings_file, filename]
if expand_macros:
args += ['--expandMacros']
run_js_tool(path_from_root('tools/preprocessor.js'), args, stdout=open(stdout, 'w'), cwd=dirname)
out = utils.read_file(stdout)
return out
def do_replace(input_, pattern, replacement):
if pattern not in input_:
exit_with_error('expected to find pattern in input JS: %s' % pattern)
return input_.replace(pattern, replacement)
def get_llvm_target():
if settings.MEMORY64:
return 'wasm64-unknown-emscripten'
else:
return 'wasm32-unknown-emscripten'
# ============================================================================
# End declarations.
# ============================================================================
# Everything below this point is top level code that get run when importing this
# file. TODO(sbc): We should try to reduce that amount we do here and instead
# have consumers explicitly call initialization functions.
set_version_globals()
CLANG_CC = os.path.expanduser(build_clang_tool_path(exe_suffix('clang')))
CLANG_CXX = os.path.expanduser(build_clang_tool_path(exe_suffix('clang++')))
LLVM_LINK = build_llvm_tool_path(exe_suffix('llvm-link'))
LLVM_AR = build_llvm_tool_path(exe_suffix('llvm-ar'))
LLVM_DWP = build_llvm_tool_path(exe_suffix('llvm-dwp'))
LLVM_RANLIB = build_llvm_tool_path(exe_suffix('llvm-ranlib'))
LLVM_OPT = os.path.expanduser(build_llvm_tool_path(exe_suffix('opt')))
LLVM_NM = os.path.expanduser(build_llvm_tool_path(exe_suffix('llvm-nm')))
LLVM_MC = os.path.expanduser(build_llvm_tool_path(exe_suffix('llvm-mc')))
LLVM_INTERPRETER = os.path.expanduser(build_llvm_tool_path(exe_suffix('lli')))
LLVM_COMPILER = os.path.expanduser(build_llvm_tool_path(exe_suffix('llc')))
LLVM_DWARFDUMP = os.path.expanduser(build_llvm_tool_path(exe_suffix('llvm-dwarfdump')))
LLVM_OBJCOPY = os.path.expanduser(build_llvm_tool_path(exe_suffix('llvm-objcopy')))
LLVM_STRIP = os.path.expanduser(build_llvm_tool_path(exe_suffix('llvm-strip')))
WASM_LD = os.path.expanduser(build_llvm_tool_path(exe_suffix('wasm-ld')))
EMCC = bat_suffix(path_from_root('emcc'))
EMXX = bat_suffix(path_from_root('em++'))
EMAR = bat_suffix(path_from_root('emar'))
EMRANLIB = bat_suffix(path_from_root('emranlib'))
EMCMAKE = bat_suffix(path_from_root('emcmake'))
EMCONFIGURE = bat_suffix(path_from_root('emconfigure'))
EM_NM = bat_suffix(path_from_root('emnm'))
FILE_PACKAGER = bat_suffix(path_from_root('tools/file_packager'))
WASM_SOURCEMAP = bat_suffix(path_from_root('tools/wasm-sourcemap'))
setup_temp_dirs()
Cache = cache.Cache(config.CACHE)
PRINT_STAGES = int(os.getenv('EMCC_VERBOSE', '0'))
| []
| []
| [
"EMCC_DEBUG",
"EM_HAVE_TEMP_DIR_LOCK",
"EMCC_DEBUG_SAVE",
"EM_IGNORE_SANITY",
"EMCC_VERBOSE",
"EMCC_CORES",
"EMCC_TEMP_DIR",
"EM_PYTHON_MULTIPROCESSING",
"EMCC_SKIP_SANITY_CHECK"
]
| [] | ["EMCC_DEBUG", "EM_HAVE_TEMP_DIR_LOCK", "EMCC_DEBUG_SAVE", "EM_IGNORE_SANITY", "EMCC_VERBOSE", "EMCC_CORES", "EMCC_TEMP_DIR", "EM_PYTHON_MULTIPROCESSING", "EMCC_SKIP_SANITY_CHECK"] | python | 9 | 0 | |
apis/extensions/v1beta1/zz_generated_ingress_controller.go | package v1beta1
import (
"context"
"github.com/rancher/norman/controller"
"github.com/rancher/norman/objectclient"
"github.com/rancher/norman/resource"
"k8s.io/api/extensions/v1beta1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/tools/cache"
)
var (
IngressGroupVersionKind = schema.GroupVersionKind{
Version: Version,
Group: GroupName,
Kind: "Ingress",
}
IngressResource = metav1.APIResource{
Name: "ingresses",
SingularName: "ingress",
Namespaced: true,
Kind: IngressGroupVersionKind.Kind,
}
IngressGroupVersionResource = schema.GroupVersionResource{
Group: GroupName,
Version: Version,
Resource: "ingresses",
}
)
func init() {
resource.Put(IngressGroupVersionResource)
}
func NewIngress(namespace, name string, obj v1beta1.Ingress) *v1beta1.Ingress {
obj.APIVersion, obj.Kind = IngressGroupVersionKind.ToAPIVersionAndKind()
obj.Name = name
obj.Namespace = namespace
return &obj
}
type IngressList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []v1beta1.Ingress `json:"items"`
}
type IngressHandlerFunc func(key string, obj *v1beta1.Ingress) (runtime.Object, error)
type IngressChangeHandlerFunc func(obj *v1beta1.Ingress) (runtime.Object, error)
type IngressLister interface {
List(namespace string, selector labels.Selector) (ret []*v1beta1.Ingress, err error)
Get(namespace, name string) (*v1beta1.Ingress, error)
}
type IngressController interface {
Generic() controller.GenericController
Informer() cache.SharedIndexInformer
Lister() IngressLister
AddHandler(ctx context.Context, name string, handler IngressHandlerFunc)
AddFeatureHandler(ctx context.Context, enabled func() bool, name string, sync IngressHandlerFunc)
AddClusterScopedHandler(ctx context.Context, name, clusterName string, handler IngressHandlerFunc)
AddClusterScopedFeatureHandler(ctx context.Context, enabled func() bool, name, clusterName string, handler IngressHandlerFunc)
Enqueue(namespace, name string)
Sync(ctx context.Context) error
Start(ctx context.Context, threadiness int) error
}
type IngressInterface interface {
ObjectClient() *objectclient.ObjectClient
Create(*v1beta1.Ingress) (*v1beta1.Ingress, error)
GetNamespaced(namespace, name string, opts metav1.GetOptions) (*v1beta1.Ingress, error)
Get(name string, opts metav1.GetOptions) (*v1beta1.Ingress, error)
Update(*v1beta1.Ingress) (*v1beta1.Ingress, error)
Delete(name string, options *metav1.DeleteOptions) error
DeleteNamespaced(namespace, name string, options *metav1.DeleteOptions) error
List(opts metav1.ListOptions) (*IngressList, error)
Watch(opts metav1.ListOptions) (watch.Interface, error)
DeleteCollection(deleteOpts *metav1.DeleteOptions, listOpts metav1.ListOptions) error
Controller() IngressController
AddHandler(ctx context.Context, name string, sync IngressHandlerFunc)
AddFeatureHandler(ctx context.Context, enabled func() bool, name string, sync IngressHandlerFunc)
AddLifecycle(ctx context.Context, name string, lifecycle IngressLifecycle)
AddFeatureLifecycle(ctx context.Context, enabled func() bool, name string, lifecycle IngressLifecycle)
AddClusterScopedHandler(ctx context.Context, name, clusterName string, sync IngressHandlerFunc)
AddClusterScopedFeatureHandler(ctx context.Context, enabled func() bool, name, clusterName string, sync IngressHandlerFunc)
AddClusterScopedLifecycle(ctx context.Context, name, clusterName string, lifecycle IngressLifecycle)
AddClusterScopedFeatureLifecycle(ctx context.Context, enabled func() bool, name, clusterName string, lifecycle IngressLifecycle)
}
type ingressLister struct {
controller *ingressController
}
func (l *ingressLister) List(namespace string, selector labels.Selector) (ret []*v1beta1.Ingress, err error) {
err = cache.ListAllByNamespace(l.controller.Informer().GetIndexer(), namespace, selector, func(obj interface{}) {
ret = append(ret, obj.(*v1beta1.Ingress))
})
return
}
func (l *ingressLister) Get(namespace, name string) (*v1beta1.Ingress, error) {
var key string
if namespace != "" {
key = namespace + "/" + name
} else {
key = name
}
obj, exists, err := l.controller.Informer().GetIndexer().GetByKey(key)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(schema.GroupResource{
Group: IngressGroupVersionKind.Group,
Resource: "ingress",
}, key)
}
return obj.(*v1beta1.Ingress), nil
}
type ingressController struct {
controller.GenericController
}
func (c *ingressController) Generic() controller.GenericController {
return c.GenericController
}
func (c *ingressController) Lister() IngressLister {
return &ingressLister{
controller: c,
}
}
func (c *ingressController) AddHandler(ctx context.Context, name string, handler IngressHandlerFunc) {
c.GenericController.AddHandler(ctx, name, func(key string, obj interface{}) (interface{}, error) {
if obj == nil {
return handler(key, nil)
} else if v, ok := obj.(*v1beta1.Ingress); ok {
return handler(key, v)
} else {
return nil, nil
}
})
}
func (c *ingressController) AddFeatureHandler(ctx context.Context, enabled func() bool, name string, handler IngressHandlerFunc) {
c.GenericController.AddHandler(ctx, name, func(key string, obj interface{}) (interface{}, error) {
if !enabled() {
return nil, nil
} else if obj == nil {
return handler(key, nil)
} else if v, ok := obj.(*v1beta1.Ingress); ok {
return handler(key, v)
} else {
return nil, nil
}
})
}
func (c *ingressController) AddClusterScopedHandler(ctx context.Context, name, cluster string, handler IngressHandlerFunc) {
resource.PutClusterScoped(IngressGroupVersionResource)
c.GenericController.AddHandler(ctx, name, func(key string, obj interface{}) (interface{}, error) {
if obj == nil {
return handler(key, nil)
} else if v, ok := obj.(*v1beta1.Ingress); ok && controller.ObjectInCluster(cluster, obj) {
return handler(key, v)
} else {
return nil, nil
}
})
}
func (c *ingressController) AddClusterScopedFeatureHandler(ctx context.Context, enabled func() bool, name, cluster string, handler IngressHandlerFunc) {
resource.PutClusterScoped(IngressGroupVersionResource)
c.GenericController.AddHandler(ctx, name, func(key string, obj interface{}) (interface{}, error) {
if !enabled() {
return nil, nil
} else if obj == nil {
return handler(key, nil)
} else if v, ok := obj.(*v1beta1.Ingress); ok && controller.ObjectInCluster(cluster, obj) {
return handler(key, v)
} else {
return nil, nil
}
})
}
type ingressFactory struct {
}
func (c ingressFactory) Object() runtime.Object {
return &v1beta1.Ingress{}
}
func (c ingressFactory) List() runtime.Object {
return &IngressList{}
}
func (s *ingressClient) Controller() IngressController {
s.client.Lock()
defer s.client.Unlock()
c, ok := s.client.ingressControllers[s.ns]
if ok {
return c
}
genericController := controller.NewGenericController(IngressGroupVersionKind.Kind+"Controller",
s.objectClient)
c = &ingressController{
GenericController: genericController,
}
s.client.ingressControllers[s.ns] = c
s.client.starters = append(s.client.starters, c)
return c
}
type ingressClient struct {
client *Client
ns string
objectClient *objectclient.ObjectClient
controller IngressController
}
func (s *ingressClient) ObjectClient() *objectclient.ObjectClient {
return s.objectClient
}
func (s *ingressClient) Create(o *v1beta1.Ingress) (*v1beta1.Ingress, error) {
obj, err := s.objectClient.Create(o)
return obj.(*v1beta1.Ingress), err
}
func (s *ingressClient) Get(name string, opts metav1.GetOptions) (*v1beta1.Ingress, error) {
obj, err := s.objectClient.Get(name, opts)
return obj.(*v1beta1.Ingress), err
}
func (s *ingressClient) GetNamespaced(namespace, name string, opts metav1.GetOptions) (*v1beta1.Ingress, error) {
obj, err := s.objectClient.GetNamespaced(namespace, name, opts)
return obj.(*v1beta1.Ingress), err
}
func (s *ingressClient) Update(o *v1beta1.Ingress) (*v1beta1.Ingress, error) {
obj, err := s.objectClient.Update(o.Name, o)
return obj.(*v1beta1.Ingress), err
}
func (s *ingressClient) Delete(name string, options *metav1.DeleteOptions) error {
return s.objectClient.Delete(name, options)
}
func (s *ingressClient) DeleteNamespaced(namespace, name string, options *metav1.DeleteOptions) error {
return s.objectClient.DeleteNamespaced(namespace, name, options)
}
func (s *ingressClient) List(opts metav1.ListOptions) (*IngressList, error) {
obj, err := s.objectClient.List(opts)
return obj.(*IngressList), err
}
func (s *ingressClient) Watch(opts metav1.ListOptions) (watch.Interface, error) {
return s.objectClient.Watch(opts)
}
// Patch applies the patch and returns the patched deployment.
func (s *ingressClient) Patch(o *v1beta1.Ingress, patchType types.PatchType, data []byte, subresources ...string) (*v1beta1.Ingress, error) {
obj, err := s.objectClient.Patch(o.Name, o, patchType, data, subresources...)
return obj.(*v1beta1.Ingress), err
}
func (s *ingressClient) DeleteCollection(deleteOpts *metav1.DeleteOptions, listOpts metav1.ListOptions) error {
return s.objectClient.DeleteCollection(deleteOpts, listOpts)
}
func (s *ingressClient) AddHandler(ctx context.Context, name string, sync IngressHandlerFunc) {
s.Controller().AddHandler(ctx, name, sync)
}
func (s *ingressClient) AddFeatureHandler(ctx context.Context, enabled func() bool, name string, sync IngressHandlerFunc) {
s.Controller().AddFeatureHandler(ctx, enabled, name, sync)
}
func (s *ingressClient) AddLifecycle(ctx context.Context, name string, lifecycle IngressLifecycle) {
sync := NewIngressLifecycleAdapter(name, false, s, lifecycle)
s.Controller().AddHandler(ctx, name, sync)
}
func (s *ingressClient) AddFeatureLifecycle(ctx context.Context, enabled func() bool, name string, lifecycle IngressLifecycle) {
sync := NewIngressLifecycleAdapter(name, false, s, lifecycle)
s.Controller().AddFeatureHandler(ctx, enabled, name, sync)
}
func (s *ingressClient) AddClusterScopedHandler(ctx context.Context, name, clusterName string, sync IngressHandlerFunc) {
s.Controller().AddClusterScopedHandler(ctx, name, clusterName, sync)
}
func (s *ingressClient) AddClusterScopedFeatureHandler(ctx context.Context, enabled func() bool, name, clusterName string, sync IngressHandlerFunc) {
s.Controller().AddClusterScopedFeatureHandler(ctx, enabled, name, clusterName, sync)
}
func (s *ingressClient) AddClusterScopedLifecycle(ctx context.Context, name, clusterName string, lifecycle IngressLifecycle) {
sync := NewIngressLifecycleAdapter(name+"_"+clusterName, true, s, lifecycle)
s.Controller().AddClusterScopedHandler(ctx, name, clusterName, sync)
}
func (s *ingressClient) AddClusterScopedFeatureLifecycle(ctx context.Context, enabled func() bool, name, clusterName string, lifecycle IngressLifecycle) {
sync := NewIngressLifecycleAdapter(name+"_"+clusterName, true, s, lifecycle)
s.Controller().AddClusterScopedFeatureHandler(ctx, enabled, name, clusterName, sync)
}
type IngressIndexer func(obj *v1beta1.Ingress) ([]string, error)
type IngressClientCache interface {
Get(namespace, name string) (*v1beta1.Ingress, error)
List(namespace string, selector labels.Selector) ([]*v1beta1.Ingress, error)
Index(name string, indexer IngressIndexer)
GetIndexed(name, key string) ([]*v1beta1.Ingress, error)
}
type IngressClient interface {
Create(*v1beta1.Ingress) (*v1beta1.Ingress, error)
Get(namespace, name string, opts metav1.GetOptions) (*v1beta1.Ingress, error)
Update(*v1beta1.Ingress) (*v1beta1.Ingress, error)
Delete(namespace, name string, options *metav1.DeleteOptions) error
List(namespace string, opts metav1.ListOptions) (*IngressList, error)
Watch(opts metav1.ListOptions) (watch.Interface, error)
Cache() IngressClientCache
OnCreate(ctx context.Context, name string, sync IngressChangeHandlerFunc)
OnChange(ctx context.Context, name string, sync IngressChangeHandlerFunc)
OnRemove(ctx context.Context, name string, sync IngressChangeHandlerFunc)
Enqueue(namespace, name string)
Generic() controller.GenericController
ObjectClient() *objectclient.ObjectClient
Interface() IngressInterface
}
type ingressClientCache struct {
client *ingressClient2
}
type ingressClient2 struct {
iface IngressInterface
controller IngressController
}
func (n *ingressClient2) Interface() IngressInterface {
return n.iface
}
func (n *ingressClient2) Generic() controller.GenericController {
return n.iface.Controller().Generic()
}
func (n *ingressClient2) ObjectClient() *objectclient.ObjectClient {
return n.Interface().ObjectClient()
}
func (n *ingressClient2) Enqueue(namespace, name string) {
n.iface.Controller().Enqueue(namespace, name)
}
func (n *ingressClient2) Create(obj *v1beta1.Ingress) (*v1beta1.Ingress, error) {
return n.iface.Create(obj)
}
func (n *ingressClient2) Get(namespace, name string, opts metav1.GetOptions) (*v1beta1.Ingress, error) {
return n.iface.GetNamespaced(namespace, name, opts)
}
func (n *ingressClient2) Update(obj *v1beta1.Ingress) (*v1beta1.Ingress, error) {
return n.iface.Update(obj)
}
func (n *ingressClient2) Delete(namespace, name string, options *metav1.DeleteOptions) error {
return n.iface.DeleteNamespaced(namespace, name, options)
}
func (n *ingressClient2) List(namespace string, opts metav1.ListOptions) (*IngressList, error) {
return n.iface.List(opts)
}
func (n *ingressClient2) Watch(opts metav1.ListOptions) (watch.Interface, error) {
return n.iface.Watch(opts)
}
func (n *ingressClientCache) Get(namespace, name string) (*v1beta1.Ingress, error) {
return n.client.controller.Lister().Get(namespace, name)
}
func (n *ingressClientCache) List(namespace string, selector labels.Selector) ([]*v1beta1.Ingress, error) {
return n.client.controller.Lister().List(namespace, selector)
}
func (n *ingressClient2) Cache() IngressClientCache {
n.loadController()
return &ingressClientCache{
client: n,
}
}
func (n *ingressClient2) OnCreate(ctx context.Context, name string, sync IngressChangeHandlerFunc) {
n.loadController()
n.iface.AddLifecycle(ctx, name+"-create", &ingressLifecycleDelegate{create: sync})
}
func (n *ingressClient2) OnChange(ctx context.Context, name string, sync IngressChangeHandlerFunc) {
n.loadController()
n.iface.AddLifecycle(ctx, name+"-change", &ingressLifecycleDelegate{update: sync})
}
func (n *ingressClient2) OnRemove(ctx context.Context, name string, sync IngressChangeHandlerFunc) {
n.loadController()
n.iface.AddLifecycle(ctx, name, &ingressLifecycleDelegate{remove: sync})
}
func (n *ingressClientCache) Index(name string, indexer IngressIndexer) {
err := n.client.controller.Informer().GetIndexer().AddIndexers(map[string]cache.IndexFunc{
name: func(obj interface{}) ([]string, error) {
if v, ok := obj.(*v1beta1.Ingress); ok {
return indexer(v)
}
return nil, nil
},
})
if err != nil {
panic(err)
}
}
func (n *ingressClientCache) GetIndexed(name, key string) ([]*v1beta1.Ingress, error) {
var result []*v1beta1.Ingress
objs, err := n.client.controller.Informer().GetIndexer().ByIndex(name, key)
if err != nil {
return nil, err
}
for _, obj := range objs {
if v, ok := obj.(*v1beta1.Ingress); ok {
result = append(result, v)
}
}
return result, nil
}
func (n *ingressClient2) loadController() {
if n.controller == nil {
n.controller = n.iface.Controller()
}
}
type ingressLifecycleDelegate struct {
create IngressChangeHandlerFunc
update IngressChangeHandlerFunc
remove IngressChangeHandlerFunc
}
func (n *ingressLifecycleDelegate) HasCreate() bool {
return n.create != nil
}
func (n *ingressLifecycleDelegate) Create(obj *v1beta1.Ingress) (runtime.Object, error) {
if n.create == nil {
return obj, nil
}
return n.create(obj)
}
func (n *ingressLifecycleDelegate) HasFinalize() bool {
return n.remove != nil
}
func (n *ingressLifecycleDelegate) Remove(obj *v1beta1.Ingress) (runtime.Object, error) {
if n.remove == nil {
return obj, nil
}
return n.remove(obj)
}
func (n *ingressLifecycleDelegate) Updated(obj *v1beta1.Ingress) (runtime.Object, error) {
if n.update == nil {
return obj, nil
}
return n.update(obj)
}
| []
| []
| []
| [] | [] | go | null | null | null |
minitests/iostandard/features/generate.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017-2020 The Project X-Ray Authors.
#
# Use of this source code is governed by a ISC-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/ISC
#
# SPDX-License-Identifier: ISC
import os
import random
import json
import csv
from collections import defaultdict
try:
random.seed(int(os.getenv("SEED"), 16))
except TypeError:
pass
# =============================================================================
def load_iob_sites(file_name):
"""
Loads IOB site dump from the given CSV file.
"""
# Load the data
with open(file_name, "r") as fp:
data = [row for row in csv.DictReader(fp)]
# Index IOB site data by clock regions
iob_sites = defaultdict(lambda: [])
for site_data in data:
iob_sites[site_data["clock_region"]].append(site_data)
return iob_sites
# =============================================================================
IOBUF_NOT_ALLOWED = [
'HSTL_I',
'HSTL_I_18',
'SSTL18_I',
]
DIFF_MAP = {
'SSTL135': 'DIFF_SSTL135',
'SSTL15': 'DIFF_SSTL15',
}
VREF_ALLOWED = [
'SSTL135',
'SSTL15',
]
def gen_iosettings():
"""
A generator function which yields all possible IO settings combintions.
"""
IOSTANDARDS = (
'LVCMOS12',
'LVCMOS15',
'LVCMOS18',
'LVCMOS25',
'LVCMOS33',
'LVTTL',
'SSTL135',
'SSTL15',
# Those are available but not currently fuzzed.
# 'SSTL135_R',
# 'SSTL15_R',
# 'SSTL18_I',
# 'SSTL18_II',
# 'HSTL_I',
# 'HSTL_I_18',
# 'HSTL_II',
# 'HSTL_II_18',
# 'HSUL_12',
# 'MOBILE_DDR',
)
DRIVES = defaultdict(lambda: [None])
DRIVES.update(
{
"LVTTL": [4, 8, 12, 16, 24],
"LVCMOS12": [4, 8, 12],
"LVCMOS15": [4, 8, 12, 16],
"LVCMOS18": [4, 8, 12, 16, 24],
"LVCMOS25": [4, 8, 12, 16],
"LVCMOS33": [4, 8, 12, 16],
})
SLEWS = ("SLOW", "FAST")
for iostandard in IOSTANDARDS:
# Single ended
for drive in DRIVES[iostandard]:
for slew in SLEWS:
yield {"iostandard": iostandard, "drive": drive, "slew": slew}
# Differential
if iostandard in DIFF_MAP:
for drive in DRIVES[iostandard]:
for slew in SLEWS:
yield {
"iostandard": DIFF_MAP[iostandard],
"drive": drive,
"slew": slew
}
# =============================================================================
def run():
"""
Main.
"""
# Load IOB data
iob_sites = load_iob_sites("iobs-{}.csv".format(os.getenv("PART")))
# Generate IOB site to package pin map and *M site to *S site map.
site_to_pkg_pin = {}
master_to_slave = {}
for region, sites in iob_sites.items():
tiles = defaultdict(lambda: {})
for site in sites:
site_to_pkg_pin[site["site_name"]] = site["pkg_pin"]
if site["site_type"] == "IOB33M":
tiles[site["tile"]]["M"] = site
if site["site_type"] == "IOB33S":
tiles[site["tile"]]["S"] = site
for sites in tiles.values():
master_to_slave[sites["M"]["site_name"]] = sites["S"]["site_name"]
# Generate designs
iosettings_gen = gen_iosettings()
design_index = 0
while True:
print("Design #{}".format(design_index))
num_inp = 0
num_out = 0
num_ino = 0
# Generate clock regions
region_data = []
for region in sorted(list(iob_sites.keys())):
# Get IO bank. All sites from a clock region have the same one.
bank = iob_sites[region][0]["bank"]
# Get IO settings
try:
iosettings = next(iosettings_gen)
except StopIteration:
break
# Get sites
sites = [
(
site["site_name"],
site["site_type"],
)
for site in iob_sites[region]
if site["is_bonded"] and not int(site["is_vref"]) and "SING"
not in site["tile"] and not "PUDC_B" in site["pin_func"]
]
if not len(sites):
continue
# Differential / single ended
if "DIFF" in iosettings["iostandard"]:
# Select 5 random sites (IBUFDS, IBUFDS, OBUFDS, OBUFDS, IOBUFDS)
site_names = [s[0] for s in sites if s[1] == "IOB33M"]
used_sites = random.sample(site_names, 5)
unused_sites = list(set(site_names) - set(used_sites))
num_inp += 4
num_out += 4
num_ino += 2
else:
# Select 5 random sites (IBUF, IBUF, OBUF, OBUF, IOBUF)
site_names = [s[0] for s in sites]
used_sites = random.sample(site_names, 5)
unused_sites = list(set(site_names) - set(used_sites))
num_inp += 2
num_out += 2
num_ino += 1
# Store data
region_data.append(
{
"region": region,
"bank": bank,
"iosettings": iosettings,
"unused_sites": unused_sites,
"input": used_sites[0:2],
"output": used_sites[2:4],
"inout": used_sites[4:5],
})
print("", region, iosettings)
# No more
if len(region_data) == 0:
break
print("----")
# Generate the design
verilog = """
module top (
input wire [{num_inp}:0] inp,
inout wire [{num_ino}:0] ino,
output wire [{num_out}:0] out
);
""".format(num_inp=num_inp - 1, num_ino=num_ino - 1, num_out=num_out - 1)
tcl = ""
inp_idx = 0
out_idx = 0
ino_idx = 0
for i, data in enumerate(region_data):
is_diff = "DIFF" in data["iosettings"]["iostandard"]
use_ino = data["iosettings"]["iostandard"] not in IOBUF_NOT_ALLOWED
iostandard = data["iosettings"]["iostandard"]
drive = data["iosettings"]["drive"]
slew = data["iosettings"]["slew"]
ibuf_param_str = ".IOSTANDARD(\"{}\")".format(iostandard)
obuf_param_str = str(ibuf_param_str)
if drive is not None:
obuf_param_str += ", .DRIVE({})".format(drive)
if slew is not None:
obuf_param_str += ", .SLEW(\"{}\")".format(slew)
bank = data["bank"]
vref = "0.75" # FIXME: Maybe loop over VREFs too ?
keys = {
"region": data["region"],
"ibuf_0_loc": data["input"][0],
"ibuf_1_loc": data["input"][1],
"obuf_0_loc": data["output"][0],
"obuf_1_loc": data["output"][1],
"iobuf_loc": data["inout"][0],
"inp_0_p": inp_idx,
"inp_0_n": inp_idx + 2,
"inp_1_p": inp_idx + 1,
"inp_1_n": inp_idx + 3,
"out_0_p": out_idx,
"out_0_n": out_idx + 2,
"out_1_p": out_idx + 1,
"out_1_n": out_idx + 3,
"ino_p": ino_idx,
"ino_n": ino_idx + 1,
"ibuf_param_str": ibuf_param_str,
"obuf_param_str": obuf_param_str,
}
if is_diff:
inp_idx += 4
out_idx += 4
ino_idx += 2
else:
inp_idx += 2
out_idx += 2
ino_idx += 1
# Set VREF if necessary
if iostandard in VREF_ALLOWED:
tcl += "set_property INTERNAL_VREF {} [get_iobanks {}]\n".format(
vref, bank)
# Single ended
if not is_diff:
tcl += "set_property PACKAGE_PIN {} [get_ports inp[{}]]\n".format(
site_to_pkg_pin[keys["ibuf_0_loc"]], keys["inp_0_p"])
tcl += "set_property PACKAGE_PIN {} [get_ports inp[{}]]\n".format(
site_to_pkg_pin[keys["ibuf_1_loc"]], keys["inp_1_p"])
tcl += "set_property PACKAGE_PIN {} [get_ports out[{}]]\n".format(
site_to_pkg_pin[keys["obuf_0_loc"]], keys["inp_0_p"])
tcl += "set_property PACKAGE_PIN {} [get_ports out[{}]]\n".format(
site_to_pkg_pin[keys["obuf_1_loc"]], keys["inp_1_p"])
tcl += "set_property PACKAGE_PIN {} [get_ports ino[{}]]\n".format(
site_to_pkg_pin[keys["iobuf_loc"]], keys["ino_p"])
verilog += """
// {region}
wire inp_0_{region};
wire inp_1_{region};
wire out_0_{region};
wire out_1_{region};
wire ino_i_{region};
wire ino_o_{region};
wire ino_t_{region};
""".format(**keys)
verilog += """
(* KEEP, DONT_TOUCH *)
IBUF # ({ibuf_param_str}) ibuf_0_{region} (
.I(inp[{inp_0_p}]),
.O(inp_0_{region})
);
(* KEEP, DONT_TOUCH *)
IBUF # ({ibuf_param_str}) ibuf_1_{region} (
.I(inp[{inp_1_p}]),
.O(inp_1_{region})
);
(* KEEP, DONT_TOUCH *)
OBUF # ({obuf_param_str}) obuf_0_{region} (
.I(out_0_{region}),
.O(out[{out_0_p}])
);
(* KEEP, DONT_TOUCH *)
OBUF # ({obuf_param_str}) obuf_1_{region} (
.I(out_1_{region}),
.O(out[{out_1_p}])
);
""".format(**keys)
if use_ino:
verilog += """
(* KEEP, DONT_TOUCH *)
IOBUF # ({obuf_param_str}) iobuf_{region} (
.I(ino_i_{region}),
.O(ino_o_{region}),
.T(ino_t_{region}),
.IO(ino[{ino_p}])
);
assign out_0_{region} = inp_0_{region};
assign out_1_{region} = ino_o_{region};
assign ino_i_{region} = inp_0_{region};
assign ino_t_{region} = inp_1_{region};
""".format(**keys)
else:
verilog += """
assign out_0_{region} = inp_0_{region};
assign out_1_{region} = inp_1_{region};
assign ino[{ino}] = 1'b0;
""".format(**keys)
# Differential
else:
tcl += "set_property PACKAGE_PIN {} [get_ports inp[{}]]\n".format(
site_to_pkg_pin[keys["ibuf_0_loc"]], keys["inp_0_p"])
tcl += "set_property PACKAGE_PIN {} [get_ports inp[{}]]\n".format(
site_to_pkg_pin[master_to_slave[keys["ibuf_0_loc"]]],
keys["inp_0_n"])
tcl += "set_property PACKAGE_PIN {} [get_ports inp[{}]]\n".format(
site_to_pkg_pin[keys["ibuf_1_loc"]], keys["inp_1_p"])
tcl += "set_property PACKAGE_PIN {} [get_ports inp[{}]]\n".format(
site_to_pkg_pin[master_to_slave[keys["ibuf_1_loc"]]],
keys["inp_1_n"])
tcl += "set_property PACKAGE_PIN {} [get_ports out[{}]]\n".format(
site_to_pkg_pin[keys["obuf_0_loc"]], keys["inp_0_p"])
tcl += "set_property PACKAGE_PIN {} [get_ports out[{}]]\n".format(
site_to_pkg_pin[master_to_slave[keys["obuf_0_loc"]]],
keys["inp_0_n"])
tcl += "set_property PACKAGE_PIN {} [get_ports out[{}]]\n".format(
site_to_pkg_pin[keys["obuf_1_loc"]], keys["inp_1_p"])
tcl += "set_property PACKAGE_PIN {} [get_ports out[{}]]\n".format(
site_to_pkg_pin[master_to_slave[keys["obuf_1_loc"]]],
keys["inp_1_n"])
tcl += "set_property PACKAGE_PIN {} [get_ports ino[{}]]\n".format(
site_to_pkg_pin[keys["iobuf_loc"]], keys["ino_p"])
tcl += "set_property PACKAGE_PIN {} [get_ports ino[{}]]\n".format(
site_to_pkg_pin[master_to_slave[keys["iobuf_loc"]]],
keys["ino_n"])
verilog += """
// {region}
wire inp_0_{region};
wire inp_1_{region};
wire out_0_{region};
wire out_1_{region};
wire ino_i_{region};
wire ino_o_{region};
wire ino_t_{region};
""".format(**keys)
verilog += """
(* KEEP, DONT_TOUCH *)
IBUFDS # ({ibuf_param_str}) ibufds_0_{region} (
.I(inp[{inp_0_p}]),
.IB(inp[{inp_0_n}]),
.O(inp_0_{region})
);
(* KEEP, DONT_TOUCH *)
IBUFDS # ({ibuf_param_str}) ibufds_1_{region} (
.I(inp[{inp_1_p}]),
.IB(inp[{inp_1_n}]),
.O(inp_1_{region})
);
(* KEEP, DONT_TOUCH *)
OBUFDS # ({obuf_param_str}) obufds_0_{region} (
.I(out_0_{region}),
.O(out[{out_0_p}]),
.OB(out[{out_0_n}])
);
(* KEEP, DONT_TOUCH *)
OBUFDS # ({obuf_param_str}) obufds_1_{region} (
.I(out_1_{region}),
.O(out[{out_1_p}]),
.OB(out[{out_1_n}])
);
""".format(**keys)
if use_ino:
verilog += """
(* KEEP, DONT_TOUCH *)
IOBUFDS # ({obuf_param_str}) iobufds_{region} (
.I(ino_i_{region}),
.O(ino_o_{region}),
.T(ino_t_{region}),
.IO(ino[{ino_p}]),
.IOB(ino[{ino_n}])
);
assign out_0_{region} = inp_0_{region};
assign out_1_{region} = ino_o_{region};
assign ino_i_{region} = inp_0_{region};
assign ino_t_{region} = inp_1_{region};
""".format(**keys)
else:
verilog += """
assign out_0_{region} = inp_0_{region};
assign out_1_{region} = inp_1_{region};
assign ino[{ino_p}] = 1'b0;
assign ino[{ino_n}] = 1'b0;
""".format(**keys)
verilog += "endmodule"
# Write verilog
fname = "design_{:03d}.v".format(design_index)
with open(fname, "w") as fp:
fp.write(verilog)
# Write TCL
fname = "design_{:03d}.tcl".format(design_index)
with open(fname, "w") as fp:
fp.write(tcl)
# Write JSON
fname = "design_{:03d}.json".format(design_index)
# Convert Vivado site names to fasm-style TILE.SITE names.
for data in region_data:
type_to_loc = {
"IOB33": "IOB_Y0",
"IOB33M": "IOB_Y0",
"IOB33S": "IOB_Y1"
}
site_to_loc = {
s["site_name"]: "{}.{}".format(
s["tile"], type_to_loc[s["site_type"]])
for s in iob_sites[data["region"]]
}
for l in ["input", "output", "inout", "unused_sites"]:
data[l] = [site_to_loc[s] for s in data[l]]
# Write design settings to JSON
with open(fname, "w") as fp:
json.dump(region_data, fp, sort_keys=True, indent=1)
design_index += 1
if __name__ == "__main__":
run()
| []
| []
| [
"SEED",
"PART"
]
| [] | ["SEED", "PART"] | python | 2 | 0 | |
quex/engine/state_machine/algorithm/TEST/test-nfa-to-dfa.py | #! /usr/bin/env python
import sys
import os
sys.path.insert(0, os.environ["QUEX_PATH"])
from quex.engine.state_machine.TEST_help.some_dfas import *
from quex.engine.state_machine.core import *
import quex.engine.state_machine.construction.repeat as repeat
import quex.engine.state_machine.algorithm.nfa_to_dfa as nfa_to_dfa
if "--hwut-info" in sys.argv:
print "NFA: Conversion to DFA (subset construction)"
sys.exit(0)
print "_______________________________________________________________________________"
print "Example A:"
sm = DFA()
n0 = sm.init_state_index
n1 = sm.add_transition(n0, ord('a'), AcceptanceF=True)
sm = repeat.do(sm, 1)
dfa = nfa_to_dfa.do(sm)
print dfa
print "_______________________________________________________________________________"
print "Example B:"
sm = DFA()
n0 = sm.init_state_index
n1 = sm.add_transition(n0, ord('a'), AcceptanceF=True)
sm = repeat.do(sm)
dfa = nfa_to_dfa.do(sm)
print dfa
print "_______________________________________________________________________________"
print "Example C:"
# (*) create a simple state machine:
# ,--<------------ eps ------------------.
# / \
# | ,- eps -->(4)-- 'b' -->(5)-- eps -. |
# \ / \ /
# (0)-- 'a' -->(1)-- eps -->(2)-- eps -->(3) (8)-- eps -->((9))
# \ \ / /
# \ '- eps -->(6)-- 'c' -->(7)-- eps -' /
# \ /
# '----------------------- eps ----------->---------------'
#
# ((9)) is the acceptance state.
#
sm = DFA()
n0 = sm.init_state_index
n1 = sm.add_transition(n0, ord('a'))
n2 = sm.add_epsilon_transition(n1)
n3 = sm.add_epsilon_transition(n2)
#
n4 = sm.add_epsilon_transition(n3)
n5 = sm.add_transition(n4, ord('b'))
#
n6 = sm.add_epsilon_transition(n3)
n7 = sm.add_transition(n6, ord('c'))
n8 = sm.add_epsilon_transition(n7)
#
sm.add_epsilon_transition(n5, n8)
#
n9 = sm.add_epsilon_transition(n8, RaiseAcceptanceF=True)
#
sm.add_epsilon_transition(n2, n9)
sm.add_epsilon_transition(n8, n3)
# (*) create the DFA from the specified NFA
dfa = nfa_to_dfa.do(sm)
print dfa
print "_______________________________________________________________________________"
print "Example D:"
tmp = repeat.do(sm3)
## print tmp.get_string(NormalizeF=False)
dfa = nfa_to_dfa.do(tmp)
print dfa
| []
| []
| [
"QUEX_PATH"
]
| [] | ["QUEX_PATH"] | python | 1 | 0 | |
main.go | /*
Copyright 2016 The MITRE Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"flag"
"fmt"
"os"
"github.com/gin-gonic/gin"
"github.com/intervention-engine/fhir/auth"
fhirSvr "github.com/intervention-engine/fhir/server"
"github.com/mitre/ptmatch/middleware"
"github.com/mitre/ptmatch/server"
)
func main() {
// Check environment variable for a linked MongoDB container
mongoHost := os.Getenv("MONGO_PORT_27017_TCP_ADDR")
if mongoHost == "" {
mongoHost = "localhost"
}
s := fhirSvr.NewServer(mongoHost)
assetPath := flag.String("assets", "", "Path to static assets to host")
jwkPath := flag.String("heartJWK", "", "Path the JWK for the HEART client")
clientID := flag.String("heartClientID", "", "Client ID registered with the OP")
opURL := flag.String("heartOP", "", "URL for the OpenID Provider")
sessionSecret := flag.String("secret", "", "Secret for the cookie session")
flag.Parse()
var authConfig auth.Config
if *jwkPath != "" {
if *clientID == "" || *opURL == "" {
fmt.Println("You must provide both a client ID and OP URL for HEART mode")
return
}
secret := *sessionSecret
if secret == "" {
secret = "reallySekret"
}
authConfig = auth.HEART(*clientID, *jwkPath, *opURL, secret)
} else {
authConfig = auth.None()
}
recMatchWatch := middleware.PostProcessRecordMatchResponse()
s.AddMiddleware("Bundle", recMatchWatch)
ar := func(e *gin.Engine) {
server.Setup(e)
if *assetPath != "" {
e.StaticFile("/", fmt.Sprintf("%s/index.html", *assetPath))
e.Static("/assets", fmt.Sprintf("%s/assets", *assetPath))
}
}
s.AfterRoutes = append(s.AfterRoutes, ar)
s.Run(fhirSvr.Config{Auth: authConfig,
ServerURL: "http://localhost:3001",
DatabaseName: "fhir"})
}
| [
"\"MONGO_PORT_27017_TCP_ADDR\""
]
| []
| [
"MONGO_PORT_27017_TCP_ADDR"
]
| [] | ["MONGO_PORT_27017_TCP_ADDR"] | go | 1 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.