vendredi 1 janvier 2021

Python Flask MySQL database schema for each environment

It is my first time working with a development, production and testing environment.

I have created three instances of my Flask application's database schema in MySQLWorkbench.

enter image description here

An environment variable FLASK_CONFIG must be set to any of the three environments.

This will determine which database my Flask app connects to.

My question simply is whether this is the right approach and, if not, what is a better solution?

Here is my code.

def create_app(config_name):
    """
        PARAM
        config_name    'development', 'production', or 'testing'
    """

    instance_path = os.path.join(os.path.dirname(__file__), 'instance')

    app = Flask(__name__, instance_path=instance_path)

    app.config.from_object(app_config[config_name])
    app.config.from_pyfile('config.py')

    app.config['SECRET_KEY'] = 'a7e6f8131a635119ca1ce2c82c7206e2c07072a9dd264189'

    if(config_name=='development'):
        database = "cbl_dev"
    elif(config_name=='production'):
        database = "cbl_prod"
    elif(config_name=='testing'):
        database = "cbl_test"
    else:
        print("Invalid value: '{}' provided for env variable FLASK_CONFIG".format(config_name))

    db = mysql.connector.connect(
        host="localhost",
        user="root",
        password="12345678",
        database=database
    )

Rspec expectation triggering twice

Getting some odd behavior when testing a custom class in Rspec (version 3.9)

Code

class AlertMaster
    def initialize(params = {})
        ...
    end

    def send_alert
        1.upto(2) do |attempt|
            begin
                self.alert_me
                break
            rescue => e
                if attempt == 2
                    puts ">> here"
                    puts attempt
                    Rails.logger.fatal "Alert error - #{e.message}"
                end
            end
        end
    end
end

RSpec

    describe "send_alert" do
        before do
            @at = AlertMaster.new
        end
        describe "catches appropriately" do
            describe "first time succeeds" do
                it "should not log error" do
                    expect(@at).to receive(:alert_me).and_return(true)
                    expect(Rails.logger).to_not receive(:fatal)

                    @at.send_alert
                end
            end

            describe "first time fails, second time succeeds" do
                it "should not log error" do
                    expect(@at).to receive(:alert_me).and_raise("oops")
                    expect(@at).to receive(:alert_me).and_return(true)
                    expect(Rails.logger).to_not receive(:fatal)

                    @at.send_alert
                end
            end

            ####### FAILING SPEC
            describe "first time fails, second time fails" do
                it "should log error" do
                    expect(@at).to receive(:alert_me).and_raise("oops")
                    expect(Rails.logger).to receive(:fatal).with("Alert error - oops")

                    @at.send_alert
                end
            end
        end
    end

The last spec fails because Rails.logger is called twice. Console log shows the puts statements I put in correctly only trigger on last attempt. Failing spec output:

>> here
2

...

Failure/Error: expect(@at).to receive(:alert_me).and_raise("oops")
     
       (#<AlertMaster:0x00007ffca7edd180 ...).alert_me(*(any args))
           expected: 1 time with any arguments
           received: 2 times with any arguments

Have a persistent browser configuration for multiple runs of a Selenium script

I have a web application test script which is written in Python using Selenium and the Firefox webdriver.

I would like to have my browser's configuration (especially cookies and localStorage) persisted across multiple runs of the script. I can use the firefox_profile with a path, but that clones the directory and does not write back changes it has made during the script runtime, the actual changes are only done within a temporary directory which is discarded after the driver exits.

Does a solution exist for my problem? I would prefer to stick with Firefox, but if it works with a different browser, that would be fine as well.

Run Test with coverage

What is going on guys?The tests with coverage does not work -it throws exeptions like this

Exception in thread "main" java.lang.reflect.InvocationTargetException at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at java.instrument/sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:513) at java.instrument/sun.instrument.InstrumentationImpl.loadClassAndCallPremain(InstrumentationImpl.java:525) Caused by: java.lang.reflect.InvocationTargetException at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at com.intellij.rt.coverage.main.CoveragePremain.premain(CoveragePremain.java:35) at com.intellij.rt.coverage.main.CoveragePremain.premain(CoveragePremain.java:28) ... 6 more Caused by: java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1 at com.intellij.rt.coverage.instrumentation.Instrumentator.performPremain(Instrumentator.java:55) at com.intellij.rt.coverage.instrumentation.Instrumentator.premain(Instrumentator.java:33) ... 12 more *** java.lang.instrument ASSERTION FAILED ***: "result" with message agent load/premain call failed at ./src/java.instrument/share/native/libinstrument/JPLISAgent.c line: 422 FATAL ERROR in native method: processing of -javaagent failed, processJavaStart failed

it happens with gradle wrapper and local gradle ,dnt have idea whats going wrong

Default tests don't work in a new React Native 0.59.10

I need to use a old React Native version (0.59.10)

When I init a new project like this

npx react-native-cli init rnTestTest --version 0.59.10

and then I run the test yarn test

the error is:

Test suite failed to run

    Cannot find module 'setupDevtools' from 'node_modules/react-native/jest/setup.js'

      at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:306:11)
      at Object.<anonymous> (node_modules/react-native/jest/setup.js:3:15)

Why is there this error?

What is the best practice to test API endpoints that use 3rd party APIs? [closed]

I have the following workflow:

Step 1: The user uploads information using the first endpoint -> the information will be stored in a database

Step 2: The user uploads a document using the second endpoint -> the document will be uploaded to AWS S3

Step 3: The user calls the 3rd endpoint - Both the document uploaded to S3 and the information will be sent to a 3rd party API

My goal is to write tests to make sure everything works fine. Currently, I test all endpoints separately, but do not stub the 3rd party APIs, so for example I upload documents to S3 during the test for Step 2. Is this considered as bad practice?

My tech stack is Typescript, Mocha and Chai.

Passing a variable's value from a test to the next one in Cypress

Is it possible to pass a variable from one it test to the next it test ? The following using cy.wrap does not work:

it('test1', () => {
 const var1 = 'test'
 cy.wrap(var1).as('var1Alias')
})
it('test2', () => {
 cy.log('@var1Alias')
})

I've checked old stackoverflow questions similar to mine such as this: Use variables across multiple 'it' statements to track change in Cypress and the difference is that the variable is declared globally outside the tests (it). Hence, you can always replace the variable.

My specific issue is that the dependency on the variable's value from the previous test. I know Cypress best practice suggests that tests shouldn't be sequential but this is a common scenario in my opinion to properly categorise tests in a readable manner.

For context, my first test is calling a POST endpoint then the response body will be passed as a query parameter for my GET endpoint in the succeeding test.

Current workarounds (while I am still looking for a better option):

  • Use fixtures and write then retrieve (slower runtime)
  • Use localstorage-commands plugin (I have multiple variables to retrieve)
  • Include the succeeding test inside the arrow function of the previous test (thus combination both tests in one test)