lundi 31 août 2020

Can Espresso test cases recording and test cases creation be done without Android Studio?

My main aim is to create a tool, which gives a user the facility to create their own tests by simply performing the required steps on the device, and then save the test.

I know this can be done using Android Studio, with manual intervention though. Can this be done without android studio? Can this be done at all? Should I use some other tool for this purpose?

Any help is appreciated.

Unable to mock a method which takes an interface

I have a service in my Spring Boot Project in which i have method which takes an interface.

interface IT {}
class AService {
 public String method(IT it) {}
}

I have two classes which implements that interface.

class AIT implements IT {}
class BIT implements IT {}

I am using this service method in some other service passing the AIT/BIT class object according to my need.

Now, I am writing the test cases for other service mocking the Service

public class OtherServiceTests {

    @MockBean
    private Service service;

  
    @Before
    public void setUp() {
    // none of these mocks working
        Mockito.when(service.method(Mockito.any()))
                .thenReturn("");
    Mockito.when(service.method(Mockito.any(IT.class)))
                .thenReturn("");
    Mockito.when(service.method(Mockito.any(BIT.class)))
                .thenReturn("");
    Mockito.when(service.method(Mockito.any(AIT.class)))
                .thenReturn("");
    // all returing to NullPointerException

    
        otherService = new OtherSerice();
    }

}
 

None of these mocks are working for this method only. Other mocks are working fine. It is returning NullPointerException which makes the tests fail.

I am new to testing using mockito. If anyone can guide me for this solution than this will be very helpful for me.

Print spec reporter output to file in WebdriverIO?

I'm trying to find a way to print spec reporter output to a text file once the test suite is complete. I'm using WebdriverIO but none of the completion callbacks seem to provide any access to the actual report output. There's also no documentation on any config variable you can pass in to set a file output. There an outputDir option but it only writes the log before the actual report to the selected location.

Entering bulk test data into Desktop applications

The company I work for has a suite of 5 Desktop Applications, lets call them Application 1-5. We work in Windows. Occasionally there is a need to enter a significant amount of test data in QA, in Applications 1-3, for use in testing Applications 4 & 5. I am trying to figure out the most efficient way to do this. Out of the 5 applications, only one of them has a API Service call we can use, to enter bulk data through JMeter. Also, we can't do this via SQL in the back-end.

We currently use TestComplete to test our Desktop Applications and its fine for that purpose, but its not efficient at all for entering a significant amount of test data, as far as I know.

I have looked into winappdriver as a possibility, but not sure how good it is for that purpose either.

Any suggestions?

Integration test with mysql, postgres & nodejs API

I need to run integration test that hits the MySQL, Postgres database, update & delete records in the DB, and a NodeJS API.

I'm not sure if Jest will be enough for this or if Supertest will be enough either. I want to run CRUD operations in the DB while testing. Are there recommendations for this or guides?

Use Spring's TestRestTemplate to test an endpoint that returns a generic type

I'm trying to use Spring's TestRestTemplate to test an endpoint that returns a List<Foo<Bar>>. Currently, the code looks like this:

ResponseEntity<List<Foo<Bar>>> response = this.restTemplate.exchange(
        ApiUrls.GET_FOOS_URL,
        HttpMethod.GET, 
        null,
        new ParameterizedTypeReference<List<Foo<Bar>>>() {});

There ought to be a method available on TestRestTemplate which simplifies calling this endpoint. I've tried using getForEntity instead, e.g.

ResponseEntity<List<Foo<Bar>>> response = this.restTemplate.getForEntity(
        ApiUrls.GET_FOOS_URL, List.class);

But this doesn't compile because List.class doesn't correspond to List<Foo<Bar>> and there's no way I can create a Class object which does (because of type erasure).

Is there a simpler replacement for restTemplate.exchange that I can use in this case which won't generate compiler warnings or require casting?

Jest Angular test private method in ngAfterViewInit()

How would I need test a private method which in inside my ngAfterViewInit. I can't test selectUsers() directly since it is a private method.

ngAfterViewInit() {
    timer(0).subscribe(() => {
        this.selectUsers();
    });
}

private selectUsers() {
   # ...
}

JMeter - Active threats over time

I am new to JMeter. I am working with it the last month. The problem that i am facing is with the graph that shows the active threats over time. What i want to achieve is a linear graph that will show that every 2 seconds a new threat is entering the application and do whatever it needs to do. My set up is as follow:

enter image description here

I can not add loop count to infinite as each user is executing different tasks that can be executed only once. It can not reuse the data and hit the services/tasks again with the use of the same user.

The process is:

  • Login
  • Get Requests
  • Post requests

If i execute my scenario i am getting the following graph:

enter image description here

What i need to do in order to get something like the below:

enter image description here

Cant test copy from 'copy-to-clipboard' with sinon

I'm trying to test my component with Sinon. It seems I can't simulate the click function which is in the TableMenu component. TableMenu.jsx

import copy from 'copy-to-clipboard';

const TableMenu = ({onClick, onHide, rowId}) => (
    <MenuPopover
        onClick={onClick}
        onHide={onHide}>
        <MenuPopover.Item id={1} onClick={() => copy(rowId)} label='Copy'/>
    </MenuPopover>
);

TableMenu.test.js

import copy from 'copy-to-clipboard';
jest.mock('copy-to-clipboard', () => sinon.spy());

it('check method onCopy called', () => {
    const wrapper = shallow(<TableMenu {...props}/>);
    wrapper.find(MenuPopover.Item).last().props().onClick()
    expect(copy.calledOnce).to.eql(true);
});

I'm getting the below error:

Error: Not implemented: window.prompt
    at module.exports (C:\adm\node_modules\jsdom\lib\jsdom\browser\not-implemented.js:9:17)
    at Window.prompt (C:\adm\node_modules\jsdom\lib\jsdom\browser\Window.js:458:7)
    at copy (C:\adm\node_modules\copy-to-clipboard\index.js:58:14)
    at Object.onClick (C:\adm\src\TableMenu/TableMenu.jsx:19:43)
    ...
    ...

TypeError: reselectPrevious is not a function
    at copy (node_modules\copy-to-clipboard\index.js:72:5)
    at Object.onClick (src\TableMenu/TableMenu.jsx:19:43)
    at Context.<anonymous> (src\TableMenu/TableMenu.test.js:62:62)
    at process.topLevelDomainCallback (domain.js:121:23)

How can I validate Postman API response contains the String mentioned CSV file

When running a Postman requests through Collection runner by passing the values contain in a CSV file for the input parameters, how can I validate each response contain the String text mentioned in the expected value column in this CSV file. I also want to write each response to the Actual result column in this CSV file.

enter image description here

For example after executing the 1st request in the above pic using the Postman collection runner I want to validate the response contains 'Sydney' as a text value and give the result as 'PASS' or 'FAIL' as well as write the actual response to the Actual result column of the above file. This should continue till the last row of the CSV file.

Use Spring's TestRestTemplate to test an endpoint that returns a generic type

I'm trying to use Spring's TestRestTemplate to test an endpoint that returns a List<Foo<Bar>>. Currently, the code looks like this:

ResponseEntity<List<Foo<Bar>>> response = this.restTemplate.exchange(
        ApiUrls.GET_FOOS_URL,
        HttpMethod.GET, 
        null,
        new ParameterizedTypeReference<List<Foo<Bar>>>() {});

There ought to be a method available on TestRestTemplate which simplifies calling this endpoint. I've tried using getForEntity instead, e.g.

ResponseEntity<List<Foo<Bar>>> response = this.restTemplate.getForEntity(
        ApiUrls.GET_FOOS_URL, List.class);

But this doesn't compile because List.class doesn't correspond to List<Foo<Bar>> and there's no way I can create a Class object which does (because of type erasure).

Is there a simpler replacement for restTemplate.exchange that I can use in this case which won't generate compiler warnings or require casting?

JEST Expected: true Received: false

I have a problem in testing the components.

So i want to test a modal, however, when i try to test it, i get this error

expect(received).toBe(expected) // Object.is equality

    Expected: true
    Received: false

My modal is

<b-modal
        id="plugin-google-analytics-webmag"
        size="lg"
        centered
        ok-only
        hide-header-close
        no-close-on-esc
        no-close-on-backdrop
        
    >

and my test is

it ('opens a modal', (done) => {
    const button = wrapper.findAll('[data-qa="button"]');
    const modal = wrapper.findAll('#plugin-google-analytics-webmag');
    expect(button.exists()).toBe(true);
    expect(button.is('button')).toBe(true);
    expect(modal.exists()).toBe(true);
    expect(modal.is('div')).toBe(true);

    expect(modal.isVisible()).toBe(false);
    button.trigger('click');

    Vue.nextTick(() => {
      expect(modal.isVisible()).toBe(true);
      done();
    });

I use the code from How do you open a bootstrap-vue modal with vue-test-utils?

Do you have some suggestions?

Robot Framework Variable Attribute In Seperate File Not Storing Attribute To Be Used ElseWhere

Variable attribute not getting passed into other file.

I have my variables for element locators stored in one file and I have assertions done in another file which has worked fine until now and separates things out nicely. I am doing an assertion to check that an element exists and its attribute(value) is not blank. If I write it on one page as follows it works perfectly. This use the selenium library keywords should not be equal and get data attribute just to note.

${EXAMPLE}  get data attribute  class=test test-data
should not be equal  ${EXAMPLE}  ${EMPTY}

But If I separate them out into different files. So a locators.robot file:

 #Locater File
 ${EXAMPLE}  get data attribute  class=test[test-data]

And an Assertions.robot:

 #Assertion File
 should not be equal  ${EXAMPLE}  ${EMPTY}

It stops working. If I use a selenium library assertion like page should contain element then it works, so I know I am pulling in the other Resource correctly. I have a feeling I may need to store the attribute in another variable somehow and actually assert against that. Any ideas would be great. Thanks in advance.

Functional Testing Best Practices In Php

I am writing the functional test in Symfony and all things are OK but i have am Api which return about 30 properties I want to know is it necessary to check all of these fileds or that is OK to write assertion randomly for them because I just read them from a table and don't do any special things on them.
Thanks

show flutter test coverage

I am a bit new to testing world in flutter. what I want to achieve is to determine my test coverage in flutter.

but I don't know any way to determine my test coverage , any help is appreciated.

Thanks.

Python unit tests for tenacity based retry logic

I am wondering if there is a way to test the retry logic provided by tenacity; e.g. I'd like to test a decorated method is successful only on a retry (or a given number of retries). In other words, is there a pattern for mocking failures for tenacity?

dimanche 30 août 2020

Testing text contrast in react-native

Not actually sure, it is should be done with jest. But how to ensure, that found text on the screen is visible? There are my short files for example: (setted color of text to be same as bg, but it passes)enter image description here

in text format to you, if you want copy/paste

export default () => (
  <SafeAreaView style={ style.container }>
    <Text style={ style.text }>loading..</Text>
  </SafeAreaView>
)

,

test('In Loading screen, there is "loading" visible label', () => {
  const { getByText } = render(
    <Loading />
  )

  getByText(/loading/) // exact 1 (not 0, not >)
})

How to test if an object is a string? [duplicate]

I have a list of objects that I need to remove all strings from, leaving me with only integers in the list.

The problem I'm having is that some of the strings only contain numbers, for example "1" is a string. If I use is in an if statement if (listOfItems[i] is string) will not work on "1" I've also tried GetType() and typeof as shown below but I'm having the same problem.

How do I test if an object is a string, even if that string contain numbers?

public static class Filter
    {
        public static IEnumerable<int> GetIntegersFromList(List<object> listOfItems)
        {
            for (int i = 0; i < listOfItems.Count; i++)
            {
                if (listOfItems[i].GetType() != typeof(int))
                    listOfItems.RemoveAt(i);
            }
            List<int> listOfInts = new List<int>();
            for (int i = 0; i < listOfItems.Count; i++)
            {
                listOfInts.Add((int)listOfItems[i]);
            }
            return listOfInts;
        }
    }

Flutter running test example in application

Hi hope everyone stays safe. Thanks for this nice community. I have done my Flutter&Dart app and it works. But i need to run some test on flutter app so I found one example that is similar to mine on one of the files that I created in my flutter app and it is unit testing. Now I watched and read the flutter docs for widget testing or some other examples for unit testing that would help me. But no luck so if there is someone that could show me an example on my dart file and the code down below.

import 'dart:convert';
import 'dart:async';
import 'dart:io';

import 'package:http_parser/http_parser.dart';
import 'package:aplikacija/models/location_data.dart';
import 'package:scoped_model/scoped_model.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:rxdart/subjects.dart';
import 'package:mime/mime.dart';

import '../models/product.dart';
import '../models/user.dart';
import '../models/auth.dart';
import '../models/location_data.dart';

mixin ConnectedProductsModel on Model {
  List<Product> _products = [];
  String _selProductId;
  User _authenticatedUser;
  bool _isLoading = false;
}

mixin ProductsModel on ConnectedProductsModel {
  bool _showFavorites = false;

  List<Product> get allProducts {
    return List.from(_products);
  }

  List<Product> get displayedProducts {
    if (_showFavorites) {
      return _products.where((Product product) => product.isFavorite).toList();
    }
    return List.from(_products);
  }

  int get selectedProductIndex {
    return _products.indexWhere((Product product) {
      return product.id == _selProductId;
    });
  }

  String get selectedProductId {
    return _selProductId;
  }

  Product get selectedProduct {
    if (selectedProductId == null) {
      return null;
    }
    return _products.firstWhere((Product product) {
      return product.id == _selProductId;
    });
  }

  bool get displayFavoritesOnly {
    return _showFavorites;
  }

  Future<Map<String, dynamic>> uploadImage(File image,
      {String imagePath}) async {
    final mimeTypeData = lookupMimeType(image.path).split('/');
    final imageUploadRequest = http.MultipartRequest(
        'POST',
        Uri.parse(
            'https://us-central1-flutter-aplikacija.cloudfunctions.net/storeImage'));
    final file = await http.MultipartFile.fromPath(
      'image',
      image.path,
      contentType: MediaType(
        mimeTypeData[0],
        mimeTypeData[1],
      ),
    );
    imageUploadRequest.files.add(file);
    if (imagePath != null) {
      imageUploadRequest.fields['imagePath'] = Uri.encodeComponent(imagePath);
    }
    imageUploadRequest.headers['Authorization'] =
        'Bearer ${_authenticatedUser.token}';

    try {
      final streamedResponse = await imageUploadRequest.send();
      final response = await http.Response.fromStream(streamedResponse);
      if (response.statusCode != 200 && response.statusCode != 201) {
        print('Something went wrong');
        print(json.decode(response.body));
        return null;
      }
      final responseData = json.decode(response.body);
      return responseData;
    } catch (error) {
      print(error);
      return null;
    }
  }

  Future<bool> addProduct(String title, String description, File image,
      double price, LocationData locData) async {
    _isLoading = true;
    notifyListeners();
    final uploadData = await uploadImage(image);

    if (uploadData == null) {
      print('Upload failed!');
      return false;
    }

    final Map<String, dynamic> productData = {
      'title': title,
      'description': description,
      'price': price,
      'userEmail': _authenticatedUser.email,
      'userId': _authenticatedUser.id,
      'imagePath': uploadData['imagePath'],
      'imageUrl': uploadData['imageUrl'],
      'loc_lat': locData.latitude,
      'loc_lng': locData.longitude,
      'loc_address': locData.address
    };
    try {
      final http.Response response = await http.post(
          'https://flutter-aplikacija.firebaseio.com/products.json?auth=${_authenticatedUser.token}',
          body: json.encode(productData));

      if (response.statusCode != 200 && response.statusCode != 201) {
        _isLoading = false;
        notifyListeners();
        return false;
      }
      final Map<String, dynamic> responseData = json.decode(response.body);
      final Product newProduct = Product(
          id: responseData['name'],
          title: title,
          description: description,
          image: uploadData['imageUrl'],
          imagePath: uploadData['imagePath'],
          price: price,
          location: locData,
          userEmail: _authenticatedUser.email,
          userId: _authenticatedUser.id);
      _products.add(newProduct);
      _isLoading = false;
      notifyListeners();
      return true;
    } catch (error) {
      _isLoading = false;
      notifyListeners();
      return false;
    }
  }
  /*.catchError((error) {
      _isLoading = false;
      notifyListeners();
      return false;
    });*/

  Future<bool> updateProduct(String title, String description, File image,
      double price, LocationData locData) async {
    _isLoading = true;
    notifyListeners();
    String imageUrl = selectedProduct.image;
    String imagePath = selectedProduct.imagePath;
    if (image != null) {
      final uploadData = await uploadImage(image);

      if (uploadData == null) {
        print('Upload failed!');
        return false;
      }

      imageUrl = uploadData['imageUrl'];
      imagePath = uploadData['imagePath'];
    }
    final Map<String, dynamic> updateData = {
      'title': title,
      'description': description,
      'imageUrl': imageUrl,
      'imagePath': imagePath,
      'price': price,
      'loc_lat': locData.latitude,
      'loc_lng': locData.longitude,
      'loc_address': locData.address,
      'userEmail': selectedProduct.userEmail,
      'userId': selectedProduct.userId,
    };
    try {
      await http.put(
          'https://flutter-aplikacija.firebaseio.com/products/${selectedProduct.id}.json?auth=${_authenticatedUser.token}',
          body: json.encode(updateData));
      _isLoading = false;
      final Product updatedProduct = Product(
          id: selectedProduct.id,
          title: title,
          description: description,
          image: imageUrl,
          imagePath: imagePath,
          price: price,
          location: locData,
          userEmail: selectedProduct.userEmail,
          userId: selectedProduct.userId);

      _products[selectedProductIndex] = updatedProduct;
      notifyListeners();
      return true;
    } catch (error) {
      _isLoading = false;
      notifyListeners();
      return false;
    }
  }

  Future<bool> deleteProduct() {
    _isLoading = true;
    final deletedProductId = selectedProduct.id;
    _products.removeAt(selectedProductIndex);
    _selProductId = null;
    notifyListeners();
    return http
        .delete(
            'https://flutter-aplikacija.firebaseio.com/products/$deletedProductId.json?auth=${_authenticatedUser.token}')
        .then((http.Response response) {
      _isLoading = false;
      _products.removeAt(selectedProductIndex);
      notifyListeners();
      return true;
    }).catchError((error) {
      _isLoading = false;
      notifyListeners();
      return false;
    });
  }

  Future<Null> fetchProducts({onlyForUser = false, clearExisting = false}) {
    _isLoading = true;
    if (clearExisting) {
      _products = [];
    }
    notifyListeners();
    return http
        .get(
            'https://flutter-aplikacija.firebaseio.com/products.json?auth=${_authenticatedUser.token}')
        .then<Null>((http.Response response) {
      final List<Product> fetchedProductList = [];
      final Map<String, dynamic> productListData = json.decode(response.body);
      if (productListData == null) {
        _isLoading = false;
        notifyListeners();
        return;
      }
      productListData.forEach((String productId, dynamic productData) {
        final Product product = Product(
            id: productId,
            title: productData['title'],
            description: productData['description'],
            price: productData['price'],
            location: LocationData(
                address: productData['loc_address'],
                latitude: productData['loc_lat'],
                longitude: productData['loc_lng']),
            image: productData['imageUrl'],
            imagePath: productData['imagePath'],
            userEmail: productData['userEmail'],
            userId: productData['userId'],
            isFavorite: productData['wishlistUsers'] == null
                ? false
                : (productData['wishlistUsers'] as Map<String, dynamic>)
                    .containsKey(_authenticatedUser.id));
        fetchedProductList.add(product);
      });
      _products = onlyForUser
          ? fetchedProductList.where((Product product) {
              return product.userId == _authenticatedUser.id;
            }).toList()
          : fetchedProductList;
      _isLoading = false;
      notifyListeners();
      _selProductId = null;
    }).catchError((error) {
      _isLoading = false;
      notifyListeners();
      return;
    });
  }

  void toggleProductFavoriteStatus() async {
    final bool isCurrentlyFavorite = selectedProduct.isFavorite;
    final bool newFavoriteStatus = !isCurrentlyFavorite;
    final Product updateProduct = Product(
        id: selectedProduct.id,
        title: selectedProduct.title,
        description: selectedProduct.description,
        price: selectedProduct.price,
        image: selectedProduct.image,
        imagePath: selectedProduct.imagePath,
        location: selectedProduct.location,
        userEmail: selectedProduct.userEmail,
        userId: selectedProduct.userId,
        isFavorite: newFavoriteStatus);
    _products[selectedProductIndex] = updateProduct;
    notifyListeners();
    http.Response response;
    if (newFavoriteStatus) {
      response = await http.put(
          'https://flutter-aplikacija.firebaseio.com/products/${selectedProduct.id}/wishlistUsers/${_authenticatedUser.id}.json?auth=${_authenticatedUser.token}',
          body: json.encode(true));
    } else {
      response = await http.delete(
          'https://flutter-aplikacija.firebaseio.com/products/${selectedProduct.id}/wishlistUsers/${_authenticatedUser.id}.json?auth=${_authenticatedUser.token}');
    }
    if (response.statusCode != 200 && response.statusCode != 201) {
      final Product updateProduct = Product(
          id: selectedProduct.id,
          title: selectedProduct.title,
          description: selectedProduct.description,
          price: selectedProduct.price,
          image: selectedProduct.image,
          imagePath: selectedProduct.imagePath,
          location: selectedProduct.location,
          userEmail: selectedProduct.userEmail,
          userId: selectedProduct.userId,
          isFavorite: !newFavoriteStatus);
      _products[selectedProductIndex] = updateProduct;
      notifyListeners();
    }
    _selProductId = null;
  }

  void selectProduct(String productId) {
    _selProductId = productId;
    if (productId != null) {
      notifyListeners();
    }
  }

  void toggleDisplayMode() {
    _showFavorites = !_showFavorites;
    notifyListeners();
  }
}

mixin UserModel on ConnectedProductsModel {
  Timer _authTimer;
  PublishSubject<bool> _userSubject = PublishSubject();

  User get user {
    return _authenticatedUser;
  }

  PublishSubject<bool> get userSubject {
    return _userSubject;
  }

  Future<Map<String, dynamic>> authenticate(String email, String password,
      [AuthMode mode = AuthMode.Login]) async {
    _isLoading = true;
    notifyListeners();
    final Map<String, dynamic> authData = {
      'email': email,
      'password': password,
      'returnSecureToken': true
    };
    http.Response response;
    if (mode == AuthMode.Login) {
      response = await http.post(
        'https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=AIzaSyAxgIztWNLV_0Xs9wqSo7rOosSKThxsaxg',
        body: json.encode(authData),
        headers: {'Content-Type': 'application/json'},
      );
    } else {
      response = await http.post(
        'https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=AIzaSyAxgIztWNLV_0Xs9wqSo7rOosSKThxsaxg',
        body: json.encode(authData),
        headers: {'Content-Type': 'aplication/json'},
      );
    }
    final Map<String, dynamic> responseData = json.decode(response.body);
    bool hasError = true;
    String message = 'Something went wrong.';
    print(responseData);
    if (responseData.containsKey('idToken')) {
      hasError = false;
      message = 'Authentication succeeded!';
      _authenticatedUser = User(
          id: responseData['localId'],
          email: email,
          token: responseData['idToken']);
      setAuthTimeout(int.parse(responseData['expiresIn']));
      _userSubject.add(true);
      final DateTime now = DateTime.now();
      final DateTime expiryTime =
          now.add(Duration(seconds: int.parse(responseData['expiresIn'])));
      final SharedPreferences prefs = await SharedPreferences.getInstance();
      prefs.setString('token', responseData['idToken']);
      prefs.setString('userEmail', email);
      prefs.setString('userId', responseData['localId']);
      prefs.setString('expiryTime', expiryTime.toIso8601String());
    } else if (responseData['error']['message'] == 'EMAIL_EXISTS') {
      message = 'This email already exists.';
    } else if (responseData['error']['message'] == 'EMAIL_NOT_FOUND') {
      message = 'This email was not found.';
    } else if (responseData['error']['message'] == 'INVALID_PASSWORD') {
      message = 'The password is invalid.';
    }
    _isLoading = false;
    notifyListeners();
    return {'success': !hasError, 'message': message};
  }

  void autoAuthenticate() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    final String token = prefs.getString('token');
    final String expiryTimeString = prefs.getString('expiryTime');
    if (token != null) {
      final DateTime now = DateTime.now();
      final parsedExpiryTime = DateTime.parse(expiryTimeString);
      if (parsedExpiryTime.isBefore(now)) {
        _authenticatedUser = null;
        notifyListeners();
        return;
      }
      final String userEmail = prefs.getString('userEmail');
      final String userId = prefs.getString('userId');
      final int tokenLifespan = parsedExpiryTime.difference(now).inSeconds;
      _authenticatedUser = User(id: userId, email: userEmail, token: token);
      _userSubject.add(true);
      setAuthTimeout(tokenLifespan);
      notifyListeners();
    }
  }

  void logout() async {
    _authenticatedUser = null;
    _authTimer.cancel();
    _userSubject.add(false);
    _selProductId = null;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.remove('token');
    prefs.remove('userEmail');
    prefs.remove('userId');
  }

  void setAuthTimeout(int time) {
    _authTimer = Timer(Duration(seconds: time), logout);
  }
}

mixin UtilityModel on ConnectedProductsModel {
  bool get isLoading {
    return _isLoading;
  }
}

If someone can show me some example test`s for this file I think i could work it out on the other files. Thanks.

Here is one of the test`s that i use

import 'package:aplikacija/pages/product_edit.dart';
import 'package:flutter_test/flutter_test.dart';

void main(List<String> args) {
  test('empty title returns error string', () {
    final result = BuildTitleTextValidator.validate('');
    expect(result, 'Title is required and should be 5+ characters long.');
  });
  test('non-empty title returns null', () {
    final result = BuildTitleTextValidator.validate('product');
    expect(result, null);
  });
  test(
    'empty dexcription returns error string',
    () {
      final result = BuildDescriptionTextValidator.validate('');
      expect(
          result, 'Description is required and should be 10 + character long');
    },
  );
  test(
    'non-empty dexcription returns error string',
    () {
      final result =
          BuildDescriptionTextValidator.validate('product description');
      expect(result, null);
    },
  );

  test(
    'empty price tag returns error string',
    () {
      final result = BuildPriceTextValidator.validate('');
      expect(result, 'Price is required and should be a number');
    },
  );

  test(
    'non-empty price tag returns error string',
    () {
      final result = BuildPriceTextValidator.validate('11');
      expect(result, null);
    },
  );
}

Thank you for your help.

angular test http call inside a service function

I am trying to test http call inside of the service method. I don't understand why my test doesn't init http call inside that funcion, even if I am using tick method.

logout() 
{
    this.http.post(environment.apiUrl + '/logout ', {}).subscribe(
      () => {
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        this.router.navigate(['']);
      }, err => console.log(err)
    );
  }

and test for this method:

it('should be send to correct URL', fakeAsync(() => {
      service.logout();
      const req = httpTestingController.expectOne(`${environment.apiUrl}/logout`);
      req.flush({});
      tick();
      httpTestingController.verify();
    }));

Dist folder generates when writing tests

I'm currently trying to write tests for my Meteor app. When I edit any .tests.js file or any file within the ./test directory, a /dist folder generates within the current directory with a matching .dev.js file. I've tested the same packages in separate applications without an issue. Not sure why it might be happening.

I'm working in VSCode.

Meteor version 1.10.2

// meteor packages

meteor-base@1.4.0             
mobile-experience@1.1.0       
mongo@1.10.0                   
reactive-var@1.0.11            

standard-minifier-css@1.6.0   
standard-minifier-js@2.6.0    
es5-shim@4.8.0                
ecmascript@0.14.3              
typescript@3.7.6             
shell-server@0.5.0           

insecure@1.0.7                
react-meteor-data       
accounts-base
accounts-ui
accounts-password
jquery
aldeed:collection2@3.0.0
cultofcoders:grapher
static-html
random
mdg:validated-method
dburles:collection-helpers
meteortesting:mocha
practicalmeteor:chai
dburles:factory
hwillson:stub-collections
// package.json

{
  "name": "proser",
  "private": true,
  "scripts": {
    "start": "meteor run",
    "test": "meteor test --once --driver-package meteortesting:mocha",
    "test-app": "TEST_WATCH=1 meteor test --full-app --driver-package meteortesting:mocha",
    "visualize": "meteor --production --extra-packages bundle-visualizer"
  },
  "dependencies": {
    "@babel/runtime": "^7.10.4",
    "@emotion/core": "^10.0.28",
    "@fortawesome/fontawesome-svg-core": "^1.2.29",
    "@fortawesome/free-solid-svg-icons": "^5.13.1",
    "@fortawesome/react-fontawesome": "^0.1.11",
    "@material-ui/core": "^4.11.0",
    "@material-ui/icons": "^4.9.1",
    "@material-ui/lab": "^4.0.0-alpha.56",
    "bcrypt": "^5.0.0",
    "bootstrap": "^4.5.0",
    "fontsource-roboto": "^2.1.4",
    "formik": "^2.1.4",
    "formik-material-ui": "^3.0.0-alpha.0",
    "history": "^5.0.0",
    "jquery": "^3.5.1",
    "meteor-node-stubs": "^1.0.0",
    "react": "^16.13.0",
    "react-contenteditable": "^3.3.5",
    "react-dom": "^16.13.0",
    "react-quill": "^2.0.0-beta.2",
    "react-router": "^5.2.0",
    "react-router-dom": "^5.2.0",
    "react-spinners": "^0.9.0",
    "simpl-schema": "^1.8.0",
    "yup": "^0.29.1"
  },
  "meteor": {
    "mainModule": {
      "client": "client/main.js",
      "server": "server/main.js"
    },
    "testModule": "tests/main.js"
  }
}
// ./tests/main.js

import assert from "assert";

describe("proser", function () {
  it("package.json has correct name", async function () {
    const { name } = await import("../package.json");
    assert.strictEqual(name, "proser");
  });

  if (Meteor.isClient) {
    it("client is not server", function () {
      assert.strictEqual(Meteor.isServer, false);
    });
  }

  if (Meteor.isServer) {
    it("server is not client", function () {
      assert.strictEqual(Meteor.isClient, false);
    });
  }
});
// ./tests/dist/main.dev.js (generated file)

"use strict";

var _assert = _interopRequireDefault(require("assert"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

describe("proser", function () {
  it("package.json has correct name", function _callee() {
    var _ref, name;

    return regeneratorRuntime.async(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.next = 2;
            return regeneratorRuntime.awrap(Promise.resolve().then(function () {
              return _interopRequireWildcard(require("../package.json"));
            }));

          case 2:
            _ref = _context.sent;
            name = _ref.name;

            _assert["default"].strictEqual(name, "proser");

          case 5:
          case "end":
            return _context.stop();
        }
      }
    });
  });

  if (Meteor.isClient) {
    it("client is not server", function () {
      _assert["default"].strictEqual(Meteor.isServer, false);
    });
  }

  if (Meteor.isServer) {
    it("server is not client", function () {
      _assert["default"].strictEqual(Meteor.isClient, false);
    });
  }
});

How to delete or replace text on monaco editor using testcafe?

I'm writing some tests with testcafe. I have monaco editor field in with some text, I want to delete the text and insert another text or just override the text that I have. I tried this code and it inserts "someText" after the characters on the first line. I used this line of code:

await t.typeText(Selector('.parent-class .inputarea'), someText);

any idea?

samedi 29 août 2020

Migrations and Testing CLI Commands Not Working in Visual Studio Code / VSCode Terminal

Running both migrations with "npm run migrate" and tests with "npm test" in the terminal in VSCode throws errors, yet if I run the same commands on the same project from the terminal on my mac, they run perfectly and as expected.

  • What is the reason for this?
  • Is there a way to configure my terminal in VSCode so that I can run migrations and testing through it or do I need to use the always use the terminal on my mac for migrations and testing?

How to set up a test in jest to check for existence of elements with specific data attributes in dom

Im testing my javascript class with jest, here's the relevant part of the class :

class ContentEditable {
  constructor(editableKind){
    this.editables =  document.querySelectorAll(`[data-editablekind='${editableKind}']`);
    this.editionStrategy = this.getStrategy(editableKind)
  }
}

In the test Id like to check that this.editables is returning the right stuff (a Nodelist of the right size). So the idea behind the test is to create a div with the right attribute then instanciate the class and check for the length of editables

test('editables of kind text', () => {
  let element = document.createElement("div");
  element.dataset.editablekind = 'text'
  console.log(element.dataset.editablekind)
  const contentEditable = new ContentEditable('text')
  expect([...contentEditable.editables].length).toEqual(1);
});

However contentEditable.editables seems to stay empty whatever I do. What am I missing here ?

Using a Stub in global setup in Spock

I am trying to prepare some abstract setup for a tested object and I am stuck when it comes to using a Stub there. Basically what I am trying to achieve - I have a Facade being created like this:

Facade facade(EventBus eventBus)

I have different test classes for different use cases - in most of the tests I don't need to interact with the eventBus, so I would like it to be a simple implementation like

event -> just("No event bus configured")

But I would also like to have a possibility to check if proper events were published there so I would like also to be able to inject a Stub if needed. Another aspect of it is that I need some code in setupSpec method to properly set up the facade before the tests and I would like to avoid doing it in setup method.

How I would see it:

abstract class AbstractSpec extends Specification {

@Shared
Facade facade = new Facade(
        eventBus())

def setupSpec() {
    runDifferentMethodsOnTheFacade()
}

EventBus eventBus() {
    return { event -> just("No event bus configured") }
}

Whereas in the class where I would like to verify EventBus calls I would have something like this:

class DerivedSpec extends AbstractSpec {

EventBus eventBus = Mock()

def "check if proper event was emited"() {
    given:
        ExpectedEvent publishedEvent

    when:
        def someId = facade.doSomething().block()

    then:
        1 * eventBus.push(_ as ExpectedEvent) >> { ExpectedEvent event -> publishedEvent = event }
        publishedEvent.id() == someId
}

EventBus eventBus() {
    return eventBus
}
}

Is it somehow achievable? Are the Spock extensions helpful in such case? I guess the simplest solution would be to resign from extending the AbstractSpec in this particular test and just reuse the setupSpec code in setup for this single class but I am curious if there is another way to solve it.

Are there IPA sounds that I can download and use for testing

I need an audio file for each IPA sound listed here.

I have Googled around but I do not know what to search and haven't really found anything.

So my question is, is there a ZIP file or something of all of the IPA audio files that I can download?

What is meant by saying this statistical test is valid at 5% significance level? what is oversized test? what is liberal test? [migrated]

I have a bunch of tests. The sizes of these tests were inspected under different sample sizes. For every sample size 10000 data sets are generated and then the empirical rejection rate is calculated. The author says when commenting the graphs this test is valid at 5%, the other test is oversized and that other becomes liberal

How to set up python testing in Databricks

I am new to Databricks and I have created a data profiling notebook within it. I now want to unit test some functions, but I feel a bit lost. I've done a lot of searching for best ways to do this, and I cannot find great answers. My code is not meant to be a sophisticated development project, it is more of a means to an end that I will be using for a few months, but I still want to make sure I have some test coverage.

The laziest approach would be to add tests within the same notebook. But what I would rather do is create a testing notebook to test functions in my profiling notebook, but I cannot figure out if this is a good practice in Databricks or not. I'm looking for guidance on how to set up testing for this type of project.

CLI Testing Tool [closed]

Whats the best tool for testing cli commands?

eg:

echo "1+1" | bc
2

# valid output 2 is 2 = True

And this tool has the feature scenarios, prepare and clearing environment.

Test case for child components onClick function

I want to test the onClick functionality of MenuPopover.Item id={3} if it was called once or not after clicking on it.

import React from 'react';
import copy from 'copy-to-clipboard';

const TableMenu = ({show, target, onClick, onHide, addedType, disable, readonly, rowId, supportRestore, supportDelete, isRestored}) => (
    <MenuPopover
        onClick={onClick}
        onHide={onHide}>
        {!readonly && (addedType ?
            <MenuPopover.Item id={1} label='Delete' disabled=true/> :
            <MenuPopover.Item id={2} label='Restore' disabled=false/>
        )}
        <MenuPopover.Item id={3} onClick={() => copy(rowId)} label='Copy'/>
    </MenuPopover>
);

Test case written so far

const onCopySpy = sinon.spy();
const props = {
    ///
    onCopy: onCopySpy,
    ///
};

it('check method onCopy called', () => {
    const wrapper = shallow(<TableMenu {...props}/>);
    expect(wrapper.find('MenuPopover').children()).to.have.lengthOf(2);
    wrapper.find('MenuPopover').props().onCopy();
    expect(onCopySpy.calledOnce).to.eql(true);
});

What is the size of a test? how to determin it in R?

Suppose I do have

x <- rnorm(20,0,1)
y <- rnorm(20,-3,1) 

Now I carry out a t.test(x,y).
How to get the size of this test? In R of course.

Angular mat-datepicker's input not working in unit tests

I'm building a custom Angular component which contains a mat-datepicker. Basically component should let user to choose a date and it then emits an event. I have the following implementation which seems to work fine when testing manually:

TS:

@Component({
  selector: 'kms-date-range-picker',
  templateUrl: './date-range-picker.component.html',
  styleUrls: ['./date-range-picker.component.scss'],
})
export class DateRangePickerComponent implements OnInit {
  @Input() startDate: moment.Moment;
  @Input() endDate: moment.Moment;
  @Output() onDateChange = new EventEmitter<{ startDate: moment.Moment; endDate: moment.Moment }>();
  startDateFormControl: FormControl;
  endDateFormControl: FormControl;

  constructor() {}

  ngOnInit(): void {
    this.startDateFormControl = new FormControl(this.startDate);
    this.endDateFormControl = new FormControl(this.endDate);
  }

  onStartDateChange(event: any): void {
    this.startDate = event.value !== null ? moment(event.value) : undefined;
    this.emitDates();
  }

  onEndDateChange(event: any): void {
    this.endDate = event.value !== null ? moment(event.value) : undefined;
    this.emitDates();
  }

  private emitDates(): void {
    this.onDateChange.emit({
      startDate: this.startDateFormControl.value,
      endDate: this.endDateFormControl.value
    })
  }
}

Template:

<div fxLayout="row" fxLayoutAlign="start center" fxLayoutGap="5px">
  <mat-form-field>
    <mat-label i18n="@@start_date">Start</mat-label>
    <input
      matInput
      data-testId="start-date-input"
      [matDatepicker]="startDatePicker"
      [formControl]="startDateFormControl"
      (dateChange)="onStartDateChange($event)"
    />
    <mat-datepicker-toggle matSuffix [for]="startDatePicker"></mat-datepicker-toggle>
    <mat-datepicker #startDatePicker></mat-datepicker>
  </mat-form-field>
  <mat-form-field>
    <mat-label i18n="@@end_date">End</mat-label>
    <input
      matInput
      data-testId="end-date-input"
      [matDatepicker]="endDatePicker"
      [formControl]="endDateFormControl"
      (dateChange)="onEndDateChange($event)"
    />
    <mat-datepicker-toggle matSuffix [for]="endDatePicker"></mat-datepicker-toggle>
    <mat-datepicker #endDatePicker></mat-datepicker>
  </mat-form-field>
</div>

The problem is that if I try to unit test this by writing something to the input field, nothing happens. Same happens if I try to set the starting values in the tests. Instead of updating the input field its value stays empty. Here is my test suite where I'm using MatInputHarness to set the value:

  beforeEach(() => {
    fixture = TestBed.createComponent(DateRangePickerComponent);
    loader = TestbedHarnessEnvironment.loader(fixture);
    component = fixture.componentInstance;

    // Set @Input values here to avoid the parent component template
    component.startDate = moment('2020-05-01');
    component.endDate = moment('2020-10-12');

    spyOn(component.onDateChange, 'emit');

    fixture.detectChanges();
  });

  it('should initialize fields with given start and end dates', async () => {
    expect(component).toBeTruthy();
    const startDateInput = await getInputHarness('start-date-input');
    const endDateInput = await getInputHarness('end-date-input');

    // await startDateInput.setValue('1234');

    expect(await startDateInput.getValue()).toBe('1.5.2020');
    expect(await endDateInput.getValue()).toBe('12.10.2020');
  });

  it('should emit date range when a date is changed to valid range', async () => {
    expect(component).toBeTruthy();
    const startDateInput = await getInputHarness('start-date-input');
    // const endDateInput = await getInputHarness('end-date-input');

    await startDateInput.setValue('4.6.2020');
    expect(component.onDateChange.emit).toHaveBeenCalledTimes(1);
  });

  async function getInputHarness(testId: string): Promise<MatInputHarness> {
    return await loader.getHarness(MatInputHarness.with({ selector: `[data-testId="${testId}"]` }));
  }

Both of these tests fail in this way:

Chrome 85.0.4183 (Linux 0.0.0) DateRangePickerComponent should initialize fields with given start and end dates FAILED
        Error: Expected '' to be '1.5.2020'.
            at <Jasmine>
            at http://localhost:9876/_karma_webpack_/main.js:35635:49
            at <Jasmine>
            at fulfilled (http://localhost:9876/_karma_webpack_/vendor.js:351548:58)
        Error: Expected '' to be '12.10.2020'.
            at <Jasmine>
            at http://localhost:9876/_karma_webpack_/main.js:35636:47
            at <Jasmine>

What gives? If I remove the [matDatepicker]="startDatePicker" from inputs, the text input via test works and input fields are updated. However, if I add them back, input fails. How should I test these fields in Angular unit tests?

How can I check RPS and DB size on my site?

I want check rps and db size on my site. How can I check it? It's possible or not? I don't understand. Help me please if you know it.

Thanks

Regarding angular Test cases

I am facing problem in running angular test case. Every time I run test for module I need to enter the sub-component providers also in my component.spec.ts. We have separate component for every things ,app-filter, app-input-box,app-dialog-box? Why by entering module of sub-component in module.spec.ts I need to Re-enter all modules and providers in component.spec.ts??

can yo help me on: AttributeError: type object 'PagesTesting' has no attribute 'test_011_employee'

I'm trying to run the test_011_employee for each different code "M00007", "M00009", "M00011" in python so that I don't have to re do all the code for every different code I need and i'm getting AttributeError: type object 'PagesTesting' has no attribute 'test_011_employee', can you kindly help me solve the error ?

complete error:

Ran 1 test in 0.003s

FAILED (errors=1)

Error
Traceback (most recent call last):
  File "C:\Users\RonaldCamilleri\AppData\Local\Programs\Python\Python38-32\lib\unittest\case.py", line 60, in testPartExecutor
    yield
  File "C:\Users\RonaldCamilleri\AppData\Local\Programs\Python\Python38-32\lib\unittest\case.py", line 676, in run
    self._callTestMethod(testMethod)
  File "C:\Users\RonaldCamilleri\AppData\Local\Programs\Python\Python38-32\lib\unittest\case.py", line 633, in _callTestMethod
    method()
  File "C:\Users\RonaldCamilleri\AppData\Local\Programs\Python\Python38-32\lib\unittest\loader.py", line 34, in testFailure
    raise self._exception
  File "C:\Users\RonaldCamilleri\AppData\Local\Programs\Python\Python38-32\lib\unittest\loader.py", line 169, in loadTestsFromName
    parent, obj = obj, getattr(obj, part)
AttributeError: type object 'LoginTest' has no attribute 'test_011_employee'


Process finished with exit code 1

Assertion failed

Assertion failed

Assertion failed

Assertion failed

Assertion failed

Assertion failed

Assertion failed

Assertion failed
@ddt
class PagesTesting(unittest.TestCase):

    @classmethod
    def setUp(cls):
        # create a new Chrome session
        opts = Options()
        opts.binary_location = "path to chrome.exe"
        cls.driver = webdriver.Chrome(options=opts, executable_path='path to chromedriver.exe')
        unittest.TestLoader.sortTestMethodsUsing = None
        cls.driver.implicitly_wait(60)
        cls.driver.maximize_window()

        # navigate to the application home page
        cls.driver.get("website address")
        wait = WebDriverWait(cls.driver, 60)

    def tearDown(self):
        for method, error in self._outcome.errors:
            if error:
                test_method_name = self._testMethodName
                self.driver.save_screenshot(
                    "screenshotname.png"
                    % test_method_name)

        # Close the browser window
        self.driver.close()

    @data("M00007", "M00009", "M00011")
    def test_011_employee(self, code):

        wait = WebDriverWait(webdriver, 60)
        
        Login.test_001_Login() #this call is used to log into the website

        employeesbutton = wait.until(
            ec.visibility_of_element_located((By.XPATH, '/html/body/form/div[1]/div/div/nav/ul/li[2]/a/span[1]')))
        
        employeesbutton.click()
        
        employeedetailsbutton = wait.until(
            ec.visibility_of_element_located((By.XPATH, '/html/body/form/div[1]/div/div/nav/ul/li[2]/ul/li[1]/a/span')))
        
        employeedetailsbutton.click()

        frame0 = wait.until(
            ec.visibility_of_element_located((By.XPATH, '/html/body/form/div[1]/main/div/div[2]/div[2]/iframe')))
        
        self.driver.switch_to.frame(frame0)

        self.driver.find_element_by_xpath('/html/body/form/div[3]/div[6]/div/p/button[4]').click()  # click clear button
        sleep(5)
        
        self.driver.find_element_by_xpath('/html/body/form/div[3]/div[2]/div[2]/div/input').clear()  # clear input box
        sleep(5)

        employeeid = wait.until(
            ec.visibility_of_element_located(
                (By.XPATH, '/html/body/form/div[3]/div[2]/div[2]/div/input')))  # locate input box
        
        employeeid.click()
        employeeid.send_keys(code)
        sleep(5)
        employeeid.send_keys(Keys.RETURN)

vendredi 28 août 2020

C# = Read from appsettings.json file to launch application - for test automation

I am using specflow for test automation and I want to read from a appsettings.json file to launch browser

Previously I used and appconfig file for this nut specflow does not support it anymore

So basically I want to read from this:

{
"appSettings": [
    {
      "key": "TestURL",
      "value": ""
    },
    {
      "key": "UATURL",
      "value": ""
    },
    {
      "key": "PRODURL",
      "value": ""
    },
    {
      "key": "BrowserType",
      "value": "Chrome"
    }
  ],


  "connectionStrings": [
    {
      "connectionString": "",
      "name": ""
    }
  ]

I want to be able to pass the key pair value as a parameter for this method

 public static void LoadApplication(string url)
        {
            DriverContext.Driver.Url = url;
          
        }

Previously I used something like this:

var url = ConfigurationManager.AppSettings["TestURL"];
           DriverContext.Driver.Url = ConfigurationManager.AppSettings["TestURL"];

Just wondering what is the best approach to to this?

How can I test file-upload with hapi and output set as stream?

I have this payload format in my hapi route that accepts only multipart/form-data data and the output is set as a stream:

payload: {
        maxBytes: 1024,
        output: 'stream',
        parse: true,
        allow: 'multipart/form-data',
      }

I want to test that route and my payload is this:

const FD = new FormData();
    FD.append('field1', 'value');
    FD.append('field2', 'value');

The hapi inject method looks like this:

    const res = await server.inject({
      method,
      url,
      headers: {
        ...
        'Content-Type': 'multipart/form-data; boundary=--SEPARATION--',
      },
      payload: FD,
    });

I am getting

Invalid multipart payload format

I tried to set a stream using a Steam object too but it doesn't work. Also I tried to send a File object.

At this point I just want to send something to the route that will not result in an error. It's not necessary to be a FormData. Anything that will be accepted by the route is fine as long as I can add some custom fields to test it further.

Thanks in advance.

Simulate No Internet Connection/Slow Internet Connection in Android Instrumentation Test

I am writing a library that checks the the connection of the android device continuously and gives a callback when the device gets connected, disconnected or the internet connection becomes slow.

https://github.com/muddassir235/connection_checker

I want to write Android Instrumentation tests for this library and I need to simulate no internet connection as well as a slow internet connection.

package com.muddassir.connection_checker

import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4

import org.junit.Test
import org.junit.runner.RunWith

import org.junit.Assert.*

/**
 * Instrumented test, which will execute on an Android device.
 *
 * See [testing documentation](http://d.android.com/tools/testing).
 */
@RunWith(AndroidJUnit4::class)
class ConnectionCheckerTest {
    @Test
    fun checkDisconnectedState() {
        val context = InstrumentationRegistry.getInstrumentation().targetContext
        InstrumentationRegistry.getInstrumentation().runOnMainSync {
            val connectionChecker = ConnectionChecker(context, null)
            connectionChecker.connectivityListener = object: ConnectivityListener {
                override fun onConnected() {
                    assertTrue(false)
                }

                override fun onDisconnected() {
                    assertTrue(true)
                }

                override fun onConnectionSlow() {
                    assertTrue(false)
                }
            }

            // Disconnect from the internet. How do I do this?

            connectionChecker.startChecking()
        }

        Thread.sleep(30000)
    }
}

How to make a test run last in a TestNG tests suite

I am using TestNG for functional testing in my project and I need to ensure a specific test run the last.

I tried using dependencies and establishing a "lineal" flow of execution through those dependencies, but this solution was a little bit inefficient since there are tests that actually can run without having to ensure another test pass before they are being executed.

So, the main problem with dependencies is if a test fails in the execution, TestNG doesn't execute the rest of them and I don't want this behavior.

Also, the order I need for my test suite is not lineal, for example: Test 1 -> Test 2 -> ... -> Test n

Actually, my ordering is more like a tree:

  • Test 1
  • Test 2 -> depends on 1
  • Test 3 -> depends on 1
  • Test 4 -> depends on 3
  • Test 5 -> depends on 4
  • Test 6 -> depends on 1 and 3
  • Test 7 -> depends on 2 and 6
  • Test -> depends on 3 (this one should be executed as the last)

(Above example is hypothetical and only tries to describe my test scenario)

I tried using priorities but they seem not to work like this. Do you have a recommendation about this guys? Thank you for your help and sorry for the noob question.

Jmet assessment

Anyone can help solve this assessment? Using JMeter framework (https://jmeter.apache.org) please implement a load test script:

The script should send 10 concurrent requests to Capital API: https://restcountries.eu/rest/v2/capital/?fields=name;capital;currencies;latlng;regionalBlocs The script should read the capital values from a CSV file (contains 10 capital names) The script should perform a status code verification for the transaction response The script should run for 2 minutes. The script should contain at least 2 listeners.

Python/Pytest fixture value depending on test number

I have created a @pytest.fixture(scope="class") inside which I have added steps in the selenium:

@pytest.fixture(scope="class")
def test_setup1(test_setup):
    driver.click_element()
    driver.enter_price()
    driver.enter_year('1997') <--- test-dependent element
    many steps
    ...
 

Is it possible that one of the elements e.g. driver.enter_year() depends on the element inside test? For example:

def test_order_1 (self, test_setup1):

    date = 1998
    assert element_in_alert('Succes')


def test_order_2 (self, test_setup1):

    date = 1994
    assert element_in_alert('Succes')


RTL's TypeError: _react2.screen.getAllBy is not a function

In my project I am successfully using render and screen from @testing-library/react, However everytime I do screen.getAllBy or screen.getByRole or anything else other than getByText I am getting such errors. One of them was,

typeerror: _react2.screen.getAllBy is not a function

This occurred upon the usage of screen.getAllBy.

My imports includes,

import React from 'react';
import { render, screen } from '@testing-library/react';
import { BrowserRouter } from 'react-router-dom;
import TestComponent from './TestComponent';

Am I missing an import or is there something wrong with my code?

it (`Testing Component`, () => { 
  render(<BrowserRouter><TestComponent /></BrowserRouter>
  expect(screen.getAllBy('li')).toBeInTheDocument();
});

How to Login only once before each fixture in testcafe

I want to run e2e test and for that I want to login only once (before each and every fixture ) in my test framework. I read that I can do it with Role but I do not know how I can deal with all the fixtures across the framework

Moreover, I do login using httpauth, before httpauth I have to enter my email, so is there any way I can handle httpauth via Role or any other way (I want to login only once until all my fixtures gets run)

Thanks in advance!!

Karate software - simple if condition is not working in 0.9.6

Using Karate Software framework, I have problem with new released version (0.9.6). I have problems with simple IF condition

* if (locate('{h6}' + appName).exists) karate.call('classpath:ui/common/applicationDeletion.feature')

This condition works properly in version 0.9.5. But with last release there is error announced when the feature is run:

evaluation (js) failed: if (locate('{h6}' + appName).exists) karate.call('classpath:ui/common/applicationDeletion.feature'), java.lang.RuntimeException: cannot find locator: {h6}stx-fat-app-tst
stack trace: com.intuit.karate.driver.Driver.locate(Driver.java:275)
 ==> expected: <true> but was: <false>

It seems there is some change between versions 0.9.5 and 0.9.6. I would expect that the condition is FALSE, karate call will not be executed (skipped) and following code will be followed.

Could you please give me some hint why it is not working?

Thank you!

POM file

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>testing</groupId>
    <artifactId>ssp-uc-tests</artifactId>
    <version>0.0.1</version>
    <packaging>jar</packaging>
 
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
        <maven.compiler.version>3.6.0</maven.compiler.version>
        <karate.version>0.9.6</karate.version>
    </properties>    

    <dependencies>
        <dependency>
            <groupId>com.intuit.karate</groupId>
            <artifactId>karate-apache</artifactId>
            <version>0.9.6</version>
            <scope>test</scope>
        </dependency>            
        <dependency>
            <groupId>com.intuit.karate</groupId>
            <artifactId>karate-junit5</artifactId>
            <version>0.9.6</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.4.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>net.masterthought</groupId>
            <artifactId>cucumber-reporting</artifactId>
            <version>5.3.1</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <testResources>
            <testResource>
                <directory>src/test/java</directory>
                <excludes>
                    <exclude>**/*.java</exclude>
                </excludes>
            </testResource>
        </testResources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.compiler.version}</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                    <compilerArgument>-Werror</compilerArgument>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.0.0-M5</version>
            </plugin>            
        </plugins>        
    </build>       
    
</project>

Laravel: How can I fake an http request to a 3rd party & mock json response

I'm struggling to figure out what is probably something that's very basic and I'll get laughed out of here but I'm hoping maybe it'll help someone else as well.

I am trying to mock/test an Http request in a feature test. I am still learning good/better/best techniques for testing so perhaps there is a much better way.

// MyFeatureTest.php

$user = factory(User::class)->create(['email' => 'example@email.com']);

// Prevent actual request(s) from being made.
Http::fake();

$this->actingAs($user, 'api')
    ->getJson('api/v1/my/endpoint/123456')
    ->assertStatus(200);

In my controller my request looks like this:

public function myFunction() {
    try {
        $http = Http::withHeaders([
                'Accept' => 'application/json',
                'Access_Token' => 'my-token',
                'Content-Type' => 'application/json',
            ])
            ->get('https://www.example.com/third-party-url, [
                'foo' => 'bar,
        ]);

            
        return new MyResource($http->json());
    } catch (RequestException $exception) {
        Log::error("Exception error: " . print_r($exception, true));
    }
}

I would like to mock that I'm getting a 200 response, and ideally mock the expected json from the resource. I've successfully been able to do this test when the endpoint is local to my application (does not call to a 3rd party). This is what I've done in the past:

$http->assertStatus(200)
    ->assertJsonStructure([
        'type', 'id', 'attributes' => [
            'email', 'uuid', 'created_at', 'updated_at',
        ],
    ])
    ->assertJson(['type' => 'example',...]);

In the docs I can see this:

Http::fake([
    'github.com/*' => Http::response(['foo' => 'bar'], 200, ['Headers']),
]);

How can I mock/fake the request to a 3rd party url and assert a good response? Thank you for any suggestions!

How to validate and print non-json response using Karate

I am getting '1' in response body and not able to print it on console and neither validate it

below are the details of response body and console output:

Scenario

Scenario: Sample Scenario 

Given path '/SomePath'
When method get
Then status 200
And print 'Service Response is: ' + response

Response body: Below Image shows the Service Response

Console output for print:

[ForkJoinPool-1-worker-1] INFO com.intuit.karate - [print] Service Response is:

Console output for validation :

ERROR com.intuit.karate - assertion failed: path: $, actual: '', expected: '1', reason: not a sub-string

Automated integration test with C/C++/ESP32 and PHP/NetBeans

do you have an idea how to approach automated testing (unit tests and integration test) including hardware (C/C++ on ESP32 in Arduino or Visual Studio) and soft-/webware (PHP/JS/websocket in NetBeans) ?

What would be a good interface (JTAG, OpenOCD ...) and how can they communicate with each other ? Currently I can't imagine how they could possibly work together in an automated manner. Any advice would be much appreciated.

Best regards

thatOneGuy

Selenium tests fail with Docker when Code is copied

Requirements:

  1. COPY source to_destination
  2. I am using container registry. So no need to think of persistence.

I created my base dockerfile based on https://github.com/markhobson/docker-maven-chrome

Then when I do

COPY src docker_destination
RUN mvn clean test

It fails multiple interactive UI tests like login from credentials, etc. If I just use mounting using

docker run -it --rm  -v "$(pwd)":/src -w /src dockerapp:tag mvn clean test

It works.

How can I make it work with the COPY command instead of VOLUME.?

Load an external libraries as jar (in resources folder ) when run class.method in a jar dinamically

I have developed a Test console that loads the @Test methods in jars in a specific folder via REFLECTION and runs them as well. Everything works fine but when a Test.jar use an external library internally (in the "resources" folder) it doesn't work, not finding this ext. library.

For example:

I have a TEST jar: SEM1.jar which has inside it in main/reosurces/ extLib1.jar When I run the TEST1 method in the ClassTest.class. I have the following ERROR:

java.lang.NoClassDefFoundError: Lit / xxxx / yy / sdk / mymqtt; (inside extLib1.jar).

The code I use to run the test is the following:

public static void runOne(String jar, String class_name, Optional<String> test_name, TestExecutionListener listener) throws ClassNotFoundException, NoSuchMethodException, MalformedURLException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        Launcher launcher = LauncherFactory.create();
        
        ClassLoader loader = URLClassLoader.newInstance(
                new URL[] { new File(pathJars+"/"+jar).toURI().toURL() },
                ServiceUtil.class.getClassLoader()
        );

        loader.getClass();
        Class cls=loader.loadClass(class_name);
        Constructor constructor = cls.getConstructor();
        constructor.newInstance();

        LauncherDiscoveryRequest request;
        if (test_name.isPresent()) {
            Method m = cls.getMethod(test_name.get());
            request = LauncherDiscoveryRequestBuilder.request()
                    .selectors(selectMethod(cls,m))
                    .build();
        }
        else{
            request = LauncherDiscoveryRequestBuilder.request()
                    .selectors(selectClass(cls))
                    .build();
        }

        TestPlan testPlan = launcher.discover(request);
        launcher.registerTestExecutionListeners(listener);
        launcher.execute(request);
        loader=null;
        System.gc();

    }

Thanks for help me. Regards

Spring: JUnit Testing Rest Controller

I'm trying to test my RestController that is called by an Angular Client. My RestController calls a service that communicate through SOAP requests to a Web Service. Do u have any example to learn from for testing this kind of stuff? Here is my code for BookController:

@RepositoryRestController  
@RestController
@CrossOrigin(origins = "http://localhost:4200")
public class BookController {
    @Autowired BookClient quoteClient;
    GetBookListResponse lista = new GetBookListResponse();
    BookService bookservice = new BookService();
  
    @GetMapping(value = "/books")
    public Object[] allBooks() {
        lista = quoteClient.getBookList(true);
        return lista.getBookList().toArray();
        
    }

I would like to test allBook() function that perform a request to the BookClient class.

public class BookClient extends WebServiceGatewaySupport {
public GetBookListResponse getBookList(boolean richiesta) {

        GetBookListRequest request = new GetBookListRequest();
        
        request.setRichiesta(true);
        log.info("Getting all books: ");
        
        try {
            GetBookListResponse response = (GetBookListResponse) getWebServiceTemplate()
            .marshalSendAndReceive("http://localhost:8080/ws/book", request,
                new SoapActionCallback(
                    "http://spring.io/guides/gs-producing-web-service/GetBookListRequest"));

        return response;
        } catch (Exception ex) {
            throw ex;}
        }

Below my JUnit testing class

@RunWith(MockitoJUnitRunner.class)
@WebMvcTest(value = BookController.class,  excludeAutoConfiguration = {SecurityAutoConfiguration.class})
public class HttpRequestTest {


    @Autowired
    private MockMvc mockMvc;
    
    @MockBean
    private BookController controller;
    @MockBean
    private BookClient client;
    
    
    
    @Before
      public void setup() {
        mockMvc = MockMvcBuilders.standaloneSetup(this.controller).build();
      }
    
    
    
    @Test
    @WithMockUser(username = "admin", password = "mypass", roles="ADMIN")
    public void allBookShouldWork() throws Exception {
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/books"))
                .andExpect(MockMvcResultMatchers.status().isOk()).andDo(print()).andReturn();
        
        assertThat(mvcResult.getResponse().getContentAsString()).isNotNull();
        
    }

The problem is that the body of the response is always null.

How to handel token authentication in performance testing using blazemeter recorder or Jmeter JMX script?

Ce résumé n'est pas disponible. Veuillez cliquer ici pour afficher l'article.

React Testing if validation message shows up for username ,email,password

I wanted to test if validation messages shows up for username, email,password using React testing with jest.

Closed aplha testing on google play store

I have many dev teams working on multiple features in my app on separate branches. I also have other dev teams working on beta test version in parallel. I haven't used the Google Play Store testing tracks except beta and want to know more about the closed alpha tracks. I did read up on the Google developer help but i think my doubts were not solved. Putting them down below:

  1. Is it possible to publish to alpha and beta tracks simultaneously? For example - usually, in my team there are 2 different version of the apha build as they are being worked upon in parallel by two different groups and a single beta version which is more stable and being tested by a larger group. Is it possible to release these three builds to two apha tracks and one beta track?
  2. What will happen to the beta build If i upload a build to alpha track? Are they independent? Will beta testers see a different version of the app if i upload a build to any of the alpha tracks? Or will these three tracks be separate and maintain their own versions?
  3. Is it possible for a tester to be added to multiple testing tracks? Or be added to multiple tracks of the same type?(e.g - adding the same email id to both the alpha tracks or adding the gmail id to all the 3 testing tracks).
  4. If point 3 is possible, what will happen if i release build to multiple tracks? Will all the builds be visible to the person? How exactly will he/she download the builds from different tracks?

Any help appreciated. Am trying to setup a managed process to accelerate app testing and feedback within the team so that we can have faster iterations

Thanks for the help in advance

Kartikeya

jeudi 27 août 2020

MochaJS: How to call spec level hooks in the global mocha instance?

Is there a way to run a hook before and after each spec? Eg, there are 3 *.spec.js files, the console stdout should print as below..

(I am aware that this can be done in before hooks of the individual spec itself. But that would mean writing a lot of duplicate code in all spec files.)

There are rootHooks but they print at the before and after all the specs have run. My requirement is to print before and after each spec(not before and after the entire suite)

Spec started at : 12:00:00 (<-- called from global spec level beforeHook) 
  ✓ Spec 1 tests
  ✓ ...
  ✓ ...
Spec Ended at : 12:00:10 (<-- called from global spec level afterHook) 

Spec started at : 12:00:11 (<-- called from global spec level beforeHook) 
  ✓ Spec 2 tests
  ✓ ...
  ✓ ...
Spec Ended at : 12:00:15 (<-- called from global spec level afterHook) 

Spec started at : 12:00:15 (<-- called from global spec level beforeHook) 
  ✓ Spec 3 tests
  ✓ ...
  ✓ ...
Spec Ended at : 12:00:20 (<-- called from global spec level afterHook)

TypeError: firebase.analytics is not a function when mocking with jest

I am starting to use Jest for testing my React app, I am writing a basic test and I have an exception. The test code is the following

// __test__/App.test.js
import '@babel/polyfill'
import React from 'react';
import App from '../components/App'
import { render } from '@testing-library/react';

jest.mock('firebase/app')
// The error is the same with or without the following line:
firebase.analytics.mockResolvedValue(null)

it("renders without crashing", () => {
  render(<App />);
});

But when I run npx jest I get this output:

 FAIL  src/__test__/App.test.js
  ● Test suite failed to run

    TypeError: firebase.analytics is not a function

       8 | // Initialize Firebase
       9 | firebase.initializeApp(firebaseConfig);
    > 10 | firebase.analytics();
         |          ^
      11 | 
      12 | const db = firebase.firestore();
      13 | 

The app works as it should outside tests

Testing SP-Initiated Saml 2.0 SSO: is there a IDP that supports dynamic ACS URL?

I'm currently trying to setup tests to test my application's SP-initiated SSO. This test will be run in different environments, and especially in kubernetes as well, where the recipient/destination URL will be dynamic and different (ie: http://localhost:5000/sso, https://k8s-server-1.com/sso, https://k8s-server-2.com/sso, etc.)

I've looked into free developer accounts with OKTA and OneLogin, and it seems neither supports dynamic ACS URLs. Short of investing time writing a mock SAML IDP of some sort, is there any other resources I can use to test my SP-initiated SSO flow?

Can i test a game in unity on ios publish it on android?

I have a game that i want to test it on my iphone device but i want to publish it on android does it makes any difference between the two ? That means the input and the movement and the screen size is all the same ?

test ask how to solve this problem oh my god

테스트 글인데 어떄요 아래는 jaeger 용 go 테스트 코드

What are unit tests, integration tests, smoke tests, and regression tests? What are the differences between them and which tools can I use for each of them?

For example, I use JUnit and NUnit for unit testing and integration testing. Are there any tools for the last two, smoke testing or regression testing?

what's the matter~! what's the matter~!

what's the matter~!what's the matter~!what's the matter~! what's the matter~!what's the matter~! ???


    package main
    
    import (
        "database/sql"
        "errors"
        "fmt"
        "io/ioutil"
        "math/rand"
        "net/http"
        "time"
    
        "github.com/globalsign/mgo"
        "github.com/globalsign/mgo/bson"
    
        // "gopkg.in/mgo.v2"
        // "gopkg.in/mgo.v2/bson"
    
        "github.com/gorilla/mux"
        "github.com/opentracing/opentracing-go"
        "github.com/opentracing/opentracing-go/ext"
        "github.com/opentracing/opentracing-go/log"
    )
    
    func checkError(err error) {
        if err != nil {
            panic(err)
        }
    }
    
    //#################################################
    //router
    //#################################################
    type Mux struct {
        Router *mux.Router
    }
    
    func getRouter() *Mux {
        router := new(Mux)
        router.Router = mux.NewRouter()
    
        router.Router.HandleFunc("/bookstore", getBookStore).Methods("GET")
        router.Router.HandleFunc("/book", getBook).Methods("GET")
        router.Router.HandleFunc("/api/book", getApiBook).Methods("GET")
        router.Router.HandleFunc("/store", getStore).Methods("GET")
        router.Router.HandleFunc("/api/store", getApiStore).Methods("GET")
        router.Router.HandleFunc("/test/{id}", getTest).Methods("GET")
    
        return router
    }
    
    type key interface {
    }
    
    func getTest(w http.ResponseWriter, r *http.Request) {
    
        id := mux.Vars(r)["id"]
        res := "id2 : " + id
        fmt.Println(res)
    
        w.Write([]byte(res))
    }
    
    //#################################################
    //http get
    //#################################################
    func httpGet(url string, w http.ResponseWriter, r *http.Request) (string, error) {
        // fmt.Println("r.Host")
        // fmt.Println(r.Host)
    
        method := "GET"
    
        httpClient := &http.Client{}
        httpReq, err := http.NewRequest("GET", url, nil)
    
        //jaeger
        span, _ := opentracing.StartSpanFromContext(
            r.Context(),
            method+"_"+url,
            ext.SpanKindRPCClient)
    
        span.SetTag(string(ext.Component), "http")
        span.SetTag(string(ext.HTTPUrl), url)
        span.SetTag(string(ext.HTTPMethod), method)
        span.SetTag(string(ext.PeerService), TARGET)
    
        if r != nil {
            span.SetTag(HTTP_REQ_HEADER, GetSpanTagReqHeader(r))
            span.SetTag(HTTP_REQ_BODY, GetSpanTagReqBody(r))
        }
    
        span.LogFields(
            log.String("event", "INFO"),
            log.String("message", "Go test log message"),
        )
    
        defer span.Finish()
    
        opentracing.GlobalTracer().Inject(
            span.Context(),
            opentracing.HTTPHeaders,
            opentracing.HTTPHeadersCarrier(httpReq.Header))
    
        fmt.Println("httpReq.Header : ")
        fmt.Println(httpReq.Header)
        //jaeger
    
        res, err := httpClient.Do(httpReq)
    
        // res, err := http.Get(url)
        if err != nil {
            fmt.Println("Error :", err.Error())
            span.SetTag(string(ext.Error), true)
            span.SetTag(string(ext.HTTPStatusCode), 500)
            span.LogFields(
                log.String("event", "error"),
                log.Object("error.object", err),
                log.String("message", err.Error()))
    
            return "Error: " + err.Error(), err
        }
        defer res.Body.Close()
    
        //jaeger
        span.SetTag(string(ext.HTTPStatusCode), res.StatusCode)
        span.SetTag(HTTP_RES_HEADER, GetSpanTagResHeader(res))
        span.SetTag(HTTP_RES_BODY, GetSpanTagResBody(res))
        if res.StatusCode >= 400 {
            span.SetTag(string(ext.Error), true)
            // w.WriteHeader(res.StatusCode)
        }
        //jaeger
    
        body, _ := ioutil.ReadAll(res.Body)
    
        result := string(body)
        fmt.Println("res from api book : " + result)
    
        return result, nil
    }
    
    //#################################################
    //bookstore
    //#################################################
    func getBookStore(w http.ResponseWriter, r *http.Request) {
        fmt.Println("----------------------------------------------")
        fmt.Println("getBookStore called")
        var result string
    
        //########################
        //##### random error #####
        //########################
        rand.Seed(time.Now().UnixNano())
        i := rand.Intn(100)
        md := i % 10
        fmt.Println("random number:", i, "/ mod:", md)
        if md == 1 {
            fmt.Println("status code:", 400)
            fmt.Println("error msg:", "Random Invalid Param")
            w.WriteHeader(400)
            w.Write([]byte("Random Invalid Param"))
            return
        } else if md == 2 {
            fmt.Println("status code:", 500)
            fmt.Println("error msg:", "Random Server Error")
            w.WriteHeader(500)
            w.Write([]byte("Random Server Error"))
            return
        }
        //##### random error #####
    
        //book
        url := remote + "/book"
        fmt.Println("call remote : " + url)
    
        result, err := httpGet(url, w, r)
        if err != nil {
            w.WriteHeader(500)
            w.Write([]byte(err.Error()))
            return
        }
    
        //self
        result2, err := getBookData()
        if err != nil {
            w.WriteHeader(500)
            w.Write([]byte(err.Error()))
            return
        }
    
        result += "\n" + result2
    
        //store
        url = remote + "/store"
        fmt.Println("call remote : " + url)
    
        result3, err := httpGet(url, w, r)
        if err != nil {
            w.WriteHeader(500)
            w.Write([]byte(err.Error()))
            return
        }
    
        result += "\n" + result3
    
        //self
        result4, err := getStoreData()
        if err != nil {
            w.WriteHeader(500)
            w.Write([]byte(err.Error()))
            return
        }
        result += "\n" + result4
    
        w.Write([]byte(result))
    }
    
    //#################################################
    // book
    //#################################################
    func getBook(w http.ResponseWriter, r *http.Request) {
        fmt.Println("----------------------------------------------")
        fmt.Println("/book called")
        url := remote + "/api/book"
        fmt.Println("call remote : " + url)
    
        //########################
        //##### random error #####
        //########################
        rand.Seed(time.Now().UnixNano())
        i := rand.Intn(100)
        md := i % 10
        fmt.Println("random number:", i, "/ mod:", md)
        if md == 1 {
            fmt.Println("status code:", 400)
            fmt.Println("error msg:", "Random Invalid Param")
            w.WriteHeader(400)
            w.Write([]byte("Random Invalid Param"))
            return
        } else if md == 2 {
            fmt.Println("status code:", 500)
            fmt.Println("error msg:", "Random Server Error")
            w.WriteHeader(500)
            w.Write([]byte("Random Server Error"))
            return
        }
        //##### random error #####
    
        result, err := httpGet(url, w, r)
        if err != nil {
            w.WriteHeader(500)
            w.Write([]byte(err.Error()))
            return
        }
    
        body2, err := getBookData()
        if err != nil {
            w.WriteHeader(500)
            w.Write([]byte(err.Error()))
            return
        }
    
        val := result + "\n" + body2
    
        fmt.Println(string(val))
    
        w.Write([]byte(val))
    }
    
    //#################################################
    // book api
    //#################################################
    func getApiBook(w http.ResponseWriter, r *http.Request) {
        fmt.Println("----------------------------------------------")
        fmt.Println("/api/book called")
    
        res, err := getBookData()
        if err != nil {
            w.WriteHeader(500)
            w.Write([]byte(err.Error()))
            return
        }
    
        fmt.Println(res)
    
        w.Write([]byte(res))
    }
    
    //#################################################
    // book data
    //#################################################
    func getBookData() (string, error) {
        // var connectionString string = fmt.Sprintf("host=%s user=%s password=%s dbname=%s sslmode=disable", HOST, USER, PASSWORD, DATABASE)
        // // Initialize connection object.
        // db, err := sql.Open("postgres", connectionString)
        // checkError(err)
    
        //########################
        //##### random error #####
        //########################
        rand.Seed(time.Now().UnixNano())
        i := rand.Intn(100)
        md := i % 10
        fmt.Println("random number:", i, "/ mod:", md)
        if md == 1 {
            fmt.Println("status code:", 500)
            fmt.Println("error msg:", "Get Book Data Error")
            return "", errors.New("Random Book Data Error")
        }
        //##### random error #####
    
        err := DB.Ping()
        if err != nil {
            return "", errors.New("DB Ping Error")
        }
        // checkError(err)
        // fmt.Println("Successfully created connection to database")
    
        q := "SELECT book_title FROM books;"
        rows, err := DB.Query(q)
        if err != nil {
            return "", errors.New("DB Query Error")
        }
        // checkError(err)
        defer rows.Close()
    
        var res string
        var title string
        for rows.Next() {
            switch err := rows.Scan(&title); err {
            case sql.ErrNoRows:
                fmt.Println("No rows were returned")
            case nil:
                res += title + ", "
            default:
                return "", errors.New("Row Scan Error")
                // checkError(err)
            }
        }
        res = "[from Go]      book : " + res
        return res, nil
    }
    
    //#################################################
    // store
    //#################################################
    func getStore(w http.ResponseWriter, r *http.Request) {
        fmt.Println("----------------------------------------------")
        fmt.Println("/store called")
    
        url := remote + "/api/store"
        fmt.Println("call remote : " + url)
    
        result, err := httpGet(url, w, r)
        if err != nil {
            w.WriteHeader(500)
            w.Write([]byte(result))
            return
        }
    
        body2, err := getStoreData()
        if err != nil {
            w.WriteHeader(500)
            w.Write([]byte(err.Error()))
            return
        }
        val := result + "\n" + body2
    
        fmt.Println(string(val))
    
        w.Write([]byte(val))
    }
    
    //#################################################
    // store api
    //#################################################
    func getApiStore(w http.ResponseWriter, r *http.Request) {
        fmt.Println("----------------------------------------------")
        fmt.Println("/api/store called")
    
        res, err := getStoreData()
        if err != nil {
            w.WriteHeader(500)
            w.Write([]byte(err.Error()))
            return
        }
        fmt.Println(res)
    
        w.Write([]byte(res))
    }
    
    //#################################################
    // store data
    //#################################################
    func getStoreData() (string, error) {
        session, err := mgo.Dial("192.168.10.130")
        if err != nil {
            return "", errors.New("Mongo dial error.")
            // panic(err)
        }
    
        defer session.Close()
    
        session.SetSafe(&mgo.Safe{})
    
        // println("#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@  st1")
        // var st mgo.Stats
        // println("#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@  st2")
        // st = mgo.GetStats
        // println("########## :: Clusters", st.Clusters)
        // println("#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@  ed")
    
        c := session.DB("test").C("stores")
    
        type Store struct {
            NO   int    `bson:"store_no"`
            NAME string `bson:"store_name"`
        }
    
        result := Store{}
        // fmt.Println("Getting  data....")
        iter := c.Find(bson.M{}).Iter()
        var index = 1
    
        var res string
        for iter.Next(&result) {
            // fmt.Printf("current result is [%d] result =%+v\n", index, result)
            res += result.NAME + ", "
            index++
        }
        res = "[from Go]     store : " + res
    
        if err2 := iter.Close(); err2 != nil {
            fmt.Printf("No data\n")
            return "", errors.New("Mongo close error.")
        }
    
        return res, nil
    }

Safari won't work after entering Charles Proxy server and port details on iPhone?

I'm trying to use Charles Proxy to do testing for some app builds for iOS. However, as soon as I enter the server and port information, the phone I'm using for testing can no longer connect to any web pages.

Here are the steps I'm using:

  1. Connect to the same WiFi on both the PC and iPhone.
  2. Open Charles
  3. Stop Windows Proxying
  4. Help -> SSL Proxying -> Install Charles Root Certificate on a Mobile Device or Remote Browser
  5. Open iPhone Settings, navigate to WiFi
  6. Navigate to "Configure Proxy", select Manual.
  7. Enter IP as "Server" and the port following the IP as "Port"

After doing this, the WiFi no longer works so I'm unable to access "chls.pro/ssl" to download the Charles certificate. Anyone have any idea why this could be happening?

Detox or any e2e testing framework with Expo

So there are a few documents out there talking about how Detox and Expo can work together but it seems all of the mare out of date and the process might be vastly difference. Has anyone gotten it to work with the latest Expo SDK (that or any other e2e framework?)

How to compare object values in a config to hrefs on a website

This is a follow-up to the question I previously posted here

In this question, I am trying to test the href values on the website to what is stored in the config file.

URL: https://wdwthemeparks.com

Config file (located at Resources/config.json)

{
    "url": "https://wdwthemeparks.com",
    "topMenuNav": {
        "All": "/all/",
        "News": "/news/",
        "Press Releases": "/press/",
        "Rumors": "/rumors/",
        "About": "/about/",
        "Contact": "/contact/",
        "Refurbishments": "/refurbishments/"
    }
}

Selectors located at Objects/header.js

import { Selector, t } from 'testcafe';

class Header {

    constructor() {
        this.topMenuNav = Selector('.top-header-menu')
        this.topMenuNavItem = Selector(this.topMenuNav).find('a');
    }
}

export default new Header();

Tests located at Tests/topMenu.js

import { Selector } from 'testcafe';
import Header from '../Objects/header';

const config = require('../Resources/config.json');

fixture `Check Top Menu`
    .page(config.url)
    .beforeEach( async t => {
        await t.maximizeWindow();
    });

test
    .meta({ desktop: 'true'})
    ('Check Top Menu Items', async t => {

        const topMenuNavKeys = Object.keys(config.topMenuNav);
        const topMenuNavValues = Object.values(config.topMenuNav);

        await t.expect(Header.topMenuNav.visible).ok('Top Menu Nav is NOT visible');
        
        for (const key of topMenuNavKeys) {
            await t.expect(Header.topMenuNavItem.withText(key).exists).ok(`"${key}" Top Menu Nav key does NOT match config`);
          }

// THE PROBLEM I AM HAVING IS HERE IN THIS PART OF THE CODE
          for (const value of topMenuNavValues) {
            await t.expect(Header.topMenuNavItem.getAttribute('href')).contains(value, `"${value}" Top Menu Nav value does NOT match config`);
          }
});

I get the following error message from TestCafe:

× Check Top Menu Items

   1) AssertionError: "/news/" Top Menu Nav value does NOT match config: expected 'https://wdwthemeparks.com/all/' to include '/news/'

      + expected - actual

      -'https://wdwthemeparks.com/all/'
      +undefined


      Browser: Chrome 85.0.4183.83 / Windows 10

         32 |                   await t.expect(Header.topMenuNavItem.withText(key).exists).ok(`"${key}" Top Menu Nav key does NOT match config`);
         33 |             }
         34 |
         35 |             for (const value of topMenuNavValues) {
         36 |                   console.log(Header.topMenuNavItem.getAttribute('href'));
       > 37 |                   await t.expect(await Header.topMenuNavItem.getAttribute('href')).contains(value, `"${value}" Top Menu Nav value does NOT match config`);
         38 |             }
         39 |});
         40 |

         at <anonymous> (C:\Users\J\Repos\wdwthemeparks-automation\Tests\topMenu.js:37:69)



 1/1 failed (7s)

I'm not sure what I'm doing wrong.