logic – Question about a puzzle in ch. 2 of “to mock a mockingbird”

In chapter 2, the author introduced Nelson Goodman Principle, which says if you ask someone who either always lies or always tells the truth: “Are you the type who could claim A is true?”, he/she will always tell the truthfulness of A. So for problem 3, the given correct answer is “Is Arthur truthful?”, which is supposed to be equivalent to the sentence formulated with Nelson Goodman Principle: “Are you the type who could claim that you are Arthur?”

However, it is really hard for me see the equivalence of the two formulations. I mean, the consequences of the two formulations are the same. But on the surface, I couldn’t tell the equivalence just by transforming the text from one to the other. Can anyone help me to understand it? Thank you!

PS: Ch. 2 Problem 3 in the book: you meet two identical twins, one of whom is Arthur. One of the two always lies. The other always tells the truth. You have no idea who is who or who lies who doesn’t. You are only allowed to ask one question with 3 words to either of the two in order to find out who is Arthur.

Java unit test Mock simulate file

I made a little game called Space Invaders, a working example you can find here: https://github.com/Koffiemolen/SpaceInvaders.git Go for the second branch, SpaceInvadersV2.

In the module dataaccess I created a Class HighscoreStore. This reads and writes to a file.
The class GamePanel in the module userinterface uses this class.

I want to test layer separation, so I want to make a mock for it. So the unit test needs to feed the GamePanel class with data but it needs to be generated in the unit test so I can test without using the file that contains the highscore.

I have the feeling that I’m going in circles and can’t get started. Do I need to make a copy of the GamePanel class and call it MockGamePanel, create a mock class from HighscoreStore called MockHighscore class that implements the same interface that HighscoreStore uses and let it generate data?

The interface is in the moduel business layer, package dataprovider.interfaces, HighscoreProvider

package dataprovider.interfaces;

import logic.entities.Highscore;

public interface HighscoreProvider {
    Highscore getHighScore();
    void setHighScore(Highscore highscore);
}

Or is it the other way around?

magento2 – How to create mock checkout without real credit card authorization?

I am new to Magento and working now on creating a demo application for a task I have to do.
As part of my demo, I have to create a full-flow checkout process, where a customer can add a product to the cart and proceed to the checkout page, there he/she can enter fake credit card information and complete the “transaction”.

I’m wondering how can I create a “fake” checkout process, which contains a checkout form for credit card details, but does nothing more than sending the CC to the backend? (also, no authorization process is needed in the backend).

The demo application, of course, won’t be published and will be used for internal and private usage only.

python – Universal class for proxifying poplib, imaplib and smtplib. Lame inheritance or mock or something else?

This is wrapper for POP3, POP3_SSL, IMAP4, IMAP4_SSL, SMTP and SMTP_SSL classes which let them work through proxies. For creating socket with proxy I’ve used PySocks.

Code:

from imaplib import IMAP4, IMAP4_SSL, IMAP4_PORT, IMAP4_SSL_PORT
from poplib import POP3, POP3_SSL, POP3_PORT, POP3_SSL_PORT
from smtplib import SMTP, SMTP_SSL, SMTP_PORT, SMTP_SSL_PORT
from socks import create_connection, PROXY_TYPE_HTTP, PROXY_TYPE_SOCKS4, PROXY_TYPE_SOCKS5
import socket
import sys
from urllib.parse import urlparse
from collections import namedtuple

def imap_before_connection(self, *args):
    sys.audit("imaplib.open", self, self.host, self.port)

def smtp_before_connection(self, host, port):
    if self.debuglevel > 0:
        self._print_debug('connect: to', (host, port), self.source_address)

def pop_before_connection(*args):
    pass

DEFAULT_SETTINGS = {
    POP3_SSL: (POP3_SSL_PORT, pop_before_connection),
    IMAP4_SSL: (IMAP4_SSL_PORT, imap_before_connection),
    SMTP_SSL: (SMTP_SSL_PORT, smtp_before_connection),
    POP3: (POP3_PORT, pop_before_connection),
    IMAP4: (IMAP4_PORT, imap_before_connection),
    SMTP: (SMTP_PORT, smtp_before_connection)
}

def proxify(base_type):
    for type_, (default_port, before_connection) in DEFAULT_SETTINGS.items():
        if issubclass(base_type, type_):
            break
    else:
        raise TypeError(f"Can't proxify {base_type}")

    class Proxified(base_type):
        Proxy = namedtuple("Proxy", ("host", "port", "username", "password", "proxy_type", "rdns"))
        on_before_connection = before_connection

        @staticmethod
        def parse_proxy_string(proxy_string):
            if not proxy_string:
                return None

            parsed = urlparse(proxy_string)
            _scheme = parsed.scheme.lower()
            if _scheme in {"http", "https"}:
                proxy_type, remote_dns = PROXY_TYPE_HTTP, True
            elif _scheme in {"socks4", "socks4a"}:
                proxy_type, remote_dns = PROXY_TYPE_SOCKS4, _scheme.endswith("a")
            elif _scheme in {"socks5", "socks5h"}:
                proxy_type, remote_dns = PROXY_TYPE_SOCKS5, _scheme.endswith("h")
            else:
                raise ValueError(f'"{_scheme}" is not supported proxy type')

            return Proxified.Proxy(parsed.hostname, parsed.port, parsed.username, parsed.password,
                                   proxy_type, remote_dns)

        def __init__(self, host="", port=default_port, *args, **kwargs):
            self.proxy = self.parse_proxy_string(kwargs.pop("proxy", ""))

            super().__init__(host, port, *args, **kwargs)

        def _create_socket(self, timeout):  # used in POP3 and IMAP
            return self._get_socket(self.host, self.port, timeout)

        def _get_socket(self, host, port, timeout):  # used in SMTP
            if timeout is not None and not timeout:
                raise ValueError('Non-blocking socket (timeout=0) is not supported')

            self.on_before_connection(self, host, port)

            if not self.proxy:
                sock = socket.create_connection(
                    (host, port),
                    timeout,
                    getattr(self, "source_address", None)
                )
            else:
                sock = create_connection(  # socks.create_connection
                    (host, port),
                    timeout,
                    getattr(self, "source_address", None),
                    self.proxy.proxy_type,
                    self.proxy.host,
                    self.proxy.port,
                    self.proxy.rdns,
                    self.proxy.username,
                    self.proxy.password
                )

            ssl_context = getattr(self, "context", None) or getattr(self, "ssl_context", None)
            if ssl_context:
                return ssl_context.wrap_socket(sock, server_hostname=host)
            else:
                return sock

    return Proxified

Usage:

from imaplib import IMAP4, IMAP4_SSL
from poplib import POP3, POP3_SSL
from smtplib import SMTP, SMTP_SSL

mail, mail_pass = "email@example.com", "password"
http_proxy = "http://username:password@127.0.0.1:8080"
pop_server = "pop.example.com"
imap_server = "imap.example.com"
smtp_server = "smtp.example.com"

pop_handler = proxify(POP3)(pop_server, proxy=http_proxy)
pop_secure_handler = proxify(POP3_SSL)(pop_server, proxy=http_proxy)
imap_handler = proxify(IMAP4)(imap_server, proxy=http_proxy)
imap_secure_handler = proxify(IMAP4_SSL)(imap_server, proxy=http_proxy)
smtp_handler = proxify(SMTP)(smtp_server, proxy=http_proxy)
smtp_secure_handler = proxify(SMTP_SSL)(smtp_server, proxy=http_proxy)

It works and works good but I look on this code and .. I feel that solution is a bit cumbersome.

Could you please take a look on it and point me what I’ve done in “wrong” way and suggest the correct way. Thanks.

UPD.

There’s also another option which looks much better (imho), but it uses mock.patch() and I’m not quite sure that it’s okay to use it in production.

Code:

from poplib import POP3
from imaplib import IMAP4
from smtplib import SMTP
from functools import wraps, partial
from collections import namedtuple
from unittest.mock import patch
from urllib.parse import urlparse
from socks import create_connection, PROXY_TYPE_HTTP, PROXY_TYPE_SOCKS4, PROXY_TYPE_SOCKS5

def mock_if_proxy(method):
    @wraps(method)
    def wrapper(self, *args, **kwargs):
        if self.proxy:
            with patch("socket.create_connection",
                       partial(create_connection, proxy_type=self.proxy.proxy_type, proxy_addr=self.proxy.host,
                               proxy_port=self.proxy.port, proxy_rdns=self.proxy.rdns,
                               proxy_username=self.proxy.username, proxy_password=self.proxy.password)):
                return method(self, *args, **kwargs)
        else:
            return method(self, *args, **kwargs)
    return wrapper

def proxify(base_type):
    if not issubclass(base_type, (POP3, IMAP4, SMTP)):
        raise TypeError(f"Can't proxify {base_type}")

    class Proxified(base_type):
        # skipped Proxy and parse_proxy_string() declaration, it's the same

        if hasattr(base_type, "_create_socket"):
            _create_socket = mock_if_proxy(base_type._create_socket)
        if hasattr(base_type, "_get_socket"):
            _get_socket = mock_if_proxy(base_type._get_socket)

        def __init__(self, *args, **kwargs):
            self.proxy = self.parse_proxy_string(kwargs.pop("proxy", ""))

            super().__init__(*args, **kwargs)

    return Proxified

Maybe you could advice me a better way without mock?

Telegram refuse to get the GPS location set by “mock gps” applications

I’d want to see how “mock GPS” applications are working, so I installed “Fake GPS Location” from PlayStore, and works flawlessly (obviously I set such app in the developer options to mock the gps location). In facts both Google Maps and Whatsapp report the GPS location which I set, but Telegram doesn’t get this setting: still reports my real location.
I tried to set the GPS accuracy, in Android’s settings, to low and high, I also rebooted the phone, with no dice.

Why? There is some other workaround that I miss?

java – Mock returning null

I try to test my service class but it return error, nullPointerException. service and repository return null. I cannot figure out why.

import com.foodcrunch.foodster.recipemanager.repository.Repository;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;

import java.util.Optional;

import static org.mockito.Mockito.when;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.times;

@RunWith(MockitoJUnitRunner.class)
public class ServiceTest {

    @InjectMocks
    private Service service; // return null

    @Mock
    private Repository repository; //return null

    @Test
    public void test() {
      // test implementation 
    }
}

javascript – How to mock a function with callback parameters in JestJS

My NodeJS app has a function readFilesJSON() that calls fs.readFile(), which of course invokes a callback with the parameters (err,data). The Jest unit test needs to walk both the error path and the data path.

My solution was to mock the call to fs.readFile() (see below). The mock function simply passes error or data based on test logic. This approach works when there is only one function being tested. The trouble I am seeing occurs when there are multiple functions that call fs.readFile(). Jest runs all the tests concurrently and the asynchronous nature of the functions mean that there is no guaranteed ordering to the calls to fs.readFile(). This non-deterministic behavior wrecks both the error/data logic and the parameter-checking logic using toHaveBeenCalledWith().

Does Jest provide a mechanism for managing independent usage of the mocks?

function readFilesJSON(files,done) {
    let index = 0;
    readNextFile();
    function readNextFile() {
        if( index === files.length ) {
            done();
        }
        else {
            let filename = files(index++);
            fs.readFile( filename, "utf8", (err,data) => {
                if(err) {
                    console.err(`ERROR: unable to read JSON file ${filename}`);
                    setTimeout(readNextFile);
                }
                else {
                    // parse the JSON file here
                    // ...
                    setTimeout(readNextFile);
                }
            });
        }
    }
}

The injected function setup looks like this:

jest.spyOn(fs, 'readFile')
    .mockImplementation(mockFsReadFile)
    .mockName("mockFsReadFile");

function mockFsReadFile(filename,encoding,callback) {
    // implement error/data logic here
}

angular – Como puedo hacer un mock de los datos de mi tienda en Shopify para desarrollar offline

Estoy desarrollando una app Storefront para Shopify y quisiera saber si hay alguna manera de tener los datos de mi tienda (o de una tienda fake) en mi PC para poder desarrollar localmente sin tener que estar accediendo a la API de Shopify online.

El frontend lo estoy implementando en Angular y la API de Shopify que estoy accediendo es la GraphQL.