Thursday, 1 July 2021

How to use pytest to check that Error is NOT raised

Let's assume we have smth like that :

import py, pytest

ERROR1 = ' --- Error : value < 5! ---'
ERROR2 = ' --- Error : value > 10! ---'

class MyError(Exception):
    def __init__(self, m):
        self.m = m

    def __str__(self):
        return self.m

def foo(i):
    if i < 5:
        raise MyError(ERROR1)
    elif i > 10:
        raise MyError(ERROR2)
    return i


# ---------------------- TESTS -------------------------
def test_foo1():
    with pytest.raises(MyError) as e:
        foo(3)
    assert ERROR1 in str(e)

def test_foo2():
    with pytest.raises(MyError) as e:
        foo(11)
    assert ERROR2 in str(e)

def test_foo3():
        ....
        foo(7)
         ....

Q: How can I make test_foo3() to test, that no MyError is raised? It's obvious, that i could just test :

def test_foo3():
    assert foo(7) == 7

but i want to test that via pytest.raises(). Is is possible someway? For example: in a case, that function "foo" has no return-value at all,

def foo(i):
    if i < 5:
        raise MyError(ERROR1)
    elif i > 10:
        raise MyError(ERROR2)

it could make sense to test this way, imho.



from How to use pytest to check that Error is NOT raised

How to copy, cut folder from one folder to another using ctrl+c and ctrl+v

My title can look a little ambiguous, so here is an explanation.

Professional IDE like Pycharm or Visual Studio Code allow copying the folder, navigating to a specific directory and pasting it there. I would also like to implement that.

But in my case, shutil.copytree needs 2 arguments - source folder and destination folder.

So is there any way that one can copy a folder, navigate through the explorer, click paste or press ctrl+v and the folder will be copied or pasted there, unlike shutil.copytree where the user already need to provide the path?

Currently, I have a code that will copy the folder name to the clipboard.

import os
import tkinter as tk
import tkinter.ttk as ttk
import clipboard
class App(tk.Frame):
    def __init__(self, master, path):
        tk.Frame.__init__(self, master)
        self.tree = ttk.Treeview(self)
        ysb = ttk.Scrollbar(self, orient='vertical', command=self.tree.yview)
        xsb = ttk.Scrollbar(self, orient='horizontal', command=self.tree.xview)
        self.tree.configure(yscroll=ysb.set, xscroll=xsb.set)
        self.tree.heading('#0', text=path, anchor='w')

        abspath = os.path.abspath(path)
        root_node = self.tree.insert('', 'end', text=abspath, open=True)
        self.process_directory(root_node, abspath)

        self.tree.bind("<Control-c>",self.copy_to_clipboard)
        self.tree.grid(row=0, column=0)
        ysb.grid(row=0, column=1, sticky='ns')
        xsb.grid(row=1, column=0, sticky='ew')
        self.grid()
    def copy_to_clipboard(self,event,*args):
        item = self.tree.identify_row(event.y)
        clipboard.copy(self.tree.item(item,"text"))
    def process_directory(self, parent, path):
        try:
            for p in os.listdir(path):
                abspath = os.path.join(path, p)
                isdir = os.path.isdir(abspath)
                oid = self.tree.insert(parent, 'end', text=p, open=False)
                if isdir:
                    self.process_directory(oid, abspath)
        except PermissionError:
            pass

root = tk.Tk()
path_to_my_project = 'C:\\Users\\91996\\Documents'
app = App(root, path=path_to_my_project)
app.mainloop()


from How to copy, cut folder from one folder to another using ctrl+c and ctrl+v

How to get historic distance date from Google FIT in android?

I am trying to get historic distance data of a user by passing a start time and an end time to google FIT android API.

I am posting this query after checking all the related article available in stack overflow.

/**
 * Returns a {@link DataReadRequest}.
 */
public DataReadRequest queryFitnessStepData(String startTime, String endTime) {
    long startVal = convertDateStringtoEpoch(startTime, true);
    long endVal = convertDateStringtoEpoch(endTime, false);

    DataSource datasource = new DataSource.Builder()
            .setAppPackageName("com.google.android.gms")
            .setDataType(DataType.TYPE_STEP_COUNT_DELTA)
            .setType(DataSource.TYPE_DERIVED)
            .setStreamName("distance_delta")
            .build();

    return new DataReadRequest.Builder()
            .aggregate(datasource)
            .bucketByTime(1, TimeUnit.DAYS)
            .setTimeRange(startVal, endVal, TimeUnit.MILLISECONDS)
            .build();
}

private void readHistoryDistanceData(String strDate, String endDate) {
readRequest = queryFitnessStepData(strDate, endDate);

FitnessOptions fitnessOptions =
            FitnessOptions.builder()
                    .addDataType(DataType.TYPE_DISTANCE_DELTA, FitnessOptions.ACCESS_READ)
                    .addDataType(DataType.AGGREGATE_DISTANCE_DELTA, FitnessOptions.ACCESS_READ)
                    .build();

    if (GoogleSignIn.hasPermissions(GoogleSignIn.getLastSignedInAccount(requireActivity()), fitnessOptions)) {
        Fitness.getHistoryClient(requireActivity(), Objects.requireNonNull(GoogleSignIn.getLastSignedInAccount(requireActivity())))
                .readData(readRequest)
                .addOnSuccessListener(
                        new OnSuccessListener<DataReadResponse>() {
                            @Override
                            public void onSuccess(DataReadResponse dataReadResponse){ 
                                  //parse data
                                }
                              }
                          }
                     }

However on running this code I am unable to get any data related to user's distance. I have all the permission like ACCESS_FINE_LOCATION and ACTIVITY_RECOGNITION in place.

Any help would be appreciated.



from How to get historic distance date from Google FIT in android?